We sacrifice by not doing any other technology, so that you get the best of Magento.

We sacrifice by not doing any other technology, so that you get the best of Magento.

    Add & Remove Product in Comparison List through Custom Controller

    As per my requirements, I have created this type of controller. So basically you need 2 types of Controller.

    The first one for adding the product in the comparison list and second for removing the product from the comparison list.

    Step 1. Please create one controller for Add Product as below.

    <?php
    
    namespace MagemonkeysCompareajaxControllerIndex;
    
    use MagentoCatalogApiProductRepositoryInterface;
    use MagentoFrameworkDataFormFormKeyValidator;
    use MagentoFrameworkViewResultPageFactory;
    use MagentoFrameworkControllerResultJsonFactory;
    use MagentoFrameworkExceptionNoSuchEntityException;
    use MagentoFrameworkEventManagerInterface as EventManager;
    
    class AddCompare extends MagentoFrameworkAppActionAction
    {
        /**
         * @var JsonFactory
         */
        protected $resultJsonFactory;
    
        /**
        * @var EventManager
        */
        private $eventManager;
    
        /**
         * Customer id
         *
         * @var null|int
         */
        protected $_customerId = null;
    
        /**
         * Catalog session
         *
         * @var MagentoCatalogModelSession
         */
        protected $_catalogSession;
    
        /**
         * Catalog product compare list
         *
         * @var MagentoCatalogModelProductCompareListCompare
         */
        protected $_catalogProductCompareList;
    
        /**
         * Customer visitor
         *
         * @var MagentoCustomerModelVisitor
         */
        protected $_customerVisitor;
    
        /**
         * Customer session
         *
         * @var MagentoCustomerModelSession
         */
        protected $_customerSession;
    
        /**
         * Item collection factory
         *
         * @var MagentoCatalogModelResourceModelProductCompareItemCollectionFactory
         */
        protected $_itemCollectionFactory;
    
        /**
         * Compare item factory
         *
         * @var MagentoCatalogModelProductCompareItemFactory
         */
        protected $_compareItemFactory;
    
        /**
         * @var MagentoStoreModelStoreManagerInterface
         */
        protected $_storeManager;
    
        /**
         * @var Validator
         */
        protected $_formKeyValidator;
    
        /**
         * @var MagentoFrameworkViewResultPageFactory
         */
        protected $resultPageFactory;
    
        /**
         * @var ProductRepositoryInterface
         */
        protected $productRepository;
    
        protected $_compareHelper;
    
        protected $_urlInterface;
    
        protected $_blockFactory;
    
        public function __construct(
            MagentoFrameworkAppActionContext $context,
            MagentoCatalogModelProductCompareItemFactory $compareItemFactory,
            MagentoCatalogModelResourceModelProductCompareItemCollectionFactory $itemCollectionFactory,
            MagentoCustomerModelSession $customerSession,
            MagentoCustomerModelVisitor $customerVisitor,
            MagentoCatalogModelProductCompareListCompare $catalogProductCompareList,
            MagentoCatalogModelSession $catalogSession,
            MagentoStoreModelStoreManagerInterface $storeManager,
            Validator $formKeyValidator,
            PageFactory $resultPageFactory,
            ProductRepositoryInterface $productRepository,
            JsonFactory $resultJsonFactory,
            EventManager $eventManager,
            MagentoCatalogHelperProductCompare $compareHelper,
            MagentoFrameworkUrlInterface $urlInterface,
            MagentoFrameworkViewElementBlockFactory $blockFactory
        ) {
            $this->resultJsonFactory = $resultJsonFactory;
            $this->_storeManager = $storeManager;
            $this->_compareItemFactory = $compareItemFactory;
            $this->_itemCollectionFactory = $itemCollectionFactory;
            $this->_customerSession = $customerSession;
            $this->_customerVisitor = $customerVisitor;
            $this->_catalogProductCompareList = $catalogProductCompareList;
            $this->_catalogSession = $catalogSession;
            $this->_formKeyValidator = $formKeyValidator;
            $this->resultPageFactory = $resultPageFactory;
            $this->productRepository = $productRepository;
            $this->eventManager = $eventManager;
            $this->_compareHelper = $compareHelper;
            $this->_urlInterface = $urlInterface;
            $this->_blockFactory = $blockFactory;
            parent::__construct($context);
        }
    
        public function execute()
        {
            $resultJson = $this->resultJsonFactory->create();
    
            $result = array();
            $error = true;
            $message = '';
    
            // TODO: Validate this is a POST request.
    
            $count = $this->_compareHelper->getItemCount();
            if($count >= 4) {
                $message = __('You can add the compared products under 4 item(s)');
                $error = true;
                return $resultJson->setData([
                    'message' => $message,
                    'data' => $result,
                    'error' => $error
                ]);
            }
    
            $productId = (int)$this->getRequest()->getParam('product');
            if ($productId && ($this->_customerVisitor->getId() || $this->_customerSession->isLoggedIn())) {
                $storeId = $this->_storeManager->getStore()->getId();
                try {
                    $product = $this->productRepository->getById($productId, false, $storeId);
                } catch (NoSuchEntityException $e) {
                    $product = null;
                    $message = __('Product does not exist');
                    $error = true;
                }
    
                if ($product) {
                    $this->_catalogProductCompareList->addProduct($product);
                    $this->_eventManager->dispatch('catalog_product_compare_add_product', ['product' => $product]);
                }
    
                $this->_objectManager->get('MagentoCatalogHelperProductCompare')->calculate();
                $html = '';
                if($this->_compareHelper->hasItems()){ 
                    $compItem = $this->_compareHelper->getItemCollection();
                    $i = 1;
                    $responseArray = array();
                    foreach($compItem->getData() as $comitem){
                        $productNew = $this->_objectManager->get('MagentoCatalogModelProduct')->load($comitem['entity_id']);
                        $imageBlock = $this->_blockFactory->createBlock('MagentoCatalogBlockProductListProduct');
                        $productImage = $imageBlock->getImage($productNew, 'product_comparison_list');
                        $imageUrl = $productImage->getImageUrl();
                        $responseArray[$i]['id'] = $comitem["entity_id"];
                        $responseArray[$i]['url'] = $imageUrl;
                        $i++;
                    }
    
                    for ($j = 1; $j <= 4; $j++)
                    {
                        if(isset($responseArray[$j]))
                        {
                            $html .= '<div class="compare-item active" data-itemid="'.$responseArray[$j]['id'].'">
                                <div class="compare-item-number">'. $j .'</div>
                                <a class="compare-item-remove removecompareajaxlink" href="javascript:void(0)" data-productid="'.$responseArray[$j]['id'].'" data-url="'. $this->_urlInterface->getUrl().'compareajax/index/removeCompare/product/'.$responseArray[$j]['id'] .'?isAjax=true"><i class="fa fa-remove"></i></a>
                                <img src="'. $responseArray[$j]['url'] .'" class="imageCompare" />
                            </div>';
                        }
                        else
                        {
                            $html .= '<div class="compare-item active" data-itemid="">
                                <div class="compare-item-number">'. $j .'</div>
                            </div>';
                        }
                    }
                }
                $message = __('Product successfully added in comparison list');
                $result = array('html'=>$html,'id'=>$productId);
                $error = false;
            }
    
            return $resultJson->setData([
                        'message' => $message,
                        'data' => $result,
                        'error' => $error
            ]);
        }
    }

    Step 2. Please create another controller for removing the product as below.

    <?php
    
    namespace MagemonkeysCompareajaxControllerIndex;
    
    use MagentoCatalogApiProductRepositoryInterface;
    use MagentoFrameworkDataFormFormKeyValidator;
    use MagentoFrameworkViewResultPageFactory;
    use MagentoFrameworkControllerResultJsonFactory;
    use MagentoFrameworkExceptionNoSuchEntityException;
    use MagentoFrameworkEventManagerInterface as EventManager;
    
    class RemoveCompare extends MagentoFrameworkAppActionAction
    {
        /**
         * @var JsonFactory
         */
        protected $resultJsonFactory;
    
        /**
        * @var EventManager
        */
        private $eventManager;
    
        /**
         * Customer id
         *
         * @var null|int
         */
        protected $_customerId = null;
    
        /**
         * Catalog session
         *
         * @var MagentoCatalogModelSession
         */
        protected $_catalogSession;
    
        /**
         * Catalog product compare list
         *
         * @var MagentoCatalogModelProductCompareListCompare
         */
        protected $_catalogProductCompareList;
    
        /**
         * Customer visitor
         *
         * @var MagentoCustomerModelVisitor
         */
        protected $_customerVisitor;
    
        /**
         * Customer session
         *
         * @var MagentoCustomerModelSession
         */
        protected $_customerSession;
    
        /**
         * Item collection factory
         *
         * @var MagentoCatalogModelResourceModelProductCompareItemCollectionFactory
         */
        protected $_itemCollectionFactory;
    
        /**
         * Compare item factory
         *
         * @var MagentoCatalogModelProductCompareItemFactory
         */
        protected $_compareItemFactory;
    
        /**
         * @var MagentoStoreModelStoreManagerInterface
         */
        protected $_storeManager;
    
        /**
         * @var Validator
         */
        protected $_formKeyValidator;
    
        /**
         * @var MagentoFrameworkViewResultPageFactory
         */
        protected $resultPageFactory;
    
        /**
         * @var ProductRepositoryInterface
         */
        protected $productRepository;
    
        protected $_compareHelper;
    
        protected $_urlInterface;
    
        protected $_blockFactory;
    
        public function __construct(
            MagentoFrameworkAppActionContext $context,
            MagentoCatalogModelProductCompareItemFactory $compareItemFactory,
            MagentoCatalogModelResourceModelProductCompareItemCollectionFactory $itemCollectionFactory,
            MagentoCustomerModelSession $customerSession,
            MagentoCustomerModelVisitor $customerVisitor,
            MagentoCatalogModelProductCompareListCompare $catalogProductCompareList,
            MagentoCatalogModelSession $catalogSession,
            MagentoStoreModelStoreManagerInterface $storeManager,
            Validator $formKeyValidator,
            PageFactory $resultPageFactory,
            ProductRepositoryInterface $productRepository,
            JsonFactory $resultJsonFactory,
            EventManager $eventManager,
            MagentoCatalogHelperProductCompare $compareHelper,
            MagentoFrameworkUrlInterface $urlInterface,
            MagentoFrameworkViewElementBlockFactory $blockFactory
        ) {
            $this->resultJsonFactory = $resultJsonFactory;
            $this->_storeManager = $storeManager;
            $this->_compareItemFactory = $compareItemFactory;
            $this->_itemCollectionFactory = $itemCollectionFactory;
            $this->_customerSession = $customerSession;
            $this->_customerVisitor = $customerVisitor;
            $this->_catalogProductCompareList = $catalogProductCompareList;
            $this->_catalogSession = $catalogSession;
            $this->_formKeyValidator = $formKeyValidator;
            $this->resultPageFactory = $resultPageFactory;
            $this->productRepository = $productRepository;
            $this->eventManager = $eventManager;
            $this->_compareHelper = $compareHelper;
            $this->_urlInterface = $urlInterface;
            $this->_blockFactory = $blockFactory;
            parent::__construct($context);
        }
    
        public function execute()
        {
            $resultJson = $this->resultJsonFactory->create();
    
            $result = array();
            $error = true;
            $message = '';
    
            // TODO: Validate this is a POST request.
    
            $productId = (int)$this->getRequest()->getParam('product');
            if ($productId) {
                $storeId = $this->_storeManager->getStore()->getId();
                try {
                    $product = $this->productRepository->getById($productId, false, $storeId);
                } catch (NoSuchEntityException $e) {
                    $product = null;
                    $message = __('Product does not exist');
                    $error = true;
                }
    
                if ($product) {
                    $item = $this->_compareItemFactory->create();
                    if ($this->_customerSession->isLoggedIn()) {
                        $item->setCustomerId($this->_customerSession->getCustomerId());
                    } elseif ($this->_customerId) {
                        $item->setCustomerId($this->_customerId);
                    } else {
                        $item->addVisitorId($this->_customerVisitor->getId());
                    }
    
                    $item->loadByProduct($product);
    
                    if ($item->getId()) {
                        $item->delete();
                        $productName = $this->_objectManager->get(MagentoFrameworkEscaper::class)
                            ->escapeHtml($product->getName());
                        $message = __('You removed product %1 from the comparison list.', $productName);
                        $this->_eventManager->dispatch('catalog_product_compare_remove_product',['product' => $item]);
                        $this->_objectManager->get('MagentoCatalogHelperProductCompare')->calculate();
                    }
    
                    $html = '';
                    if($this->_compareHelper->hasItems()){ 
                        $compItem = $this->_compareHelper->getItemCollection();
                        $i = 1;
                        $responseArray = array();
                        foreach($compItem->getData() as $comitem){
                            $productNew = $this->_objectManager->get('MagentoCatalogModelProduct')->load($comitem['entity_id']);
                            $imageBlock = $this->_blockFactory->createBlock('MagentoCatalogBlockProductListProduct');
                            $productImage = $imageBlock->getImage($productNew, 'product_comparison_list');
                            $imageUrl = $productImage->getImageUrl();
                            $responseArray[$i]['id'] = $comitem["entity_id"];
                            $responseArray[$i]['url'] = $imageUrl;
                            $i++;
                        }
    
                        for ($j = 1; $j <= 4; $j++)
                        {
                            if(isset($responseArray[$j]))
                            {
                                $html .= '<div class="compare-item active" data-itemid="'.$responseArray[$j]['id'].'">
                                    <div class="compare-item-number">'. $j .'</div>
                                    <a class="compare-item-remove removecompareajaxlink" href="javascript:void(0)" data-productid="'.$responseArray[$j]['id'].'" data-url="'. $this->_urlInterface->getUrl().'compareajax/index/removeCompare/product/'.$responseArray[$j]['id'] .'?isAjax=true"><i class="fa fa-remove"></i></a>
                                    <img src="'. $responseArray[$j]['url'] .'" class="imageCompare" />
                                </div>';
                            }
                            else
                            {
                                $html .= '<div class="compare-item active" data-itemid="">
                                    <div class="compare-item-number">'. $j .'</div>
                                </div>';
                            }
                        }
                    }
                    $message = __('You removed product from the comparison list.');
                    $result = array('html'=>$html,'id'=>$productId);
                    $error = false;
                }
    
            }
    
            return $resultJson->setData([
                        'message' => $message,
                        'data' => $result,
                        'error' => $error
            ]);
        }
    }

    You can execute and modify these controllers as per your requirements.

    Magento 2 set custom attribute value from Quote item to Order item

    Please follow below steps to assign order item value from the quote item.

    step 1) Create a di.xml under app/code/Vendor/Module/etc/di.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="MagentoQuoteModelQuoteItemToOrderItem">
            <plugin name="vendor_mymodule_sales_quote_item_order_item" type="VendorModulePluginSetOrderItemValue" />
        </type>    
    </config>

    step 2) Create the plugin file app/code/Vendor/Module/Plugin/SetOrderItemValue.php

    <?php
    namespace VendorModulePlugin;
    use MagentoFrameworkSerializeSerializerInterface;
    
    class SetOrderItemValue
    {
        public function aroundConvert(MagentoQuoteModelQuoteItemToOrderItem $subject, callable $proceed, $quoteItem, $data)
        {
            $orderItem = $proceed($quoteItem, $data);
            $quotecustomattribute = $quoteItem->getMyCustomAttribite();
            $orderItem->setMyCustomAttribite($quotecustomattribute);
            return $orderItem;
        }
    }

     

    Magento2 get customer group in system xml

    By using the below code, we can get customer group multi-select option with the help of system.xml.

    We can get all Customer group by system.xml in System -> Configuration Section of admin.

    Create system.xml file,
    Path, app/code/Magemonkeys/Customer/etc/adminhtml/system.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
        <system>
            <section id="catalog">
                <group id="customer_group" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    <field id="list" translate="label" type="multiselect" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="0">
                        <label>Customer Groups</label>
                        <source_model>MagemonkeysCustomerModelAdminhtmlSystemConfigSourceCustomerGroup</source_model>
                        <can_be_empty>1</can_be_empty>
                    </field>
                </group>
            </section>
        </system>
    </config>

    You need to get  all customer group using a Model file

    Create Group.php file,
    Path, app/code/Magemonkeys/Customer/Model/Adminhtml/System/Config/Source/Customer/Group.php

    <?php
    namespace MagemonkeysCustomerModelAdminhtmlSystemConfigSourceCustomer;
    
    class Group implements MagentoFrameworkOptionArrayInterface
    {
        public function __construct(MagentoCustomerModelResourceModelGroupCollectionFactory $groupCollectionFactory)
        {
            $this->_groupCollectionFactory = $groupCollectionFactory;
        }
    
        /**
         * @return array
         */
        public function toOptionArray()
        {
            if (!$this->_options) {
                $this->_options = $this->_groupCollectionFactory->create()->loadData()->toOptionArray();
            }
            return $this->_options;
        }
    }

    Clear Cache using php bin/magento cache:flush

    Magento 2: How to customize and set up the “Contact Us” page?

    ‘Contact Us’ page is one of the essential things you can see in various companies or websites having established products, services, or brand names.

    Via contact page, customers and visitors send inquiries, messages, or emails. It enables you, for the most part, to be customers in contact with you.

    You can customize the ‘Contact Us’ page available in Magento 2 as per your requirements.

    ‘Contact Us’ page set up:

    • The first step is to go to ‘Admin Panel’ in Magento.
    • Now, go to store – Configuration – General – Contacts.
    • After the setting screen appears, make necessary changes.

    To enable the ‘Contact Us’ page on the storefront, select ‘yes’ option.

    Email Options:

    1. Send Emails to: Please note the email address in this field to which you would like to receive all the emails sent using the contact us form.

    2. Email Sender: Pick the name that you want to see as a sender.

    3. Email Template: You can use any email template to send messages or emails.

    4. And finally, click on ‘save config’ to enable the changes.

    Customizing ‘Contact Us’ page:

    1. Go to Content > Blocks.

    2. In the Blocks page, go to Action Menu and click on Edit option for ‘Contact Us’.

    3. Now go to the content box and make necessary changes to appear on the ‘Contact Us’ page.

    4. Click on ‘Save Block’ to finish your customization.

    After you finish all of the above steps, you have completed the configuration of the ‘Contact Us’ page in Magento 2.

    How to add new customer address attributes in Magento 2?

    Magento provides so many default fields but If we need custom information in customer address then we can create a new customer_address type attribute.

    In this article, I will share how we can add text type attribute in Customer Address,

    You need to create InstallData.php file in your existing module or you can create a new module as well as,

    If you are creating in your existing module: app/code/[Vendor Name]/[Module Name]/Setup/InstallData.php

    <?php
    namespace [Vendor Name]/[Module Name]Setup;
     
    use MagentoCustomerSetupCustomerSetupFactory;
    use MagentoEavModelEntityAttributeSet as AttributeSet;
    use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
    use MagentoFrameworkSetupInstallDataInterface;
    use MagentoFrameworkSetupModuleContextInterface;
    use MagentoFrameworkSetupModuleDataSetupInterface;
     
    class InstallData implements InstallDataInterface
    {	
    	/**
         * @var CustomerSetupFactory
         */
        private $customersetupFactory;
     	
     	/**
         * @var AttributeSetFactory
         */
        private $attributesetFactory;
     	
     	/**
         * @param CustomerSetupFactory $customersetupFactory
         * @param AttributeSetFactory $attributesetFactory
         */
        public function __construct(
            CustomerSetupFactory $customersetupFactory,
            AttributeSetFactory $attributesetFactory
        ) {
            $this->customersetupFactory = $customersetupFactory;
            $this->attributesetFactory = $attributesetFactory;
        }
     
        public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        {
     
            $customerSetup = $this->customersetupFactory->create(['setup' => $setup]);
            $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
            $attributeSetId = $customerEntity->getDefaultAttributeSetId();
            $attributeSet = $this->attributesetFactory->create();
            $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
     
            $customerSetup->addAttribute('customer_address', 'job_title', [
                'type' => 'varchar',
                'label' => 'Job Title',
                'input' => 'text', //You can change your input type as per your requirement
                'required' => false, //If You need this field is required in customer address area then you can just set "true" in stand of "false"
                'visible' => true,
                'user_defined' => true,
                'sort_order' => 1000,
                'position' => 1000,
                'system' => 0,
            ]);
     
            $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'job_title')
                ->addData([
                    'attribute_set_id' => $attributeSetId,
                    'attribute_group_id' => $attributeGroupId,
                    'used_in_forms' => ['adminhtml_customer_address'], //Other list of forms: customer_address_edit, customer_register_address where you want to display the custom attribute 
                ]);
     
            $attribute->save();
        }
    }

    After creating the above file you have to run below commands:

    php bin/magento setup:upgrade
    php bin/magento cache:clean

    Now you can check in the customer section in the admin area.
    Our newly created attribute shown in the customer address form.

    Magento 2: Change product price on change quantity box in Product detail page

    If you want to set price update while changing the quantity in product detail page then paste below script

    <script> 
    require(
    [
     'jquery', 'Magento_Catalog/js/price-utils'
    ],
    function($, priceUtils) {
    
     $(document).ready(function(){ 
     
     $('#qty').on('input propertychange paste', function() {
     changeCuPrice();
     });
     function changeCuPrice(){ 
     var totalQty = $('#qty').val();
     if(totalQty == 'undefined' || totalQty == ''){
     totalQty = 1;
     } 
     
     var price = $('.price-final_price .price-container .price-including-tax').data("price-amount");
     totalQty = parseFloat(totalQty); 
     
     var flprice = parseFloat(price) * parseFloat(totalQty);
     var inPrice = priceUtils.formatPrice(flprice);
     $('.box-tocart .price-final_price .price-container .price-excluding-tax .price').text(inPrice); 
     }
     
     setTimeout(function(){ changeCuPrice(); }, 500);
     
     });
    
    });
    </script>

    at this path

    app/design/frontend/Vendername/Themenamge/Magento_Catalog/templates/product/view/addtocart.phtml 

    How to assign the product image programmatically form external url?

    Step 1). Get the Product image from URL – create a file in Helper/Data.php

    public function getProductImage($imgurl){
    	 		$fileSystem = $this->_objectManager->create('MagentoFrameworkFilesystem');
    	        $mediaPath = $fileSystem->getDirectoryRead(MagentoFrameworkAppFilesystemDirectoryList::MEDIA)->getAbsolutePath();
    	        if (!file_exists($mediaPath.'imagefolder')) {
    	            mkdir($mediaPath.'imagefolder', 0777, true);
    	        }
    	        $url = $imgurl;
    	        $ch = curl_init($url);
    	        $my_save_dir = $mediaPath.'imagefolder/';
    	        $filename = basename($url);
    	        $complete_save_loc = $my_save_dir . $filename;
    	        $fp = fopen($complete_save_loc, 'wb');
    	        curl_setopt($ch, CURLOPT_FILE, $fp);
    	        curl_setopt($ch, CURLOPT_HEADER, 0);
    	        curl_setopt($ch, CURLOPT_TIMEOUT, 28800);
    	        $return = curl_exec($ch);
    	        curl_close($ch);
    	        $image = $return;
            	return $image;
            }

    Step 2). Assign the images to existing products.

    $product = $this->productFactory->create()->load($proid);
    	$getimgurl = $url;
    	$imagename= basename($getimgurl);
    	$imgpath = $mediaPath.'imagefolder/'.$imagename;
    	if (!file_exists($imgpath)) { //check image already exist in directory
    	    $this->helperData->getProductImage($getimgurl);
    	}
    $product->addImageToMediaGallery($imgpath, array('image', 'small_image', 'thumbnail','media_gallery'), false, false);
    $product->save();

     

    Setup Multi Store With Multi Domain in Magento 2

    Open index.php file and replace the following code with it.

    Then change domain, website, store or store view code.

    <?php
    /**
     * Application entry point
     *
     * Example - run a particular store or website:
     * --------------------------------------------
     * require __DIR__ . '/app/bootstrap.php';
     * $params = $_SERVER;
     * $params[MagentoStoreModelStoreManager::PARAM_RUN_CODE] = 'website2';
     * $params[MagentoStoreModelStoreManager::PARAM_RUN_TYPE] = 'website';
     * $bootstrap = MagentoFrameworkAppBootstrap::create(BP, $params);
     * /** @var MagentoFrameworkAppHttp $app */
     * $app = $bootstrap->createApplication('MagentoFrameworkAppHttp');
     * $bootstrap->run($app);
     * --------------------------------------------
     *
     * Copyright © 2016 Magento. All rights reserved.
     * See COPYING.txt for license details.
     */
     
    try {
        require __DIR__ . '/app/bootstrap.php';
    } catch (Exception $e) {
        echo <<<HTML
    <div style="font:12px/1.35em arial, helvetica, sans-serif;">
        <div style="margin:0 0 25px 0; border-bottom:1px solid #ccc;">
            <h3 style="margin:0;font-size:1.7em;font-weight:normal;text-transform:none;text-align:left;color:#2f2f2f;">
            Autoload error</h3>
        </div>
        <p>{$e->getMessage()}</p>
    </div>
    HTML;
        exit(1);
    }
    
    $params = $_SERVER;
    $domain2store = array(
    	'ww.xyx.nl'=> array('code'=>'nl','type'=>'store'), 
    	'www.xyz.de'=> array('code'=>'de','type'=>'store'), 
    	'www.xyz.be'=> array('code'=>'be','type'=>'website')
    );
    $params[MagentoStoreModelStoreManager::PARAM_RUN_CODE] = isset($domain2store['code']) ? $domain2store['code'] : 'nl';
    $params[MagentoStoreModelStoreManager::PARAM_RUN_TYPE] = isset($domain2store['type']) ? $store['domain2store'] : 'store';
    $bootstrap = MagentoFrameworkAppBootstrap::create(BP, $params);
    $app = $bootstrap->createApplication('MagentoFrameworkAppHttp');
    $bootstrap->run($app);

     

    Magento 2 Add Custom Validation to Billing Address Field

    By performing below steps one-by-one, we can put any validation in the checkout billing address.
    In this example, we are going to set validation for the telephone field.

    Here validation will be about the maximum and minimum length of telephone Exact ten digits going to get allowed.

    First, you have to create a file in your existing module following to below path,

    appcode[VendorName][ModuleName]etcfrontenddi.xml
    <type name="MagentoCheckoutBlockCheckoutLayoutProcessor">
        <plugin disabled="false" name="checkout_billing_address_layoutProcessor" sortOrder="110" type="[VendorName][ModuleName]PluginBlockCheckoutLayoutProcessor"/>
    </type>

    Then, you have to create another file at a given path,

    appcode[VendorName][ModuleName]PluginBlockCheckoutLayoutProcessor.php
    <?php
    
    namespace [VendorName][ModuleName]PluginBlockCheckout;
    
    class LayoutProcessor {
    
        public function afterProcess(MagentoCheckoutBlockCheckoutLayoutProcessor $subject, array $jsLayout) {
            if (isset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
                            ['payment']['children']['payments-list']['children']
                    )) {
    
                foreach ($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
                ['payment']['children']['payments-list']['children'] as $key => $payment) {
    
                    /* Telephone Billing Address */
                    if (isset($payment['children']['form-fields']['children']['telephone'])) {
                        $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
                                ['payment']['children']['payments-list']['children'][$key]['children']['form-fields']['children']
                    ['telephone']['validation'] = ['required-entry' => true, 'min_text_length' => 10, 'max_text_length' => 10];
                    }
                }
            }
    
            return $jsLayout;
        }
    
    }

    After doing the above steps you need to run below command:

    php bin/magento cache:flush
    php bin/magento cache:clean

    You can also put validations for other fields. All that you need to do is to change the field name in the form-field section. You can also change default validation error message using .csv in your module.

    How to add a custom column in Shipment grid in Magento 2

    Before following the below steps, you can create the order attribute and store it into the value.

    Step 1: Create module.xml file under app/code/Vendor/Modulename/etc directory and registration.php file under app/code/Vendor/Modulename directory.

    Step 2: Create sales_order_shipment_grid.xml file under app/code/Vendor/Modulename/view/adminhtml/ui_component directory with below code

    <?xml version="1.0" encoding="UTF-8"?>
    <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
        <columns name="sales_order_shipment_columns">
            <column name="custcolumn" class="VendorModulenameUiComponentListingColumnCustcolumn">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="filter" xsi:type="string">text</item>
                        <item name="label" xsi:type="string" translate="true">Custom Column</item>
                    </item>
                </argument>
            </column>
        </columns>
    </listing>
    

    Step 3: Create Custcolumn.php ui component class file under app/code/Vendor/Modulename/Ui/Component/Listing/Column directory with below code

    <?php
    namespace VendorModulenameUiComponentListingColumn;
     
    use MagentoSalesApiOrderRepositoryInterface;
    use MagentoFrameworkViewElementUiComponentContextInterface;
    use MagentoFrameworkViewElementUiComponentFactory;
    use MagentoUiComponentListingColumnsColumn;
    use MagentoFrameworkApiSearchCriteriaBuilder;
     
    class Custcolumn extends Column
    {
     
        protected $_orderRepository;
        protected $_searchCriteria;
        protected $_customfactory;
     
        public function __construct(
            ContextInterface $context,
            UiComponentFactory $uiComponentFactory,
            OrderRepositoryInterface $orderRepository,
            SearchCriteriaBuilder $criteria,
            MagentoFrameworkAppResourceConnection $resource,
            MagentoSalesModelOrderFactory $orderFactory,
            array $components = [], array $data = [])
        {
            $this->_orderRepository = $orderRepository;
            $this->_searchCriteria  = $criteria;
            $this->resource = $resource;
            $this->orderFactory = $orderFactory;
            parent::__construct($context, $uiComponentFactory, $components, $data);
        }
     
        public function prepareDataSource(array $dataSource)
        {
            if (isset($dataSource['data']['items'])) {
                $connection  = $this->resource->getConnection();
                $tableName = $connection->getTableName('sales_shipment_grid'); 
                foreach ($dataSource['data']['items'] as & $item) {
                    $order = $this->orderFactory->create()->loadByIncrementId($item["order_increment_id"]);
                    if($order->getCustcolumn()){
                        $item['custcolumn'] = $order->getCustcolumn();
                    }
                }
            }
            return $dataSource;
        }
    }