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.

    How to add table via declarative schema in Magento 2?

    Magento 2.4 version have given feature to add table using declarative schema.

    Module name : Magemonkeys_Core

    We need to create db_schema.xml file in the app/code/Magemonkeys/Core/etc/  folder

    <?xml version="1.0" encoding="UTF-8"?>
    <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
       <table name="customtable" resource="default" engine="innodb" comment="Custom table">
          <column xsi:type="smallint" name="id" unsigned="false" nullable="false" identity="true" comment="ID" />
          <column xsi:type="varchar" name="name" nullable="false" length="20" comment="Name" />
          <column xsi:type="varchar" name="email" nullable="false" length="20" comment="Email" />
          <constraint xsi:type="primary" referenceId="PRIMARY">
             <column name="id" />
          </constraint>
       </table>
    </schema>

    After that, we need to generate db white list schema json

    For that, we need to run command as per below

    php bin/magento setup:db-declaration:generate-whitelist --module-name=Magemonkeys_Core

    After that we need to run setup:upgrade and cache:flush command

    That’s it.

     

    Magento 2.4.x: Remove Content Security Policies Errors in Console

    Create config.xml in your custom module and add below code
    Vendor/Module/etc/config.xml
    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
        <default>
            <csp>
                <mode>
                    <storefront>
                        <report_only>0</report_only>
                    </storefront>
                    <admin>
                        <report_only>0</report_only>
                    </admin>
                </mode>
            </csp>
        </default>
    </config>
    Add a domain to the whitelist
    Create csp_whitelist.xml in your custom module and add below code
    Vendor/Module/etc/csp_whitelist.xml
    <?xml version="1.0"?>
    <csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp/etc/csp_whitelist.xsd">
        <policies>
            <policy id="script-src">
                <values>
                    <value id="cdn.jsdelivr.net" type="host">https://cdn.jsdelivr.net/</value>
                </values>
            </policy>
            <policy id="style-src">
                <values>
                    <value id="fontawesome" type="host">https://fontawesome.com</value>
                </values>
            </policy>
            <policy id="img-src">
                <values>
                    <value id="google.co.in" type="host">https://www.google.co.in/</value>
                </values>
            </policy>
            <policy id="connect-src">
                <values>
                    <value id="ct.pinterest.com" type="host">https://ct.pinterest.com</value>
                </values>
            </policy>
            <policy id="font-src">
                <values>
                    <value id="cloudflare" type="host">https://cloudflare.com</value>
                </values>
            </policy>
            <policy id="frame-src">
                <values>
                    <value id="pinterest" type="host">https://pinterest.com</value>
                </values>
            </policy>
            <policy id="form-action">
                <values>
                    <value id="pinterest.com" type="host">https://pinterest.com</value>
                </values>
            </policy>
        </policies>
    </csp_whitelist>

     

    Magento 2 : How to check use default value with all categories & all products?

    If you want all products to have Use Default Value as CHECKED, then run below SQL in the database:

    DELETE FROM `catalog_product_entity_text` where store_id = 1;
    DELETE FROM `catalog_product_entity_datetime` where store_id = 1;
    DELETE FROM `catalog_product_entity_decimal` where store_id = 1;
    DELETE FROM `catalog_product_entity_int` where store_id = 1;
    DELETE FROM `catalog_product_entity_varchar` where store_id = 1;

    If you want all categories to have Use Default Value as CHECKED, then run below SQL in the database:

    DELETE FROM `catalog_category_entity_text` where store_id = 1;
    DELETE FROM `catalog_category_entity_datetime` where store_id = 1;
    DELETE FROM `catalog_category_entity_decimal` where store_id = 1;
    DELETE FROM `catalog_category_entity_int` where store_id = 1;
    DELETE FROM `catalog_category_entity_varchar` where store_id = 1;

     

     

    Magento 2.4.x: How to install coding Standard and errors debug command?

    Follow below steps to install Using composer : 

    - composer require --dev magento/magento-coding-standard
    - php bin magento setup:upgrade
    - php bin/magento cache:flush

    You are done with installations.

    Now, You can check Magento coding standard errors using the below command for Custom module :

    vendor/bin/phpcs --standard=Magento2 app/code/Vendor/Module

    After running the above command, you can see coding errors and warnings. You need to resolve those errors & warnings by adopting Magento coding standards.

    That’s It.

    How to add load more button in any listing page in Magento 2?

    In one of the Magento 2 project, we have added a load more button on the listing page.

    So whenever the user clicks on the load more button, the next page of products will be shown.

    You can use below on the custom listing page.

    <script src ="https://infiniteajaxscroll.com/vendor/jquery-ias/dist/jquery-ias.min.js"></script>
    <link src = "https://raw.githubusercontent.com/ravbetsky/infinite-ajax-scroll/master/dist/css/jquery.ias.css"/>
    <script type="text/javascript">
    var ias = jQuery.ias({
    container: ".main",
    item: ".products-grid",
    pagination: ".toolbar .pages",
    next: ".next"
    });
    ias.extension(new IASSpinnerExtension()); // shows a spinner (a.k.a. loader)
    ias.extension(new IASTriggerExtension({offset: 1})); // shows a trigger after page 3
    ias.extension(new IASNoneLeftExtension({
    text: 'There are no more pages left to load.' // override text when no pages left
    }));
    </script>

    You will also need to change class for this as shown below.

    container: ".main",
    item: ".products-grid",
    pagination: ".toolbar .pages",
    next: ".next"

    That’s it.

    How to discontinue product backend settings?

    To achieve this, create a basic module and below code in InstallSchema.php file.

    Change the vendor namespace and module name as per your requirement.

    <?php
    namespace MagemonkeysDiscontinueSetup;
    
    use MagentoEavSetupEavSetup;
    use MagentoEavSetupEavSetupFactory;
    use MagentoFrameworkSetupInstallDataInterface;
    use MagentoFrameworkSetupModuleContextInterface;
    use MagentoFrameworkSetupModuleDataSetupInterface;
    
    class InstallData implements InstallDataInterface
    {
        private $eavSetupFactory;
    
        public function __construct(EavSetupFactory $eavSetupFactory)
        {
            $this->eavSetupFactory = $eavSetupFactory;
        }
    
        public function install(
            ModuleDataSetupInterface $setup,
            ModuleContextInterface $context
        )
        {
            /** @var EavSetup $eavSetup */
            $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
    
            /**
             * Add attributes to the eav/attribute
             */
               $eavSetup->addAttribute(
                MagentoCatalogModelProduct::ENTITY,
                'discontinue',
                [
                    'group' => 'Discontinue Product Information',
                    'type' => 'int',
                    'backend' => '',
                    'frontend' => '',
                    'label' => 'Discontinue',
                    'input' => 'boolean',
                    'class' => '',
                    'source' => 'MagentoEavModelEntityAttributeSourceBoolean',
                    'global' => MagentoCatalogModelResourceModelEavAttribute::SCOPE_GLOBAL,
                    'visible' => true,
                    'required' => false,
                    'user_defined' => false,
                    'default' => false,
                    'searchable' => false,
                    'filterable' => false,
                    'comparable' => false,
                    'visible_on_front' => false,
                    'used_in_product_listing' => true,
                    'unique' => false
                ]
            );
    
               /**
             * Add attributes to the eav/attribute
             */
               $eavSetup->addAttribute(
                MagentoCatalogModelProduct::ENTITY,
                'alternate_product_url',
                [
                     'group' => 'Discontinue Product Information',
                     'type' => 'text',
                     'backend' => '',
                     'frontend' => '',
                     'label' => 'Alternate Product URL',
                     'input' => 'text',
                     'class' => '',
                     'source' => '',
                     'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_GLOBAL,
                     'visible' => false,
                     'required' => false,
                     'user_defined' => false,
                     'default' => '',
                     'searchable' => false,
                     'filterable' => false,
                     'comparable' => false,
                     'visible_on_front' => true,
                     'used_in_product_listing' => true,
                     'unique' => false,
                     'apply_to' => ''
                ]
            );
               $eavSetup->addAttribute(
                MagentoCatalogModelProduct::ENTITY,
                'alternate_product_sku',
                [
                     'group' => 'Discontinue Product Information',
                     'type' => 'text',
                     'backend' => '',
                     'frontend' => '',
                     'label' => 'Alternate Product SKU',
                     'input' => 'text',
                     'class' => '',
                     'source' => '',
                     'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_GLOBAL,
                     'visible' => true,
                     'required' => false,
                     'user_defined' => false,
                     'default' => '',
                     'searchable' => false,
                     'filterable' => false,
                     'comparable' => false,
                     'visible_on_front' => true,
                     'used_in_product_listing' => true,
                     'unique' => false,
                     'apply_to' => ''
                ]
            );
        }
    }

    Create a Observer with catalog_product_save _before in adminhtml/events.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
        <event name="catalog_product_save_before">
            <observer name="discontinue_product_save_after" instance="MagemonkeysDiscontinueObserverProductsavebefore" />
        </event>
    </config>

    Add Observer file and place the below code in it.

    <?php
    
    namespace MagemonkeysDiscontinueObserver;
    
    use MagentoFrameworkEventObserverInterface;
    use MagentoCatalogApiProductRepositoryInterface;
    use MagentoFrameworkUrl;
    use MagentoFrameworkExceptionNoSuchEntityException;
    
    class Productsavebefore implements ObserverInterface
    {    
    
        /**
         * @var ProductRepositoryInterface
         */
        protected $productRepository;
    
        protected $_url;
     
        /**
         * @param ProductRepositoryInterface $productRepository
         */
        public function __construct(
            ProductRepositoryInterface $productRepository,
            Url $url
        ) {
            $this->productRepository = $productRepository;
            $this->_url = $url;
        }
    
        public function execute(MagentoFrameworkEventObserver $observer)
        {
            $_product = $observer->getProduct();  // you will get product object
    
            $sku = $_product->getAlternateProductSku();
    
            if($sku != '')
            {
                try
                {
                    $alternateProduct = $this->productRepository->get($sku);
                }
                catch (NoSuchEntityException $noSuchEntityException) {
                    $productUrl = null;
                }
    
                if($alternateProduct)
                {
    
                    $product = $this->productRepository->getById($alternateProduct->getId(), false);
                    //$productUrl = $product->setStoreId(1)->getUrlModel()->getUrlInStore($product, ['_escape' => true]);
                    $productUrl = $product->getUrlKey();
                    $_product->setData('alternate_product_url', $productUrl);
                    
                }
            }
            else
            {
                $productUrl = null;
                $_product->setData('alternate_product_url', $productUrl);
            }
    
        }   
    }

    Create a plugin with aroundGetProduyctCollection to remove the discontinue product from whole site. Please add the below code in that plugin.

    <?php
    
    namespace MagemonkeysDiscontinuePluginMagentoCatalogModel;
    
    class Layer
    {
    
        public function aroundGetProductCollection(
            MagentoCatalogModelLayer $subject,
            Closure $proceed
        ) {
            $collection = $proceed();
            $collection->addAttributeToSelect('*')->addAttributeToFilter(array(
                array(
                    'attribute' => 'discontinue',
                    'null' => true),
                array(
                    'attribute' => 'discontinue',
                    'eq' => '0')
            ));
            return $collection;
        }
    
    
    }
    
    

     

    Get params data in magento 2 api

    Today we are going to talk about how to get params data in Magento 2 api.

    You can use this class for this MagentoFrameworkWebapiRestRequest

    And below code.

    <?php
    namespace MagemonkyesParamsModel;
    use MagentoFrameworkWebapiRestRequest;
    class GetpostParams
    {
        public function __construct(
            Request $requestparam
        ) {
            $this->requestparam = $requestparam;
        }
    
        public function getParampostgetValue()
        {
            $filter = $this->requestparam->getParam('name');
        }
    }

    User can get this by code to call getParampostgetValue this function.

    How to Set Price Format using JavaScript in Magento 2?

    When you pass price value phtml to js , you need to display price with currency from js.

    Use ‘Magento_Catalog/js/price-utils’ priceUtils Js object in your custom javascript file to set currency to price.

    Then add getFormattedPrice() function in your file to display currency symbol with price from javascript.

    define([
        'ko',
        'Magento_Catalog/js/price-utils'
    ], function (
        ko,
        priceUtils
    ) {
        'use strict';
        return {
            /**
             * Formats the price with currency format
             *
             * @param {number}
             * @return {string}
             */
            getFormattedPrice: function (price) {
                var priceFormat = {
                    decimalSymbol: '.',
                    groupLength: 3,
                    groupSymbol: ",",
                    integerRequired: false,
                    pattern: "₹%s",
                    precision: 2,
                    requiredPrecision: 2
                };
                return priceUtils.formatPrice(price, priceFormat);
            }
        }
    });

     

    Magento 2: 404 error and logged in customer

    First of all Override the following file :

    /vendor/magento/module-customer/Model/Account/Redirect.php
    • change redirect URL if login post controller gets 404 error or redirect the customer to a specific page :
      private function applyRedirect($url)
      {
         /* changes start*/
          $baseUrl = $this->storeManager->getStore()->getBaseUrl();
          if($url == $baseUrl.'customer/account/loginPost/'){
              $url = $baseUrl.'customer/account/login/';
          }
         /* changes  end*/
          $this->session->setBeforeAuthUrl($url);
      }

      NOTE:  Override core file in your custom module.