Posts

Showing posts from August, 2023

Add Admin User name and Action name in Order Comment Section through Action Performed from Sales Order Grid in Magento 2

  Step 1:  First, we need to create an “events.xml“ file inside our extension at the following path app\code\Vendor\Extension\etc\adminhtml\ Then add the code as follows. <?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_save_after">         <observer name="sales_order_save_after_comment_history_add"           instance="\Vendor\Extension\Observer\OrderSaveAfter" />     </event> </config> Step 2:  After that, we need to create an “OrderSaveAfter.php” file inside our extension at the following path app\code\Vendor\Extension\Observer\ And embed the code as given below. <?php  namespace Vendor\Extension\Observer;   use Magento\Framework\Event\ObserverInterface; use Magento\Framework\App\RequestInterface; use Magento\Backen...

How to Remove JS and CSS using Layout XML in Magento 2

 Step 1: Go to your layout file app\code\Vendor\Extension\view\frontend\layout\your_layout_file.xml  To remove JS and CSS, you need to add <remove> tag in layout XML under the <head> tag. <?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">       <head>         <remove src="Vendor_Extension::css/custom.css"/>         <remove src="Vendor_Extension::js/custom.js"/>     </head>   </page>

How to Add Editable Field in Admin Order View Page in Magento 2

 Step 1: Go to the below file path app\code\Vendor\Extension\view\adminhtml\layout\sales_order_view.xml Then add the 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>         <referenceBlock name="order_additional_info">             <block class="Vendor\Extension\Block\Adminhtml\Order\Checkoutcustomformedit" name="admin.chekoutcustomfield" template="Vendor_Extension::checkoutcustomformedit.phtml" />         </referenceBlock>     </body> </page> Step 2: Next, move to the following file path app\code\Vendor\Extension\Block\Adminhtml\Order\Checkoutcustomformedit.php Now add the below-mentioned code snippet <?php namespace Vendor\Extension\Block\Adminhtml\Order;   use \Magento\Backend\Block\Templa...

How to Get Product Attribute List using Attribute Set ID in Magento 2

 <?php use \Magento\Framework\AppInterface; try { require __DIR__ . '/../app/bootstrap.php';  } catch (\Exception $e) { echo 'Autoload error: ' . $e->getMessage(); exit(1); } try { $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $appState = $objectManager->get('\Magento\Framework\App\State'); $appState->setAreaCode('frontend'); $productAttributesManagement = $objectManager->get('\Magento\Catalog\Api\ProductAttributeManagementInterface'); $productAttributesRepository = $objectManager->get('\Magento\Catalog\Api\ProductAttributeRepositoryInterface'); $attrubuteOptionRepository = $objectManager->get('\Magento\Catalog\Model\Product\Attribute\Repository'); $productAttributes = $productAttributesManagement->getAttributes(9); // enter attribute id $attributeData = array(); foreach($productAttributes as $key=>$val...

How to Join Two Tables and Create Admin Grid using UI Component in Magento 2

 Step 1: Firstly, you need to edit the di.xml file. For that go to the below path app/code/Vendor/Extension/etc/di.xml Now add the code as follows <?xml version="1.0"?>   <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">     <!-- here we remove virtualType and defile collection as follow-->     <type name="Vendor\Extension\Model\ResourceModel\Custom\Grid\Collection">         <arguments>             <argument name="mainTable" xsi:type="string">magecomp_customtable</argument>             <argument name="eventPrefix" xsi:type="string">magecomp_grid_collection</argument>             <argument name="eventObject" xsi:type="string">magecomp_collection</argument>           ...

How to Set and Get Cookie in Magento 2

 <?php namespace Vendor\Extension\Model; class Customcookie {     private $customCookieManager;     private $customCookieMetadataFactory;     public function __construct(         \Magento\Framework\Stdlib\CookieManagerInterface $customCookieManager,         \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $customCookieMetadataFactory)    {         $this->customCookieManager = $customCookieManager;         $this->customCookieMetadataFactory = $customCookieMetadataFactory;     }     public function setCookie()     {         $customCookieMetadata = $this->customCookieMetadataFactory->createPublicCookieMetadata();         $customCookieMetadata->setDurationOneYear();         $customCookieMetadata->setPath('/');         $customCookieMe...

How to Reset Customer Password using Console Command in Magento 2

 Step 1: First, we need to create a “di.xml” file inside the extension etc directory of our extension. app\code\Vendor\Extension\etc Then add the below code <?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="Vendor\Extension\Command\Changepasswordcommand">         <arguments>             <argument name="resource" xsi:type="object">Magento\Customer\Model\ResourceModel\Customer\Proxy</argument>         </arguments>     </type>     <type name="Magento\Framework\Console\CommandList">         <arguments>             <argument name="commands" xsi:type="array">                 ...

How to Move Category Position Programmatically in Magento 2

 <?php use Magento\Framework\AppInterface; try {     require_once __DIR__ . '/app/bootstrap.php'; }  catch (\Exception $e)  {     echo 'Autoload error: ' . $e->getMessage();     exit(1); } try { $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $appState = $objectManager->get('\Magento\Framework\App\State'); $appState->setAreaCode('frontend');        $category = $objectManager->get('\Magento\Catalog\Api\CategoryManagementInterface'); $categoryId = 5; //id of The category to be moved         $parentId = 6; //id of parent category where the new category to move         $afterId = 7; //id of category after which you want to move                  $CategoryMoveSuccess = $category->move($categoryId, $parentId, $afterId);       ...

How to Get Invoice Comments List Programmatically in Magento 2

 Steps to Get Invoice Comments List Programmatically in Magento 2: Step 1: First, create an Invoicecomments.php file inside the Model folder. app\code\Vendor\Extension\Model Now, add the code as follows <?php namespace Vendor\Extension\Model;   use Magento\Sales\Api\InvoiceManagementInterface; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Sales\Api\Data\InvoiceCommentSearchResultInterface; class Invoicecomments {     private $invoice;     public function __construct(         InvoiceManagementInterface $invoice     ) {         $this->invoice = $invoice;     }          public function getInvoiceComments($invoiceId): ?InvoiceCommentSearchResultInterface     {            $invoiceComments = null;         try {             $invoiceComments = $this->invoice->g...

How to Disable Empty Category Programmatically using Root Script in Magento 2

 <?php use Magento\Framework\AppInterface; try {        require_once __DIR__ . '/app/bootstrap.php'; }  catch (\Exception $e)  {        echo 'Autoload error: ' . $e->getMessage();        exit(1); } try {        $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);        $objectManager = $bootstrap->getObjectManager();        $appState = $objectManager->get('\Magento\Framework\App\State');        $appState->setAreaCode('frontend');        $Collectionfactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');        $Categoryfactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');        $Categorydisable=false;        $categories=$Collectionfactory->create()-...

How to Add URL Rewrite for Product Programmatically using Root Script in Magento 2

 <?php use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; try{     $bootstrap = Bootstrap::create(BP, $_SERVER);     $objectManager = $bootstrap->getObjectManager();     $state = $objectManager->get('Magento\Framework\App\State');     $state->setAreaCode('frontend');     $productIds = ['1','2']; // Product Ids     foreach($productIds as $productId){         $urls = [];         $product = $objectManager->create(\Magento\Catalog\Model\Product::class)->load($productId);         $urls[] = $objectManager->create(\Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator::class)->generate($product);           $urlPersist = $objectManager->create(\Magento\UrlRewrite\Model\UrlPersistInterface::class);         $urlPersist->replace(array_merge([], ...$urls));    ...

How to Create Custom Indexer in Magento 2

 app\code\Vendor\Extension\etc\ Now, add the code as follows <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Indexer/etc/indexer.xsd">     <indexer id="vendor_extension_indexer" view_id="vendor_extension_indexer" class="Vendor\Extension\Model\Indexer" shared_index="vendor_extension_indexer">         <title translate="true">Custom Indexer Title</title>         <description translate="true">Custom Indexer Description</description>     </indexer> </config> Let us see in detail all attributes of the indexer.xml file: id: unique indexer id. view_id: id of the view element, which is defined in mview.xml file class: Add a class of indexer method. shared_index: To improve performance if your indexer is related to another indexer. title: Add title of indexer. descri...

How to Filter Order Collection by Specific Product Item Name in Magento 2

 Steps to Filter Order Collection by Specific Product Item Name in Magento 2: Step 1: Create a file in your Magento root directory at the below path magento_root_directory\getOrderItem.php Then add the code as follows <?php use Magento\Framework\App\Bootstrap; require_once __DIR__ . '/../app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER);   $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend');   try {  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();  $productname='test 2'; // Replace with product name you want to search  $orderdata = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory')->create()->addAttributeToSelect('*');  $orderdata->getSelect()->join(array('order_item' => 'sales_order_item'),'main_table.entity_id = order_item.order_...

How to Add Sign Out Tab in Customer Account in Magento 2

 <?xml version="1.0"?>  <page layout="2columns-left" xmlns xsi="http://wwww3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/ete/page_configuration.xsd">      <body>         <referenceBlock name="customer_account_navigation">              <block class="Magento\Framework\View\Element\Html\Link\Current" name="customer-account-navagation-signout-link">                 <arguments>                     <argument name="path" xsi:type="string">customer/account/logout</argument>                     <argument name="label" xsi:type="string" translate="true">Sign Out</argument>                 </arguments>     ...

How to Pre-select Default Payment Method at the Checkout Page in Magento 2

  var config = {     config: {         mixins: {             'Magento_Checkout/js/model/checkout-data-resolver': {                 'Vendor_Extension/js/model/checkout-data-resolver': true             }         }     } }; Step 2: After that, we must create a “checkout-data-resolver.js” file inside the extension at the following path. app\code\Vendor\Extension\view\frontend\web\js\model Now add the code as given below define([     'Magento_Checkout/js/model/payment-service',     'Magento_Checkout/js/checkout-data',     'Magento_Checkout/js/action/select-payment-method' ], function(     paymentService,     checkoutData,     selectPaymentMethodAction ) {     'use strict';       return function(checkoutDataResolver) {         ...

How to Add Custom Button in Backend CMS Page Section in Magento 2

 Steps to Add Custom Button in Backend Category Page Section in Magento 2: Step 1: First, we need to create a category form.xml file inside the extension at the following path. app\code\Vendor\Extension\view\adminhtml\ui_component Then add the code as follows <?xml version="1.0" encoding="UTF-8"?> <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">     <fieldset name="search_engine_optimization" sortOrder="30">         <container name="custom_button_container" sortOrder="135">             <htmlContent name="html_content">                 <argument name="block" xsi:type="object">Vendor\Extension\Block\Adminhtml\Category\Edit\Categorybutton</argument>             </htmlContent>         </cont...

How to Update Product Attribute using Data Patch in Magento 2

 Steps to Update Product Attribute using Data Patch in Magento 2: Step 1: First, create the ColorAttribute.php file inside the Setup folder app\code\Vendor\Extension\Setup\Patch\Data Then add the below code <?php namespace Vendor\Extension\Setup\Patch\Data;   use Magento\Eav\Setup\EavSetup; use Magento\Catalog\Model\Product; use Magento\Eav\Setup\EavSetupFactory; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\Patch\DataPatchInterface;   class ColorAttribute implements DataPatchInterface {     private $moduleDataSetup;     private $eavSetupFactory;       public function __construct(         ModuleDataSetupInterface $moduleDataSetup,         EavSetupFactory $eavSetupFactory     ) {         $this->moduleDataSetup = $moduleDataSetup;         $this->eavSetupFactory = $eavSetupFactory;       } ...

How to Programmatically Export CSV File Category Name with Parent Category Name

  <?php use Magento\MediaStorage\Helper\File\Storage\Database; use Magento\Framework\AppInterface; try {     require_once __DIR__ . '/app/bootstrap.php'; } catch (\Exception $e) {     echo 'Autoload error: ' . $e->getMessage();     exit(1); } try {     header("Content-type: text/csv");     header("Content-Disposition: attachment; filename=category_level.csv");     header("Pragma: no-cache");     header("Expires: 0");     $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);     $objectManager = $bootstrap->getObjectManager();     $appState = $objectManager->get('\Magento\Framework\App\State');     $appState->setAreaCode('frontend');         $categoryData = [];     $rootCategoryId = 2; //Pass Root Category Id     $categoryManagement = $objectManager->get('Magento\Catalog\Api\CategoryManagementInterface'...

How to Add Image Field on CMS Page in Magento 2?

 Steps to Add Image Field on CMS Page in Magento 2: Step 1: In the first step, we need to create a db_schema.xml file inside the extension at the following path. {{magento_root}}/app/code/Vendor/Module/etc/db_schema.xml Now add the code as follows. <?xml version="1.0"?> <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">     <table name="cms_page" resource="default" engine="innodb" comment="Cms Page">         <column length="255" name="custom_image" nullable="false" xsi:type="varchar"/>     </table> </schema> Step 2: After that, we need to create a cms_page_form.xml to define the CMS page form with the image field File inside the extension at the following path. {{magento_root}}/app/code/Vendor/Module/view/adminhtml/ui_component/cms_page_f...

Magento 2 Export Product CSV File Permission Issue

  1 Steps to Solve Magento 2 Export Product CSV File Permission Issue: 2 Conclusion: Steps to Solve Magento 2 Export Product CSV File Permission Issue: Step 1: First, you must create a di.xml file in the path below. app/code/Vendor/Extension/etc/adminhtml/di.xml And add the following code <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">     <preference for="Magento\ImportExport\Controller\Adminhtml\Export\File\Download" type="Vendor\Extension\Controller\Adminhtml\Export\File\Download" /> </config> Step 2: After that, you must create a preference file in the following path. app/code/Vendor/Extension/Controller/Adminhtml/Export/File/Download.php Then add the below-mentioned code snippet <?php /**  * Copyright © Magento, Inc. All rights reserved.  * See COPYING.txt for license details.  */ declar...

How to Create a Directory Programmatically in Magento 2?

 <?php namespace Vendor\Extension\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\Filesystem; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Filesystem\Directory\WriteInterface; class CreateDirectory extends AbstractHelper {      protected $file;     protected $newCreateDirectory;     public function __construct(         Filesystem $file     ) {         $this->newCreateDirectory = $file->getDirectoryWrite(DirectoryList::VAR_DIR);     }     public function createDirectory()     {         $directoryPath = "magecomp";         $newCreateDirectory = false;         try         {             $newCre...

How to Check if Customer is Logged in or Not

  <?php namespace Vendor\Extension\Helper; class Data  {     public function __construct(        \Magento\Framework\App\Http\Context $httpContext     ) {         $this->httpContext = $httpContext;     }     public function getLogin() {         return $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);     } ?> ------------------------------------------------------------------------------------ <?php    use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php';   try {     $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);     $objectManager = $bootstrap->getObjectManager();     $appState = $objectManager->get('\Magento\Framework\App\State');     $appState->setAreaCode('frontend');       $objectManager = \Magento\F...

How to Move Cart Total Below Cart Items in Checkout Page

 <?xml version="1.0" encoding="UTF-8"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">    <body>       <referenceBlock name="checkout.root">          <arguments>             <argument name="jsLayout" xsi:type="array">                <item name="components" xsi:type="array">                   <item name="checkout" xsi:type="array">                      <item name="children" xsi:type="array">                         <item name="sidebar" xsi:type="array">                           ...

How to Get all the Child Categories IDs of the Specific Category in Magento 2?

 Steps to Get all the Child Categories IDs of the Specific Category in Magento 2: Say, you have the following categories in your Magento 2 store. categories To get category IDs, follow the below step. Step 1: Create a file in your Magento root directory at the below path magento_root_directory\getcategory.php Then add the code as follows. <?php   use Magento\Framework\AppInterface; ini_set('display_errors', TRUE); try {     require_once __DIR__ . '/app/bootstrap.php'; } catch (\Exception $e) {     echo 'Autoload error: ' . $e->getMessage();     exit(1); }   try {     $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);     $objectManager = $bootstrap->getObjectManager();     $appState = $objectManager->get('\Magento\Framework\App\State');     $appState->setAreaCode('frontend');          $categoryFactory = $objectManager->get('\Magento\Catalog\Mo...

How to Add Additional Text Based on Selected Shipping Methods in the Checkout in Magento 2

 Steps to Add Additional Text Based on Selected Shipping Methods in the Checkout in Magento 2: Step 1: Create a Template file in the path given below.   {{magento_root}}\app\code\Vendor\Extension\view\frontend\web\template\shipping-info.html And add the code as follows. <div class="free-shipping-info" data-bind="visible: showFreeShippingInfo()" style="display: none;">     <div class="step-title" data-role="title" data-bind="i18n: 'Free Shipping Information'"></div>     <p class="desc" data-bind="i18n: 'Here add custom Free shipping text..'"></p> </div> <div class="table-rate-shipping-info" data-bind="visible: showTableRateShippingInfo()" style="display: none;">     <div class="step-title" data-role="title" data-bind="i18n: 'Table Rate Delivery'"></div>     <p class=...