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.

Magento 2 : [SOLUTION] Tier price saving percentage wrong when Tax/Vat is included in price

Solution:

Magento2 ver. 2.1.5, 2.1.7 

Going to 'vendor/magento/module-catalog/Pricing/Price/TierPrice.php

Line No 209

public function getSavePercent(AmountInterface $amount)
    {
       return ceil(
            100 - ((100 / $this->priceInfo->getPrice(FinalPrice::PRICE_CODE)->getValue())
                * $amount->getBaseAmount())
        );        
       

    }


Replace to :

public function getSavePercent(AmountInterface $amount)
    {
        /*return ceil(
            100 - ((100 / $this->priceInfo->getPrice(FinalPrice::PRICE_CODE)->getValue())
                * $amount->getBaseAmount())
        );*/
        
        $productPriceAmount = $this->priceInfo->getPrice(
            FinalPrice::PRICE_CODE
        )->getAmount();

        return round(
            100 - ((100 / $productPriceAmount->getValue()) * $amount->getValue())
        );

    }


Wednesday, 2 May 2018

Magento 2 : How to get associated products of a grouped product in product list page

The following sample code how to load a group product by object manager and get all child products (associated simple products) as an array.


$product_id = $_product->getId();
$groupedProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
$_children=$groupedProduct->getTypeInstance()->getAssociatedProducts($groupedProduct);
                                    if(count($_children)>0){                                      
                                    foreach ($_children as $child){
                                    echo "Here are your child Product Ids ".$child->getID()."\n";                                       
                                        }                                      

                                    }