Thursday, 15 December 2022

How to disable MSI in Magento 2.4.X

 

Simple Run the below command to disable MSI.

php -d error_log= -d memory_limit=-1 bin/magento module:disable -f Magento_Inventory Magento_InventoryAdminUi Magento_InventoryAdvancedCheckout Magento_InventoryApi Magento_InventoryBundleProduct Magento_InventoryBundleProductAdminUi Magento_InventoryCatalog Magento_InventorySales Magento_InventoryCatalogAdminUi Magento_InventoryCatalogApi Magento_InventoryCatalogSearch Magento_InventoryConfigurableProduct Magento_InventoryConfigurableProductAdminUi Magento_InventoryConfigurableProductIndexer Magento_InventoryConfiguration Magento_InventoryConfigurationApi Magento_InventoryDistanceBasedSourceSelection Magento_InventoryDistanceBasedSourceSelectionAdminUi Magento_InventoryDistanceBasedSourceSelectionApi Magento_InventoryElasticsearch Magento_InventoryExportStockApi Magento_InventoryIndexer Magento_InventorySalesApi Magento_InventoryGroupedProduct Magento_InventoryGroupedProductAdminUi Magento_InventoryGroupedProductIndexer Magento_InventoryImportExport Magento_InventoryCache Magento_InventoryLowQuantityNotification Magento_InventoryLowQuantityNotificationApi Magento_InventoryMultiDimensionalIndexerApi Magento_InventoryProductAlert Magento_InventoryRequisitionList Magento_InventoryReservations Magento_InventoryReservationCli Magento_InventoryReservationsApi Magento_InventoryExportStock Magento_InventorySalesAdminUi Magento_InventorySalesFrontendUi Magento_InventorySetupFixtureGenerator Magento_InventoryShipping Magento_InventorySourceDeductionApi Magento_InventorySourceSelection Magento_InventorySourceSelectionApi Magento_InventoryLowQuantityNotificationAdminUi Magento_InventoryShippingAdminUi Magento_InventoryGraphQl

Wednesday, 21 September 2022

Magento 2.4.4 Admin Login Responce 302 After Upgrade

 Magento 2.4.4 Admin Login Responce 302 After Upgrade.

Found the issue! In Magento 2.4.4 it seems that a value of "0" for "Max Session Size in Admin" breaks it. Solved this issue for simple run below cli command. After that flush cache.


sudo php bin/magento config:set system/security/max_session_size_admin 2560000

php bin/magento config:set system/security/max_session_size_admin 2560000

Monday, 22 August 2022

Magento 2 Repairing Database Using Magento CLI

You can use the Magento CLI and Magerun 2 like this sample:

Using Magento CLI:

Installs and upgrades data in the DB

php -f bin/magento setup:db-data:upgrade


Installs and upgrades the DB schema

php -f bin/magento setup:db-schema:upgrade 


Checks if DB schema or data requires upgrade

php -f bin/magento setup:db:status 

Wednesday, 6 July 2022

Magento 2 Coding Standard warning fixed

 Magento Coding Standard  warning fixed



First we add DocBlock on all pages at top like this

<?php

/**

 * Copyright © Magento, Inc. All rights reserved.

 * See COPYING.txt for license details.

 */


WARNING | Short description duplicates class property name.

WARNING | Missing short description

WARNING | There must be exactly one blank line before tags

WARNING | Type is not specified


---------------------WARNING | Short description duplicates class property name.

/**

 * Url Builder

 *

 * @var UrlInterface

 */

protected $_urlBuilder;


..........Replace to

/**

 * Builder a Url

 *

 * @var urlBuilder

 */

 

---------------------WARNING | Missing short description

/**

 * @param \Magento\Checkout\CustomerData\Cart $subject

 * @param $result

 *

 * @return mixed

 * @throws LocalizedException

 * @throws NoSuchEntityException

 */

 

 .........Replace to

 

/**

 * After Plugin Get Section Data

 *

 * @param $result

 *

 * @return mixed

 *

 * @throws LocalizedException

 * @throws NoSuchEntityException

 */

 

 

----------------------WARNING | There must be exactly one blank line before tags

 

/**

* After Plugin Get Section Data

*

* @param $result

*

* @return mixed

* @throws LocalizedException

* @throws NoSuchEntityException

*/

 .........Replace to

 

/**

 * After Plugin Get Section Data

 *

 * @param $result

 *

 * @return mixed

 *

 * @throws LocalizedException

 * @throws NoSuchEntityException

 */

 

 ----------------------WARNING | Type is not specified

 

 /**

 * After Plugin Get Section Data

 *

 * @param $result

 *

 * @return mixed

 *

 */

public function afterGetSectionData($result)


............Replace to @param array $result


/**

 * After Plugin Get Section Data

 *

 * @param array $result

 *

 * @return mixed

 *

 */

 more example like this

 /**

 * Validates that forbidden tags are not used in comment

 *

 * @param File $phpcsFile

 * @param int $commentStartPtr

 * @param array $tokens

 * @return bool

 */

private function validateTags(File $phpcsFile, $commentStartPtr, $tokens)


WARNING | Short description must start with a capital letter

/**

 * set cart token

 *

 * @param CartInterface $cart

 *

 * @return CartInterface

 */

 .............. Replace to

/**

 * Set Cart Token

 *

 * @param CartInterface $cart

 *

 * @return CartInterface

 */





WARNING | Line exceeds 120 characters; contains 133 characters

$tcpdf2 = new \Eighteentech\DownloadQuote\Block\Tcpdf\MYTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);


.............. Replace to


$tcpdf2 = new \Eighteentech\DownloadQuote\Block\Tcpdf\MYTCPDF(

            PDF_PAGE_ORIENTATION,

            PDF_UNIT,

            PDF_PAGE_FORMAT,

            true,

            'UTF-8',

            false

        );

        

WARNING | Comment block is missing


public function getCmsFilterContent($value = '')

 

.............. Replace to

 

/**

 * Cms Filter Content

 *

 * @param voide $value

 */

public function getCmsFilterContent($value = '')



WARNING | The use of function unlink() is discouraged


unlink($pdffilepath);


.............. Replace to all files related solution

First you add like this

use Magento\Framework\Filesystem\Io\File;


/** @var File */

private $file;


/**

 * @param File $file

 */

public function __construct(File $file)

{

$this->file = $file;

}


file_exist() can be

$this->file->fileExists($file);


unlink() can be

$this->file->rm($file)


mkdir() can be

$this->file->mkdir($dir)


`dirname() can be

$this->file->dirname($file)


file_put_contents() can be

$this->file->write($filename, $src, $mode)


Thursday, 14 April 2022

Get started PWA Studio with Magento 2

Minimum requirements#

  • Basic knowledge of React
  • Node >= 10.14.1
  • Yarn (recommended) or NPM

Before you can start developing with PWA Studio, make sure you meet the requirements listed on this page.

Note: You must have a version of NodeJS >=10.14.1, and Yarn >=1.13.0. The latest LTS versions of both are recommended.

Reference link: https://developer.adobe.com/commerce/pwa-studio/tutorials/

when checking the yarn version some time is an error below

kuldeep@8DYTVG3:~$ yarn -v

ERROR: There are no scenarios; must have at least one.

Solution:

Fix  'ERROR: There are no scenarios; must have at least one.' run the below command.

sudo apt remove yarn

In my case (Ubuntu 18.04) it was the following:

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt update && sudo apt install yarn

kuldeep@8DYTVG3:~$ yarn -v

1.22.18




Thursday, 24 March 2022

Magento 2 Solved: cluster_block_exception

error: cluster_block_exception [TOO_MANY_REQUESTS/12/disk usage exceeded flood-stage watermark, index has read-only-allow-delete block] .

This error means you do not have enough disk space to store or update data. The flood storage watermark is 95% default, so when it exceeds, the above error is shown and it puts the Elasticsearch into read-only mode. So you need to free up disk space or enlarge it.

Steps to Solve Reindex issue with Elasticsearch: run below cmd

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_cluster/settings -d '{ "transient": { "cluster.routing.allocation.disk.threshold_enabled": false } }'

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

php bin/magento indexer:reindex

Magento 2.2.4 :menu is not showing after upgrade CE To EE

I was found that issue related to Varnish Cache

If we select Store -> Configuration -> Advanced -> System -> Full page cache -> Caching Application Set to Varnish Cache then menu are not appear in home page other then appear on all pages .

Monday, 2 December 2019

Magento 2 Add Attribute Name To Configurable Select Option 'Choose a option..'

Configurable products display 'Choose an option...'. with Attribute option label like 'Color Choose an option...'


You also need to change that text in below file,

vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js
In this file, you need to find _fillSelect method and see "chooseText" value.

element.options[0].innerHTML = this.options.spConfig.chooseText

Replace with below code


var attribute_lable = this.options.spConfig.attributes[element.id.replace(/[a-z]*/, '')]['label']; element.options[0].innerHTML = attribute_lable +' ' + this.options.spConfig.chooseText; 

Thanks,

Wednesday, 16 October 2019

Magento 2: Pub Static CSS files are present but show 404

Resolved after placing the missing .htaccess file in the static folder.

Magento 2 Error error too many redirects in admin login screen

This web page has a redirect loop.

Go to PHP Myadmin

In the "core_config_data" table remove the value of "web/cookie/cookie_domain" and set "web/cookie/cookie_httponly" to "0". 

Clear the cache by 'php -d error_log= -d memory_limit=-1 bin/magento cache:flush'

Thursday, 1 August 2019

Magento 2.3.1 Notice: Undefined index: color_bucket / gift_dropdown_bucket / gift_price_bucket

This is not to be a problem in Magento, but in problem with Elastic-Search.

Magento 2.3.1 Notice: Undefined index: color_bucket / gift_dropdown_bucket / gift_price_bucket \/app\/vendor\/magento\/module-elasticsearch\/SearchAdapter\/Aggregation\/Builder\/Term.php$

Solved :

 Find the attribute gift_dropdown remove _bucket

Go To admin and Store >> Product then search attribute with code.

Use in Search: No

Use In Search Results Layered Navigation No 

Then run the following two commands:

php bin/magento cache:clean

php bin/magento indexer:reindex catalogsearch_fulltext 

if get this warning for another attribute after doing this change. repeat the same process with another attribute.


Thursday, 18 July 2019

Magento 2 : Adding additional store email addresses in the store admin

Magento 2 allows you to set five email addresses in the store admin:

  1. 1.General Contact
  2. Sales Representative
  3. Customer Support
  4. Custom Email 1
  5. Custom Email 2


add more
  • Custom Email 3
  • Custom Email 4
  • Custom Email 5
  • .
  • .
  • .
  • .
  • more.........


Need to create a new module using the below steps
Mycompany/Additionalstoreemail/

registration.php
composer.json
etc/module.xml
etc/adminhtml/system.xml

registration.php
<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Mycompany_Additionalstoreemail',
    __DIR__
);
------------------------------------------------------
composer.json

{
    "name": "mycompany\/additionalstoreemail",
    "description": "Magento 2 Additional Store Email Address",
     "require": {
        "php": "~5.5.22|~5.6.0|7.0.2|7.0.4|~7.0.6|~7.1.0",
        "magento/framework": "100.0.*|100.1.*|101.0.*"
    },
    "type": "magento2-module",
    "version": "1.0.1",
    "license": [
        "OSL-3.0",
        "AFL-3.0"
    ],
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Mycompany\\Additionalstoreemail\\": ""
        }
    }
}

------------------------------------------------------
etc/module.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Mycompany_Additionalstoreemail" setup_version="1.0.1" />
</config>

------------------------------------------------------
etc/adminhtml/system.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="general" translate="label" sortOrder="100">
            <label>General</label>
        </tab>             
        <section id="trans_email" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1">
                   
            <group id="ident_custom3" translate="label" type="text" sortOrder="6" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Custom Email 3</label>
                <field id="email" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Sender Email</label>
                    <validate>validate-email</validate>
                    <backend_model>Magento\Config\Model\Config\Backend\Email\Address</backend_model>
                </field>
                <field id="name" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Sender Name</label>
                    <backend_model>Magento\Config\Model\Config\Backend\Email\Sender</backend_model>
                    <validate>validate-emailSender</validate>
                </field>
            </group>
           
            <group id="ident_custom4" translate="label" type="text" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Custom Email 4</label>
                <field id="email" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Sender Email</label>
                    <validate>validate-email</validate>
                    <backend_model>Magento\Config\Model\Config\Backend\Email\Address</backend_model>
                </field>
                <field id="name" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Sender Name</label>
                    <backend_model>Magento\Config\Model\Config\Backend\Email\Sender</backend_model>
                    <validate>validate-emailSender</validate>
                </field>
            </group>
           
            <group id="ident_custom5" translate="label" type="text" sortOrder="8" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Custom Email 5</label>
                <field id="email" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Sender Email</label>
                    <validate>validate-email</validate>
                    <backend_model>Magento\Config\Model\Config\Backend\Email\Address</backend_model>
                </field>
                <field id="name" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Sender Name</label>
                    <backend_model>Magento\Config\Model\Config\Backend\Email\Sender</backend_model>
                    <validate>validate-emailSender</validate>
                </field>
            </group>           
           
        </section>       
    </system>
</config>

Wednesday, 3 July 2019

Magento 2 : Add WYSISYG Editor Admin Form In Custom Module

<?php
namespace [VENDOR]\[EXTENSION]\Block\Adminhtml\[CUSTOM]\Edit\Tab;

class Form extends \Magento\Backend\Block\Widget\Form\Generic implements \Magento\Backend\Block\Widget\Tab\TabInterface
{
protected $_wysiwygConfig;

public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory, 
\Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
array $data = []
)
{
$this->_wysiwygConfig = $wysiwygConfig;
parent::__construct($context, $registry, $formFactory, $data);
}

protected function _prepareForm()
{
$model = $this->_coreRegistry->registry('EXTENSIONKEY');

/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create();

$fieldset = $form->addFieldset('base_fieldset', ['legend' => __('YOUR FORM TITLE')]);

$fieldset->addField('storycontent', 'editor', [
  'name'      => 'storycontent',
  'label'   => 'Story Content',
  'config'    => $this->_wysiwygConfig->getConfig(),
  'wysiwyg'   => true,
  'required'  => false,
  'after_element_html' => '<small>YOURCOMMENT.</small>',
  'value' => $model->getStorycontent()
]);

$this->setForm($form);
return parent::_prepareForm();
}
}
?>

Monday, 1 July 2019

Magento 2 : Modal Popup Window Call Anywhere

Modal Popup Window Call Anywhere

<a href="#" id="click-header">View Video</a></div>

<div id="header-mpdal" style="display:none;">
<div class="videoWrapper">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/code_hear" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe>
</div>
</div>

<script>
    require(
        [
            'jquery',
            'Magento_Ui/js/modal/modal'
        ],
        function(
            $,
            modal
        ) {
            var options = {
                type: 'popup',
                responsive: true,
                innerScroll: true,
                title: '',
                buttons: [{
                    text: $.mage.__('Close'),
                    class: '',
                    click: function () {
                        this.closeModal();
                    }
                }]
            };

            var popup = modal(options, $('#header-mpdal'));
            $("#click-header").on('click',function(){
                $("#header-mpdal").modal("openModal");
            });

        }
    );
</script>

Magento 2: How to Call a CMS Static Block in Phtml File

Display CMS Static Block In Phtml File:

Here the code to show CMS Static Block in any template (phtml) file in Magento 2,
Display CMS Static Block In Phtml File:

Here the code to show CMS Static Block in any template (phtml) file in Magento 2,

<?php
    echo $block->getLayout()
               ->createBlock('Magento\Cms\Block\Block')
               ->setBlockId('block_identifier')
               ->toHtml();
?>
Display CMS Static Block In CMS Content:

Here the code to show CMS Static Block in any other CMS static block/page in Magento 2,
1

{{block class="Magento\\Cms\\Block\\Block" block_id="block_identifier"}}
Display CMS Static Block In XML:

Here the code to show CMS Static Block in any layout (XML) file in Magento 2,

<referenceContainer name="content">
    <block class="Magento\Cms\Block\Block" name="block_identifier">
        <arguments>
            <argument name="block_id" xsi:type="string">block_identifier</argument>
        </arguments>
    </block>
</referenceContainer>

Wednesday, 8 May 2019

Magento 2 full page cache invalidates every time

We have found a quick fix without any issues. Go To this file and update below changes.

/vendor/magento/module-page-cache/Observer/FlushCacheByTags.php

Line no 57
Replace this function
public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if ($this->_config->getType() == \Magento\PageCache\Model\Config::BUILT_IN && $this->_config->isEnabled()) {
            $object = $observer->getEvent()->getObject();
            if (!is_object($object)) {
                return;
            }
            $tags = $this->getTagResolver()->getTags($object);

            if (!empty($tags)) {
                $this->getCache()->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array_unique($tags));
            }
        }
    }
 
 
To

 
public function execute(\Magento\Framework\Event\Observer $observer)
    {
        if ($this->_config->getType() == \Magento\PageCache\Model\Config::BUILT_IN && $this->_config->isEnabled()) {
            $object = $observer->getEvent()->getObject();
            if (!is_object($object)) {
                return;
            }
            $tags = $this->getTagResolver()->getTags($object);

            if (!empty($tags)) {
                $this->getCache()->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, array_unique($tags));
            }
        }
    }
   

 In both function change only  CLEANING_MODE_MATCHING_ANY_TAG from CLEANING_MODE_MATCHING_TAG   
   
After the update a code it's working in my case.

Magento2 : Reset/Change Magento2 admin password

Solution 1.
Go to phpMyAdmin, select the corresponding database and find admin_user table run the foloing query

UPDATE admin_user SET password = CONCAT(SHA2('xxxxxxxxNewpassword', 256), ':xxxxxxxx:1') WHERE username = ‘adminusername';

Note that each xxxxxxxx sequence should be replaced with any random characters.

Solution 2.
Forgot your password? You can change your forgotten or lost password for the admin account. 

Monday, 1 April 2019

Magento 2 : [SOLUTION] Add Bundle product into Cart Programmatically

We have created a script to add bundle product to the cart, programmatically adding all options to the bundle.

It's a simple code and its work perfectly.

create a text file in root directory and past the code then save and run in a browser. Then check the quote table.

test.php
<?php
ini_set('memory_limit','2048M');
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$params[Bootstrap::PARAM_REQUIRE_MAINTENANCE] = true; // default false
$params[Bootstrap::PARAM_REQUIRE_IS_INSTALLED] = false; // default true

$bootstrap = Bootstrap::create(BP, $params);

$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('global');

$quote = $obj->get('\Magento\Checkout\Model\Cart');

$product_id=66;
$_product = $obj->create('Magento\Catalog\Model\Product')->load($product_id);
 $selectionCollection = $_product->getTypeInstance(true)
                           ->getSelectionsCollection(
    $_product->getTypeInstance(true)->getOptionsIds($_product),$_product);
    // create bundle option
    $cont = 0;
    $selectionArray = [];
    $selectionqtyArray = [];
    $selectionpriceArray = [];
    foreach ($selectionCollection as $proselection){ 
       
                $selectionArray[$cont] = $proselection->getSelectionId();
                $selectionqtyArray[$cont] = $proselection->getSelectionQty();
                $selectionpriceArray[$cont] = $proselection->getPrice();
                $cont++;
            }
    // get options ids
    $optionsCollection = $_product->getTypeInstance(true)
                ->getOptionsCollection($_product);
   
    foreach ($optionsCollection as $options) {
           $id_option = $options->getId();
                }           
    // generate bundle_option array
    $bundle_option = [$id_option => $selectionArray];
    $bundle_qty = [$id_option => $selectionqtyArray];
    $bundle_price = [$id_option => $selectionpriceArray];
   
   
    $params = [
                'product' => $_product->getId(),
                'bundle_option' => $bundle_option,
                'bundle_option_qty' => $bundle_qty,
                'bundle_option_price' => $bundle_price,                           
                'qty' => 1,
                'original_qty' => 1
              ]; 
             
 $quote->addProduct($_product, $params);
 $quote->save();
//echo "<pre>";
//print_r($params);

?>

Please feel free to contact me any M1 & M2 issue at any time.


Regards
Kuldeep Singh
kuldeep4110@gmail.com

Tuesday, 18 September 2018

Magento 2 : [SOLVE] Magento 2.2.* Find and Remove Duplicate Product Images

One of the biggest issue was product image duplicate on 2.2.*  the issue of storage. The below script delete the unused product images.

Create a php file in your magento root directory like '/public_html/findduplicateimage.php' and past the code

<?php

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$params[Bootstrap::PARAM_REQUIRE_MAINTENANCE] = true; // default false
$params[Bootstrap::PARAM_REQUIRE_IS_INSTALLED] = false; // default true

$bootstrap = Bootstrap::create(BP, $params);

$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
$mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();
//echo $mediaPath;

$path = $mediaPath . DIRECTORY_SEPARATOR . "catalog" . DIRECTORY_SEPARATOR . "product";
$product_folder = array();
$di = new RecursiveDirectoryIterator($path);

foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
//echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
if (!is_dir($filename)) {
$folder_file = str_replace($mediaPath, '', $filename);
$folder_file = str_replace('\\', '/', $folder_file);
$product_folder[] = $folder_file;
}
}

// creat and load all product collection
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()
->addAttributeToSelect('*')
->load();

$images_array = array();

foreach ($collection as $product) {
$objectManager->get("Magento\Catalog\Model\Product\Gallery\ReadHandler")->execute($product);
$imageProcessor = $objectManager->create('\Magento\Catalog\Model\Product\Gallery\Processor');
$images = $product->getMediaGalleryImages();
foreach ($images as $child) {
$file_update = str_replace($mediaPath, "", $child->getPath());
$images_array[] = "/" . $file_update;
}
}
// uncoment below code print array all catalog media array & product use media file array
/*echo "<pre>";
print_r($images_array);
echo "<br/>=======";
print_r($product_folder);
echo "</pre>";*/

foreach ($product_folder as $file) {

if (!in_array($file, $images_array)) {
//echo "<br/> Unlink Found File :::: ".unlink($mediaPath . $file); // uncoment the code when remove the file
echo "<br/>Found file :::::: ". $mediaPath ."  ===  ".$file;

}

die("stop");

?>

Sunday, 9 September 2018

Magento 2: [SOLUTION] Order confirmation email contains no FROM or FROM EMAIL address

Confirmation emails have no FROM or FROM email address 2.2.4

Going to : /vendor/magento/module-sales/Model/Order/Email/SenderBuilder.php

 Edit function configureEmailTemplate() and add this line
 $this->transportBuilder->setFrom($this->identityContainer->getEmailIdentity());
 to show like below:

 protected function configureEmailTemplate()
 {
$this->transportBuilder->setTemplateIdentifier($this->templateContainer->getTemplateId());
$this->transportBuilder->setTemplateOptions($this->templateContainer->getTemplateOptions());
$this->transportBuilder->setTemplateVars($this->templateContainer->getTemplateVars());
$this->transportBuilder->setFrom($this->identityContainer->getEmailIdentity()); //the below are commented
//$this->transportBuilderByStore->setFromByStore(
// $this->identityContainer->getEmailIdentity(),
// $this->identityContainer->getStore()->getId()
// );
 }

Its a simple fix and its work perfectly.