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 download pdf file magento2?

    Magento2 has a built-in script for any kind of file download, we can use the below code for file downloads:

    <?php
    /**
     * Magemonkeys.
     *
     * @category  Magemonkeys
     *
     * @author    Magemonkeys
     * @copyright Copyright (c) 2020 Magemonkeys (https://magemonkeys.com/)
     */
    
    namespace MagemonkeysDownloadControllerDownload;
    
    use MagentoFrameworkAppActionContext;
    
    /**
     * file download controller.
     */
    class Index extends MagentoFrameworkAppActionAction
    {
        /**
         * @var MagentoFrameworkAppResponseHttpFileFactory
         */
        protected $_downloader;
    
        /**
         * @var MagentoFrameworkFilesystemDirectoryList
         */
        protected $directory;
    
        /**
         * @param Context     $context
         * @param PageFactory $resultPageFactory
         */
        public function __construct(
            Context $context,
            MagentoFrameworkAppResponseHttpFileFactory $fileFactory,
            MagentoFrameworkFilesystemDirectoryList $directory
        ) {
            $this->_downloader =  $fileFactory;
            $this->directory = $directory;
            parent::__construct($context);
        }
    
        public function execute()
        {
            $fileName = $this->getRequest()->getParam('fileName');
            $file = $this->directory->getPath("media")."/FilePath/".$fileName;
            // do your validations
    
            /**
             * do file download
             */
            return $this->_downloader->create(
                $fileName,
                @file_get_contents($file)
            );
        }
    }

     

    Make clickable Value of Grid (UI Column)

    If you want to set clickable value in the Magento 2 Grid then please follow the below steps. I have made this type of functionality for my custom module.

    Step 1: Please add this code to your UI Listing XML. We have added bodyTmpl to make value clickable in the UI column.

    <column name="holiday_id" class="MagemonkeysHolidaylistingUiComponentListingColumnHolidayId">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">ID #</item>
                <item name="sortOrder" xsi:type="number">10</item>
                <item name="filter" xsi:type="string">text</item>
                <item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>
            </item>
        </argument>
    </column>

    Step 2: We have to paste the below code for Class which is defined in the <column> tag.
    Path : appcodeMagemonkeysHolidaylistingUiComponentListingColumnHolidayId.php

    <?php
    
    namespace MagemonkeysHolidaylistingUiComponentListingColumn;
    
    use MagentoFrameworkUrlInterface;
    use MagentoUiComponentListingColumnsColumn;
    use MagentoFrameworkViewElementUiComponentFactory;
    use MagentoFrameworkViewElementUiComponentContextInterface;
    
    
    class HolidayId extends Column
    {
        private $urlBuilder;
    
        public function __construct(
            ContextInterface $context,
            UiComponentFactory $uiComponentFactory,
            UrlInterface $urlBuilder,
            array $components = [],
            array $data = []
        ) {
            $this->urlBuilder = $urlBuilder;
            parent::__construct($context, $uiComponentFactory, $components, $data);
        }
    
        public function prepareDataSource(array $dataSource)
        {
            if (isset($dataSource['data']['items'])) {
                foreach ($dataSource['data']['items'] as & $item) {
                    if (isset($item['holiday_id'])) {
                        $url = $this->urlBuilder->getUrl('holiday/view', ['holiday_id' => $item['holiday_id']]);
                		$link = '<a href="' . $url . '"">' . $item['holiday_id'] . '</a>';
                        $item['holiday_id'] = $link;
                    }
                }
            }
            return $dataSource;
        }
    }

    Now you can see the Id column values are clickable.

    How to clean or flush cache programmatically in magento2?

    Some times we need to clear cache programmatically.

    You can do that by using the below code.

    <?php
    namespace MagemonkeysCacheBlock;
    
    class CacheClear extends MagentoFrameworkViewElementTemplate
    {
        public function __construct(
            MagentoFrameworkViewElementTemplateContext $context,
            MagentoFrameworkAppCacheFrontendPool $cacheFrontendPool,
            MagentoFrameworkAppCacheTypeListInterface $cacheTypeList,
            array $data = []
        ) {
            $this->_cacheFrontendPool = $cacheFrontendPool;
            $this->_cacheTypeList = $cacheTypeList;
            parent::__construct($context, $data);
        }
    
    
        public function cacheClear()
        {
            /* get all types of cache in system */
            $allTypes = array_keys($this->_cacheTypeList->getTypes());
    
            /* Clean cached data for specific cache type */
            foreach ($allTypes as $type) {
                $this->_cacheTypeList->cleanType($type);
            }
    
            /* flushed the Entire cache storage from system, Works like Flush Cache Storage button click on System -> Cache Management */
            foreach ($this->_cacheFrontendPool as $cacheFrontend) {
                $cacheFrontend->getBackend()->clean();
            }
        }
    }

    Call function like below,

    $clearCache = $block->cacheClear();

    Magento 2: add body css class on checkout page step-wise

    If you need to set a CSS class on change checkout stepwise then follow the below instructions.

    You need to override progress-bar.js from

    vendor/magento/module-checkout/view/frontend/web/js/view
    

    to your current theme and replace the below js function.

    /**
     * @param {Object} item
     * @return {*|Boolean}
     */
    isProcessed: function (item) {
     var itemCode = item.code;
     if (itemCode == "shipping") {
     jQuery('body').addClass('payment-step');
     jQuery('body').removeClass('shipping-step');
     } else {
     jQuery('body').addClass('shipping-step');
     jQuery('body').removeClass('payment-step');
     }
     return stepNavigator.isProcessed(item.code);
    }

    How to add column with filter in orders grid magento 2?

    In Magento 2 we can customize the order grid with adding column and filter as well.

    n today’s tutorial, we’ll add telephone no as a column in order grid. The next step is to create a new module.

    Here are the namespace and module name :

    Magemonkeys_CustomOrdersGrid

    Create registration.php file

    <?php
    MagentoFrameworkComponentComponentRegistrar::register(
        MagentoFrameworkComponentComponentRegistrar::MODULE,
        'Magemonkeys_CustomOrdersGrid',
        __DIR__
    );

    Create etc/module.xml file

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Magemonkeys_CustomOrdersGrid" setup_version="1.0.0">
            <sequence>
                <module name="Magento_Sales"/>
                <module name="Magento_Ui"/>
            </sequence>
        </module>
    </config>

    Create etc/adminhtml/di.xml file

    <?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="MagentoFrameworkViewElementUiComponentDataProviderCollectionFactory">
            <plugin name="magemonkeys_custom_orders_grid"
                    type="MagemonkeysCustomOrdersGridPluginOrdersGrid"
                    sortOrder="20"
                    disabled="false"/>
        </type>
    </config>

    Create Plugin/OrdersGrid.php file

    <?php
    namespace MagemonkeysCustomOrdersGridPlugin;
    
    use MagentoSalesModelResourceModelOrderGridCollection as OrderGridCollection;
    
    class OrdersGrid
    {
        
        private $logger;
        
        public function __construct(
            PsrLogLoggerInterface $customLogger,
            array $data = []
        ) {
            $this->logger = $customLogger;
        }
    
        public function afterGetReport($subject, $collection, $requestName)
        {
            if ($requestName !== 'sales_order_grid_data_source') {
                return $collection;
            }
    
            if ($collection->getMainTable() === $collection->getResource()->getTable('sales_order_grid')) {
                try {
                    $orderAddressTable  = $collection->getResource()->getTable('sales_order_address');
                    
                    $collection->getSelect()->joinLeft(
                        ['oat' => $orderAddressTable],
                        'oat.parent_id = main_table.entity_id AND oat.address_type = 'shipping'',
                        ['telephone']
                    );
                } catch (Zend_Db_Select_Exception $selectException) {
                    $this->logger->log(100, $selectException);
                }
            }
    
            return $collection;
        }
    }

    Create view/adminhtml/ui_component/sales_order_grid.xml file

    <?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_columns">
            
            <column name="telephone">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/column</item>
                        <item name="label" xsi:type="string" translate="true">Telephone</item>
                        <item name="sortOrder" xsi:type="number">60</item>
                        <item name="align" xsi:type="string">left</item>
                        <item name="dataType" xsi:type="string">text</item>
                        <item name="visible" xsi:type="boolean">true</item>
                        <item name="filter" xsi:type="string">text</item>
                    </item>
                </argument>
            </column>
            
        </columns>
    </listing>

    after that we can enable the module by running a few commands:

    php bin/magento module:enable Magemonkeys_CustomOrdersGrid
    php bin/magento setup:upgrade
    php bin/magento cache:clean

    Now, you will able to see the telephone column in order grid.

     

    Magento 2 custom options dependency on product page

    Override custom option file in your theme
    app/design/frontend/namespace/themename/Magento_Catalog/templates/product/view/options/type/select.phtml

    <?php @var $this Mage_Catalog_Block_Product_View_Options_Type_Select ?>
    <?php $_option = $this->getOption() ?>
    
    <?php if ($_option->getTitle()=="testoption1") { ?>
    <div id="hingebox">
    <?php } ?>
    <?php if ($_option->getTitle()=="testoption2") { ?>
    <script type="text/javascript">
        jQuery(document).ready(function(){
            jQuery('#hingebox select').on('change', function() {
                    if (jQuery('#hingebox select option:selected' ).text()==0)
                    {
                            jQuery('#hingeoptions').hide();
                    }
                    else jQuery('#hingeoptions').show();
            });
        });
    </script>
    <div id="hingeoptions" style="display:none;">
    <?php } ?>
    <dt>
        <?php if ($_option->getTitle()=="Please select option") { ?>
        <h3 class="edging-title"><span class="cfg-step">STEP 2</span>Please select testoption <a href="/blog/products/" title="What is option?" target="_blank">What is option?</a></h3>
        <?php } else { ?>
        <label<?php if ($_option->getIsRequire()) echo ' class="required"' ?>><?php if ($_option->getIsRequire()) echo '<em>*</em>' ?><?php echo  $this->escapeHtml($_option->getTitle()) ?></label>
        <?php } ?>
    </dt>
    <dd<?php if ($_option->decoratedIsLast){?> class="last"<?php }?>>
        <div class="input-box">
            <?php
            $valuesHtml=$this->getValuesHtml();
            $valuesHtml=str_replace("<ul","<div class='edging-list'",$valuesHtml);
            $valuesHtml=str_replace("</ul>","</div>",$valuesHtml);
            $valuesHtml=str_replace("<li","<div class='edging-list-item'",$valuesHtml);
            $valuesHtml=str_replace("</li>","</div>",$valuesHtml);
            echo $valuesHtml;
            ?>
            <?php if ($_option->getIsRequire()): ?>
                <?php if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO || $_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_CHECKBOX): ?>
                    <span id="options-<?php echo $_option->getId() ?>-container"></span>
                <?php endif; ?>
            <?php endif;?>
        </div>
    </dd>

     

    Magento 2 add custom price in summary section on checkout page

    Step 1) Create di.xml

    <?xml version="1.0"?>
     <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    
    	<type name="MagentoCheckoutModelDefaultConfigProvider">
    	    <plugin name="AddAttPlug" type="[vendor][module]ModelPluginDefaultConfigProvider" />
    	</type>
    </config>

    Step 2) create plugin file DefaultConfigProvider.php

    class DefaultConfigProvider 
    {
    
      /**
        *@var checkoutSession
        */
        protected $checkoutSession;
    
        /**
        *Constructor
        * @param CheckoutSession $checkoutSession
        */
        public function __construct(CheckoutSession $checkoutSession)
        {
            $this->checkoutSession = $checkoutSession;
        }
        public function afterGetConfig(MagentoCheckoutModelDefaultConfigProvider $subject, $config)
        {
        	$objectManager = MagentoFrameworkAppObjectManager::getInstance(); 
            foreach ($config['quoteItemData'] as &$item) {
                $priceHelper = $objectManager->create('MagentoFrameworkPricingHelperData');
                $quoteItem = $this->checkoutSession->getQuote()->getItemById($item['item_id']);
                $price =  $quoteItem->getProduct()->getPrice();
                $formattedPrice = $priceHelper->currency($price, true, false);
                $item['originalprice'] = $formattedPrice;
            }
           return $config;
        }
    }

    Step 3) Override the /vendor/magento/module-checkout/view/frontend/web/js/view/summary/item/details.js to your module

    **
     * Copyright © Magento, Inc. All rights reserved.
     * See COPYING.txt for license details.
     */
    
    define([
        'uiComponent',
        'Magento_Checkout/js/model/quote'
    ], function (Component) {
        'use strict';
    
        return Component.extend({
            defaults: {
                template: 'Magento_Checkout/summary/item/details'
            },
    
            /**
             * @param {Object} quoteItem
             * @return {String}
             */
            getValue: function (quoteItem) {
                return quoteItem.name;
            },
            getItemBaseprice: function (quoteItem) {
                    return this.getPropertyDataFromItem(quoteItem, 'originalprice');
            },
            getPropertyDataFromItem: function (quoteItem, propertyName) {
                    var property,
                        itemDetails;
                    if (quoteItem.hasOwnProperty(propertyName)) {
                        property = quoteItem[propertyName];
                    }
                    var quoteItem = this.getItemFromQuote(quoteItem);
                    if (quoteItem.hasOwnProperty(propertyName)) {
                        property = quoteItem[propertyName];
                    }
                    if (property) {
                        this.storage().set('item_details' + quoteItem.item_id + propertyName, property);
                        return property;
                    }
                    itemDetails = this.storage().get('item_details' + quoteItem.item_id + propertyName);
                    return itemDetails ? itemDetails : false;
                },
                getItemFromQuote: function (item) {
                    var items = quote.getItems();
                    var quoteItems = items.filter(function (quoteItem) {
                        return quoteItem.item_id == item.item_id;
                    });
                    if (quoteItems.length == 0) {
                        return false;
                    }
                    return quoteItems[0];
                }
        });
    });
    

    Step 4) Override the vendor/magento/module-checkout/view/frontend/web/template/summary/item/details.html to your module add the below line.

    <span class="originalprice" data-bind="text: getItemBaseprice($parent)"></span>

     

    Move billing address before the payment method section on checkout page in Magento

    For this, we need to create a plugin to place the billing address section before the payment methods.

    create below file at the located place and paste the below code it

    Path: app/code/Magemonkeys/Babeforepayment/etc/frontend/di.xml

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">    
        <type name="MagentoCheckoutBlockCheckoutLayoutProcessor">
            <plugin name="move_billingaddress" type="MagemonkeysBabeforepaymentPluginBlockCheckoutLayoutProcessor"/>
        </type>
    </config>

    Create a plugin at the located place and paste the below code.

    Path: app/code/Magemonkeys/Babeforepayment/Plugin/Block/Checkout/LayoutProcessor.php

    <?php
    namespace MagemonkeysBabeforepaymentPluginBlockCheckout;
     
    use MagentoCheckoutBlockCheckoutLayoutProcessor as CheckoutLayoutProcessor;
     
    class LayoutProcessor
    {
        
        public function afterProcess(CheckoutLayoutProcessor $subject, array $jsLayout)
        {
            $paymentLayout = $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children'];
     
            if (isset($paymentLayout['afterMethods']['children']['billing-address-form'])) {
    
                $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['beforeMethods']['children']['billing-address-form'] = $paymentLayout['afterMethods']['children']['billing-address-form'];
     
                unset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['afterMethods']['children']['billing-address-form']);
    
            }
     
            return $jsLayout;
        }
    }

    Clear the cache and check the output.

    Magento 2 : custom field data from quote item to order after place order

    Follow below steps to copy data from quote item to order item in Magento 2 through the below plugin

    1. Create an di.xml in : /app/code/Vendor/ModuleName/etc

    <type name="MagentoQuoteModelQuoteItemToOrderItem">
        <plugin name="custom_field_to_order_item" type="VendorModuleNamePluginQuoteCustomFieldToOrderItem"/>
    </type>

    2. Create an CustomFieldToOrderItem.php in : app/code/Vendor/ModuleName/Plugin/Quote

    <?php
    
    namespace VendorModuleNamePluginQuote;
    
    class CustomFieldToOrderItem
    
    {
    	public function aroundConvert(
            MagentoQuoteModelQuoteItemToOrderItem $subject,
            Closure $proceed,
            MagentoQuoteModelQuoteItemAbstractItem $item,
            $additional = []
        ) {
            /** @var $orderItem Item */
            $orderItem = $proceed($item, $additional);
            $orderItem->setCustomField($item->getCustomField());
            return $orderItem;
          }
    
    }