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 generate invoice PDF & save it on server at invoice creation time?

    Follow the below steps to generate invoice PDF & save it on the server at invoice creation time.

    1. Create file event.xml on app/code/Magemonkeys/Saveinvoice/etc

    <?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="sales_order_invoice_save_after">
        <observer name="save_invoice_pdf" instance="MagemonkeysSaveinvoiceObserverSaveinvoice" />
      </event>
    </config>

    2. Create file Saveinvoice.php on app/code/Magemonkeys/Saveinvoice/Observer

    <?php
    namespace MagemonkeysSaveinvoiceObserver;
    
    use MagentoFrameworkEventObserverInterface;
    
    class Saveinvoice implements ObserverInterface
    {
        protected $_pdfInvoiceModel;
        protected $_outputDirectory;
        private $_myPdfStorageSubDirectory = "pdfinvoices";
    
        public function __construct(
            MagentoSalesModelOrderPdfInvoice $pdfInvoiceModel,
            MagentoFrameworkFilesystem $filesystem
            ) {
                $this->_pdfInvoiceModel = $pdfInvoiceModel;
                $this->_outputDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::VAR_DIR);
        }
    
        public function execute(MagentoFrameworkEventObserver $observer)
        {
            try{            
                $invoice = $observer->getEvent()->getInvoice();            
                $pdfContent = $this->_pdfInvoiceModel->getPdf([$invoice])->render();
                //save to file  var/pdfinvoices/[IncrementID].pdf
                $this->_outputDirectory->writeFile($this->_myPdfStorageSubDirectory. "/" . $invoice->getIncrementId() . ".pdf" ,$pdfContent);
            } catch (Exception $e){
                $message = $e->getMessage();
            }
            return $this;
        }
    }

     

    How to solve “The address failed to save. Verify the address and try again.” error in Magento 2?

    You might get this error “The address failed to save. Verify the address and try again.”

    If you can see the exception.log displaying the Email Validation failed error, then you can solve this error by doing some PHP settings.

    If You are a Plesk customer, then go to PHP settings, and then check the field “include_path” and you will see the value “.:/opt/Plesk/php/7.2/share/pear” replace this with “.”. and then press Apply button.

    After performing the above steps, you should overcome the programming error.

    See Attached Screenshot for reference

    Magento 2: move wishlist link after media images in product detail page

    In this article, we are going to move the wishlist link under the media block after view more images.

    The first step is to create file catalog_product_view.xml in custom theme :

    Create app/design/frontend/Magemonkey/theme/Magento_Catalog/layout/catalog_product_view.xml

    <?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="view.addto.wishlist" destination="product.info.media" after="-"/>
        </body>
    </page>

    after executing above step, you need to execute the below command

    php bin/magento cache:flush

    That’s it.

     

    Invalid customer address id at checkout – Magento2

    I focused merely on the solution and I just changed the function validateForCart
    In vendor/magento/module-quote/Model/QuoteAddressValidator.php file :

    from :

     public function validateForCart(CartInterface $cart, AddressInterface $address): void
        {
            $this->doValidate($address, $cart->getCustomerIsGuest() ? null : $cart->getCustomer()->getId());
        }

    to :

    public function validateForCart(CartInterface $cart, AddressInterface $address): void
        {
            $this->doValidate($address, $cart->getCustomerId() ? $cart->getCustomer()->getId() : null );
        }

    It worked for me very well. Let me know if this trick helped you too.

    Magento 2: change default primary buttons color and background in your theme

    Let’s say if you want to change the default primary button color as shown above then we need to override _theme.less file in the app/design/frontend/Mage/Monkey/web/css/source directory and put below code

    /* Primary button */
    @button-primary__background: #000;
    @button-primary__border: 1px solid #000;
    @button-primary__color: #fff;
    @button-primary__hover__background: #fff;
    @button-primary__hover__border: 1px solid #fff;
    @button-primary__hover__color: #000;

    Hope applying the above code will help you to change colors as per your requirements.

    How to Add a Custom Button to Admin Sales Order View in Magento2?

    If you want to add a custom button in the admin order view, then you can follow below steps.

    1. Create file di.xml on app/code/Magemonkeys/Custombutton/etc

    <?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="MagentoBackendBlockWidgetContext">
            <plugin name="add_custom_button_sales_veiw" type="MagemonkeysCustombuttonPluginWidgetContext" sortOrder="1"/>
        </type>
    </config>

    2. Create file Context.php on app/code/Magemonkeys/Custombutton/Plugin/Widget

    <?php
    namespace MagemonkeysCustombuttonPluginWidget;
    
    class Context
    {
        protected $urlBuider;
        public function __construct(
            MagentoFrameworkAppActionContext $context,
            MagentoFrameworkAppRequestHttp $request,
            MagentoFrameworkUrlInterface $urlBuilder
        ) 
        { 
            $this->urlBuilder = $urlBuilder;
            $this->request = $request;
        }
        public function afterGetButtonList(
            MagentoBackendBlockWidgetContext $subject,
            $buttonList
        )
        {        
            if($this->request->getFullActionName() == 'sales_order_view'){
                $buttonList->add(
                    'custom_button',
                    [
                        'label' => __('Custom Button'),
                        'onclick' => 'setLocation('' . $this->getCustomUrl() . '')',
                        'class' => 'ship'
                    ]
                );
            }
    
            return $buttonList;
        }
    
        public function getCustomUrl()
        {        
            $order_id = $this->request->getParam('order_id');
            return $this->urlBuilder->getUrl('modulename/controllername/methodname',array('parameter'=>$order_id));
        }
        
    } ?>

     

    Magento 2: How to Add the filter option value in title on category page?

    Step 1). Create the Vendor/Module/etc/frontend/event.xml in your module

    <event name="controller_action_postdispatch">
       <observer name="change_title_filter" instance="VendorModuleObserverFiltertitle" />
    </event>

    Step 2). Create the Vendor/Module/Observer/Filtertitle.php in your module

    <?php
    
    namespace VendorModuleObserver;
    
    use MagentoFrameworkEventObserverInterface;
    use MagentoFrameworkEventObserver;
    use MagentoFrameworkViewLayoutInterface;
    
    class Filtertitle implements ObserverInterface
    {
        protected $context;
        public function __construct(
            MagentoFrameworkViewElementTemplate $context,
            MagentoFrameworkViewResultPage $resultPage,
            MagentoFrameworkViewPageConfig $pageConfig
        ) {
            $this->pageConfig = $pageConfig;
            $this->resultPageFactory = $resultPage;
            $this->context = $context;
        }  
        public function execute(MagentoFrameworkEventObserver $observer)
        {
            $layout = $this->context->getLayout();
            $pageMainTitle = $layout->getBlock('page.main.title');
            if ($pageMainTitle) {
                $blockfilter = $layout->getBlock('catalog.navigation.state');
                if($blockfilter){
                    $selectedFilters = $blockfilter->getActiveFilters();
                    if (!empty($selectedFilters)){
                        $filters = array();
                        foreach($selectedFilters as $filter){
                            $filters[] = $blockfilter->stripTags($filter->getLabel());
                        }
                        if(count($filters) > 0){
                            $activefilters = __("Your selection: ").implode(" - ", $filters);
                            $pageMainTitle->setPageTitle($activefilters);
                        }
                    }
                }
            }
        }
    }

     

    How to send mail to admin after customer signup front-side in Magento 2?

    By default in Magento 2 does not provide the mail functionality to admin when new customers signup. It means no email will be sent to the admin when a customer registers with the front side.

    If you want to get the mail sent to admin when new customer signup happens then do follow below steps:

    Step 1: Create a registration file like

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

     

    Step 2: Create event file like

    <?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="customer_register_success">
            <observer name="sendmail_toadmin" instance="MagemonkeyMailtoAdminObserverMailtoAdmin"/>
        </event>
    </config>

     

    Step 3: Create module file like Magemonkey/MailtoAdmin/etc/module.xml

    <?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="Magemonkey_MailtoAdmin" setup_version="1.0.0"/>
    </config>

     

    Step 4: Create PHP file in Magemonkey/MailtoAdmin/Observer/MailtoAdmin.php

    <?php
     
    namespace MagemonkeyMailtoAdminCustomObserver;
    
    use MagentoFrameworkEventObserverInterface;
     
    class MailtoAdmin implements ObserverInterface
    {
     
        const XML_PATH_EMAIL_RECIPIENT = 'trans_email/ident_general/email';
        protected $_transportBuilder;
        protected $inlineTranslation;
        protected $scopeConfig;
        protected $storeManager;
         protected $_escaper;
        
        public function __construct(
            MagentoFrameworkMailTemplateTransportBuilder $transportBuilder,
            MagentoFrameworkTranslateInlineStateInterface $inlineTranslation,
            MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
            MagentoStoreModelStoreManagerInterface $storeManager,
            MagentoFrameworkEscaper $escaper
        ) {
            $this->_transportBuilder = $transportBuilder;
            $this->inlineTranslation = $inlineTranslation;
            $this->scopeConfig = $scopeConfig;
            $this->storeManager = $storeManager;
            $this->_escaper = $escaper;
        }
     
        public function execute(MagentoFrameworkEventObserver $observer)
        {
            
            
            $customer = $observer->getData('customer');
            
            $this->inlineTranslation->suspend();
            try
            {
                $error = false;
                
                $sender = [
                    'name' => $this->_escaper->escapeHtml($customer->getFirstName()),
                    'email' => $this->_escaper->escapeHtml($customer->getEmail()),
                ];
                $postObject = new MagentoFrameworkDataObject();
                $postObject->setData($sender);
                $storeScope = MagentoStoreModelScopeInterface::SCOPE_STORE;
                $transport =
                    $this->_transportBuilder
                    ->setTemplateIdentifier('1')
                    ->setTemplateOptions(
                        ['area' => MagentoFrameworkAppArea::AREA_FRONTEND, 
                        'store' => MagentoStoreModelStore::DEFAULT_STORE_ID,]
                    )
                    ->setTemplateVars(['data' => $postObject])
                    ->setFrom($sender)
                    ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
                    ->getTransport();
                $transport->sendMessage(); ;
                $this->inlineTranslation->resume();
                
                
            }
            catch (Exception $e)
            {
                MagentoFrameworkAppObjectManager::getInstance()->get('PsrLogLoggerInterface')->debug($e->getMessage());
            }
        
        }
     
    }

     

    Step 5: Then after run the below commands.

    php bin/magento setup:upgrade
    php bin/magento setup:static-content:deploy
    php bin/magento cache:flush

     

    That’s it…

    Now clean the cache and check it by creating new customer signup. You will find the mail of new customer’s sign up.

    Magento 2.3.5-P2 error cannot use a scalar value as an array in SessionManager.php on line 492

    The following error occurs while we using Redis for session storage Or file session storage :

    Warning: Cannot use a scalar value as an array in /home/web/domains/web.com/public_html/vendor/magento/framework/Session/SessionManager.php on line 492


    – Please follow the below steps to resolve it :

    Step 1: Please first override the following file: vendor/magento/framework/Session/SessionManager.php

    Step 2: Open SessionManager.php and find following function ‘_getHosts()’  replace below line from this function :

    return $_SESSION[self::HOST_KEY] ?? [];

    replace it with:

    return isset($_SESSION[self::HOST_KEY]) ? [$_SESSION[self::HOST_KEY]] : [];
    

    That’s it! The error should be solved now.

     

     

    How to set cookie variable in Magento 2?

    In today’s article we are going to describe that how to create cookie variable and assign value into it. We made a module for it and named it “Magemonkeys_General”

    The first step is to create a block file for this in Cookie.php location which is  app/code/Magemonkeys/General/Block/

    <?php
    namespace MagemonkeysGeneralBlock;
    use MagentoFrameworkViewElementTemplate; 
    
    class Cookie extends MagentoFrameworkViewElementTemplate 
    {
        private $cookieManager;
     
        private $cookieMetadataFactory;
     
        public function __construct(
            MagentoFrameworkStdlibCookieManagerInterface $cookieManager,
            MagentoFrameworkStdlibCookieCookieMetadataFactory $cookieMetadataFactory
        ) {
            $this->cookieManager = $cookieManager;
            $this->cookieMetadataFactory = $cookieMetadataFactory;
        }
     
        public function setCustomCookie($gender = '')
        {
            $publicCookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
            $publicCookieMetadata->setDurationOneYear();
            $publicCookieMetadata->setPath('/');
            $publicCookieMetadata->setHttpOnly(false);
     
            return $this->cookieManager->setPublicCookie(
                'gender',
                $gender,
                $publicCookieMetadata
            );
        }
     
        public function getCustomCookie()
        {
            return $this->cookieManager->getCookie(
                'gender'
            );
        }
    }

    Then create cookie.phtml file in below location app/code/Magemonkeys/General/view/

    Set cookie :

    $blockName = $block->getLayout()->createBlock('MagemonkeysGeneralBlockCookie');
    $setcookie = $blockName->setCustomCookie('man');

    Get cookie :

    $blockName = $block->getLayout()->createBlock('MagemonkeysGeneralBlockCookie');
    echo $getcookie = $blockName->getCustomCookie();

    That’s it.