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.

    Magento 2.3.3 Version issue – Store Switcher not working when customer is logged in

    This tutorial is a solution if your store switcher is not working when customer is logged in Magento.

    It happens because there is a difference between 2.3-develop and 2.3.3 for the di.xml file of the store module.

    Check the following changes to resolve this issue :

    First of all override the following file :

    magento2/app/code/Magento/Store/etc/di.xml

    & Replace the following code : 

     <type name="MagentoStoreModelStoreSwitcher"> 
         <arguments> 
             <argument name="storeSwitchers" xsi:type="array"> 
                 <item name="cleanTargetUrl" xsi:type="object">MagentoStoreModelStoreSwitcherCleanTargetUrl</item> 
                 <item name="manageStoreCookie" xsi:type="object">MagentoStoreModelStoreSwitcherManageStoreCookie</item> 
                 <item name="managePrivateContent" xsi:type="object">MagentoStoreModelStoreSwitcherManagePrivateContent</item> 
                 <item name="hashGenerator" xsi:type="object">MagentoStoreModelStoreSwitcherHashGenerator</item> 
             </argument> 
         </arguments> 
     </type>

    With 

     <type name="MagentoStoreModelStoreSwitcher"> 
         <arguments> 
             <argument name="storeSwitchers" xsi:type="array"> 
                 <item name="cleanTargetUrl" xsi:type="object">MagentoStoreModelStoreSwitcherCleanTargetUrl</item> 
                 <item name="manageStoreCookie" xsi:type="object">MagentoStoreModelStoreSwitcherManageStoreCookie</item> 
                 <item name="managePrivateContent" xsi:type="object">MagentoStoreModelStoreSwitcherManagePrivateContent</item> 
             </argument> 
         </arguments> 
     </type>

    We deleted the following line and the store switcher started working for logged in customers.

    <item name="hashGenerator" xsi:type="object">MagentoStoreModelStoreSwitcherHashGenerator</item>

    Please let us know if this article is helpful to you or not.

    Magento 2 remove hidden from the product image which having a base role in the product image

    Find the base image attribute id from eav_attribute.

    attr_id = SELECT `attribute_id` FROM `eav_attribute` WHERE `attribute_code` = "image" AND `frontend_label` = "Base" LIMIT 1;

    Find all images which having a Base image role.

    value = SELECT `value` FROM `catalog_product_entity_varchar` WHERE `attribute_id` = (attr_id);

    Find all ids from the media gallery.

    gallery = SELECT `value_id` FROM `catalog_product_entity_media_gallery` WHERE `value` IN (value);

    Update the media gallery value to 0.

    UPDATE `catalog_product_entity_media_gallery_value` SET `disabled` = 0 WHERE `value_id` IN (gallery);

    Final query:

    UPDATE `catalog_product_entity_media_gallery_value` SET `disabled` = 0 WHERE `value_id` IN ( 
        SELECT `value_id` FROM `catalog_product_entity_media_gallery` WHERE `value` IN ( 
            SELECT `value` FROM `catalog_product_entity_varchar` WHERE `attribute_id` = ( 
                SELECT `attribute_id` FROM `eav_attribute` WHERE `attribute_code` = "image" AND `frontend_label` = "Base" LIMIT 1 ) ) );

     

    Magneto 2 – export product data using custom code

    Create one php file inside your Magento root directory with below code.

    <?php
    
    use MagentoFrameworkAppBootstrap;
    
    require 'app/bootstrap.php';
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $instance = MagentoFrameworkAppObjectManager::getInstance();
    $state = $objectManager->get('MagentoFrameworkAppState');
    $state->setAreaCode('frontend');
    
    $productCollectionFactory = $objectManager->get('MagentoCatalogModelResourceModelProductCollectionFactory');
    $collection = $productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
     
    // filter current website products
    $collection->addWebsiteFilter();
     
    // filter current store products
    $collection->addStoreFilter();
     
    // set visibility filter
    $collection->setVisibility($objectManager->get('MagentoCatalogModelProductVisibility')->getVisibleInSiteIds());
    $header = array("ID", "Product Name", "Sku","Image", "Main Image");	
    $fp = fopen('evhr-products.csv', 'w+');
    fputcsv($fp, $header);
    $productdata = array();
    $collection->setPageSize(5000); 
        foreach ($collection as $product) { 
        $productsku = $product->getSku();
        $productname = $product->getName();
        $product_id = $product->getId();
    	$productimages = array();
    	$product = $objectManager ->create('MagentoCatalogModelProduct')->load($product_id);
    	$productimages = $product->getMediaGalleryImages();
    	$allimgarray = array();
    	$productImage = $product->getData('image');
    	$productBase = 1;
    	foreach($productimages as $productimage)
    	{
    		if($productimage['file'] == $productImage){
    			$data = array('id' => $product_id, 'productname' => $productname, 'productsku' => $productsku, 'productImage' => $productimage['file'], 'mainimage' => 1 );
    		}else{
    			$data = array('id' => $product_id, 'productname' => $productname, 'productsku' => $productsku, 'productImage' => $productimage['file'], 'mainimage' => 0 );
    
    		}
    		fputcsv($fp, $data);
    	}
    }

     

    How to get system configuration value in Magento 2?

    Here we are going to write about how to get system configuration value in your custom file or anywhere else.

    Inside the header data file we have add this code

    create Data.php file in Magemonkeys/General/Helper/

    public function __construct(
       MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
    )
    {
       $this->_scopeConfig = $scopeConfig;
    }
    
    public function getConfig($config_path)
    {
        return $this->_scopeConfig->getValue(
                $config_path,
                MagentoStoreModelScopeInterface::SCOPE_STORE
                );
    }

    In phtml file – add below for call helper function

    $systemconfval = $this->helper('MagemonkeysGeneralHelperData')->getConfig('sectionid/groupid/fieldid');
    echo $systemconfval;

    Well, after performing above changes, value will be shown. Hope that helps!

    Magento 2: change translation for specific module

    Magento 2 provides translate the same element in different ways for different modules.

    Here, I have to change the “Next” slug translation for the checkout module by using the theme translate file.

    "Next","Continue to Payment", module, Magento_Checkout
    "Next","Next"

    Note: I have used this with Magento 2.3.6 version

    How to per page filters in catalog product grid in admin panel of Magento 2?

    Follow the below mentioned steps:

    Step 1 : Go to database of your site using phpmyadmin

    Step 2 : Filter related settings stored in ‘ui_bookmark‘ table. Find the table and open it.

    Step 3 : Find the row with your user_id, namespace with ‘product_listing‘ and identifier with ‘current’.

    Step 4 : Edit this row and change in ‘config’ column’s data.

    Change “current”:750, with “current”:1,

    {"current":{"paging":{"pageSize":20,"current":750,"options":{"20":{"value":20,"label":20},"30":{"value":30,"label":30},"50":{"value":50,"label":50},"100":{"value":100,"label":100},"200":{"value":200,"label":200}},"value":20},"columns":{"entity_id":{"visible":true,"sorting":"desc"},"name":{"visible":true,"sorting":false},"sku":{"visible":true,"sorting":false},"price":{"visible":true,"sorting":false},"websites":{"visible":true,"sorting":false},"qty":{"visible":true,"sorting":false},"short_description":{"visible":false,"sorting":false},"special_price":{"visible":false,"sorting":false},"cost":{"visible":false,"sorting":false},"weight":{"visible":false,"sorting":false},"meta_title":{"visible":false,"sorting":false},"meta_keyword":{"visible":false,"sorting":false},"meta_description":{"visible":false,"sorting":false},"msrp":{"visible":false,"sorting":false},"url_key":{"visible":false,"sorting":false},"actions":{"visible":true,"sorting":false},"ids":{"visible":true,"sorting":false},"salable_quantity":{"visible":true,"sorting":false},"special_from_date":{"visible":false,"sorting":false},"special_to_date":{"visible":false,"sorting":false},"news_from_date":{"visible":false,"sorting":false},"news_to_date":{"visible":false,"sorting":false},"custom_design_from":{"visible":false,"sorting":false},"custom_design_to":{"visible":false,"sorting":false},"type_id":{"visible":true,"sorting":false},"attribute_set_id":{"visible":true,"sorting":false},"visibility":{"visible":true,"sorting":false},"status":{"visible":true,"sorting":false},"manufacturer":{"visible":false,"sorting":false},"color":{"visible":false,"sorting":false},"custom_design":{"visible":false,"sorting":false},"page_layout":{"visible":false,"sorting":false},"country_of_manufacture":{"visible":false,"sorting":false},"custom_layout":{"visible":false,"sorting":false},"tax_class_id":{"visible":false,"sorting":false},"gift_message_available":{"visible":false,"sorting":false},"thumbnail":{"visible":true,"sorting":false},"led":{"visible":true,"sorting":false},"bol_status":{"visible":true,"sorting":false}},"filters":{"applied":{"placeholder":true}},"search":{"value":""},"displayMode":"grid","positions":{"ids":0,"entity_id":1,"thumbnail":2,"name":3,"type_id":4,"attribute_set_id":5,"sku":6,"price":7,"qty":8,"salable_quantity":9,"visibility":10,"status":11,"websites":12,"short_description":13,"special_price":14,"special_from_date":15,"special_to_date":16,"cost":17,"weight":18,"manufacturer":19,"meta_title":20,"meta_keyword":21,"meta_description":22,"color":23,"news_from_date":24,"news_to_date":25,"custom_design":26,"custom_design_from":27,"custom_design_to":28,"page_layout":29,"country_of_manufacture":30,"custom_layout":31,"msrp":32,"url_key":33,"tax_class_id":34,"gift_message_available":35,"actions":36,"led":37,"bol_status":38}}}

    After that clear your Magento cache using below mentioned command

    - php bin/magento cache:clean

    That’s it.

    Now, you can check your catalog product grid page of admin panel. Your catalog product grid page error should be resolved.

    Magento 2 Site breaking due to Braintree Configuration

    This article is a solution If you face an uncaught TypeError which details

    explode() expects parameter 2 to be string, null given in /vendor/gene/module-braintree/Model/Lpm/Config.php:127

    All you need to do is check the following code & replace the method getAllowedMethods in /vendor/gene/module-braintree/Model/Lpm/Config.php.

    public function getAllowedMethods(): array
    {
        $this->allowedMethods = [];
        $allowedMethods = [];
        if ($this->getValue(self::KEY_ALLOWED_METHODS,$this->storeConfigResolver->getStoreId()))
        {
    	$allowedMethods = explode(',',$this->getValue(self::KEY_ALLOWED_METHODS,$this->storeConfigResolver->getStoreId()));
        }
        foreach ($allowedMethods as $allowedMethod) {
            $this->allowedMethods[] = [
                'method' => $allowedMethod,
                'label' => constant('self::LABEL_'.strtoupper($allowedMethod)),
                'countries' => constant('self::COUNTRIES_'.strtoupper($allowedMethod))
            ];
        }
        return $this->allowedMethods;
    }

     

    Add cms page via install script in magento 2

    Today we are going to share that how to add CMS page via install script in CMS page admin area.

    This is our module : Magemonkeys_Cmspagescript

    So we need to create InstallData.php file in setup folder

    Here is code

    <?php
    
    namespace MagemonkeysCmspagescriptSetup;
    
    use MagentoCmsModelPageFactory;
    use MagentoFrameworkSetupInstallDataInterface;
    use MagentoFrameworkSetupModuleContextInterface;
    use MagentoFrameworkSetupModuleDataSetupInterface;
    
    class InstallData implements InstallDataInterface
    {
        private $pageFactory;
        
        public function __construct(PageFactory $pageFactory)
        {
            $this->pageFactory = $pageFactory;
        }
    
        public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        {
            $cmsPageDataarray = [
                'title' => 'My cms page', 
                'page_layout' => '1column', 
                'meta_keywords' => 'My Page keywords',
                'meta_description' => 'My Page description',
                'identifier' => 'my-page',
                'content_heading' => 'my cms page',
                'content' => "<h1>This is hello world my page</h1>",
                'is_active' => 1,
                'stores' => [0],
                'sort_order' => 0
            ];
    
            $this->pageFactory->create()->setData($cmsPageDataarray)->save();
        }
    }

    Now all we have to do is to run below commands:

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

    That’s it. Hope that helps!

    Magento 2 move wishlist link after add to cart button in product detail page

    Today I am going to share that how we can move wishlist icon under product info using xml.

    For moving wishlist block you have to create catalog_product_view.xml in your custom theme or custom module.

    Create app/design/frontend/[Theme Vendor Name]/[Theme Name]/Magento_Catalog/layout/catalog_product_view.xml and add below code:

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <move element="product.info.social" destination="product.info.form.content" after="product.info.addtocart" />
        </body>
    </page>

    After doing above process, run the below commands.

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

    There you will find wishlist link shown after add to cart button.

    How to add category drop down in system configuration Magento 2?

    For any custom module we can add category drop down selection in system configuration.

    Let’s start with creating a module names Magemonkeys_Categorydropdown

    in adminhtml we can create file system.xml

    Here is code for call category selection

    <group id="categoryselection_setting" translate="label" type="text" default="1" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
        <label>Setting</label>
        <field id="categorylist" translate="label" type="multiselect" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Please Select Category</label>
            <source_model>MagemonkeysCategorydropdownModelConfigSourceCategorylist</source_model>
        </field>
    </group>

    and then we can create file Categorylist.php in MagemonkeysCategorydropdownModelConfigSource

    <?php
    namespace MagemonkeysCategorydropdownModelConfigSource;
    
    use MagentoFrameworkOptionArrayInterface;
    
    class Categorylist implements ArrayInterface
    {
        protected $_categoryHelper;
    
        public function __construct(MagentoCatalogHelperCategory $catalogCategory)
        {
            $this->_categoryHelper = $catalogCategory;
        }
    
        public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
        {
            return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
        }
    
        public function toOptionArray()
        {
    
            $arr = $this->toArray();
            $ret = [];
    
            foreach ($arr as $key => $value)
            {
    
                $ret[] = [
                    'value' => $key,
                    'label' => $value
                ];
            }
    
            return $ret;
        }
    
        public function toArray()
        {
    
            $categories = $this->getStoreCategories(true,false,true);
    
            $catagoryList = array();
            foreach ($categories as $category){
    
                $catagoryList[$category->getEntityId()] = __($category->getName());
            }
    
            return $catagoryList;
        }
    
    }

    That’s it.