1

I have created a script that deletes duplicated option for custom attribute because this attribute product will generate duplicated value after every save or edit of the product so how to proceed to execute this xscript automatically every 1 minute and thanks in advance Here is my code according to what you have suggest :

class Test {

private $_objectManager;

public function __construct(
    \Magento\Framework\ObjectManagerInterface $objectmanager
){
    $this->_objectManager = $objectmanager;
}


public function execute()
{

    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/templog.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    $logger->info("Cron is working !");
    $logger->info(__METHOD__);

    return $this;

    // You can write your code logic here
    $attributeCode = 'choix_prix_product';
    $attribute = $this->_objectManager->create('Magento\Eav\Model\Config')->getAttribute('catalog_product', $attributeCode);
    $options = $attribute->getSource()->getAllOptions();

    foreach ($options as $option) {
        $products = $obj->create('Magento\Catalog\Model\Product')
            ->getCollection()
            ->addAttributeToFilter($attributeCode, $option['value']);

        $productIds = [];
        foreach ($products as $prod) {
            $productIds[] = $prod->getId();
        }


    }
    $duplicateOptions = [];
    foreach ($options as $option) {
        // because the first option can be blank
        if(!empty(trim($option['label']))) {
            $products = $obj->create('Magento\Catalog\Model\Product')
                ->getCollection()
                ->addAttributeToFilter($attributeCode, $option['value']);

            if ($products->count()) {
                $productsCount = $products->count();
            } else {
                $productsCount = 0;
            }

            $duplicateOptions[$option['label']][$option['value']] = $productsCount;
        }
    }
    foreach ($duplicateOptions as $key => $value) {
        if (count($value) > 1) {
            foreach ($value as $k => $v) {
                if ($v == 0) {
                    $duplicateOptions[$key]['delete'][] = $k;
                }
            }

            if (isset($duplicateOptions[$key]['delete'])) {
                /**
                 * if multiple options are in delete array,
                 * i.e. multiple option ids have zero product count
                 */
                if (count($duplicateOptions[$key]['delete']) > 1) {
                    sort($duplicateOptions[$key]['delete']); // sort the array
                    array_shift($duplicateOptions[$key]['delete']); // remove the first item of the array

                    /**
                     * if you assume that the older option id is the duplicate one
                     * then, you keep the older option id in the delete list
                     * and remove the latest/newly-added attribute option from the delete list
                     */
                    // rsort($duplicateOptions[$key]['delete']); // reverse sort the array
                    // array_shift($duplicateOptions[$key]['delete']); // remove the first item of the array
                }

                // DELETE DUPLICATE ATTRIBUTE OPTIONS
                foreach ($duplicateOptions[$key]['delete'] as $optionId) {
                    $optionModel = $obj->get('Magento\Eav\Model\Entity\Attribute\Option')->load($optionId);
                    try {
                        $optionModel->delete();
                        echo '<font color="green">"'.$key.' ('.$optionId.')" duplicate option deleted!</font><br />';
                        $data .= 'Option Value: ' . $key . ', ' . 'Option ID: ' . $optionId;
                        $data .= "\n";
                    } catch(Exception $e) {
                        echo '<font color="red">'. $e->getMessage() .'</font><br />';
                        $data .= $e->getMessage();
                    }
                }
            }
        }
    }



}

}

  • See this link crontab.guru/#*/1__** using this you can make cron expression as per your requirement and copy that expression and past into <schedule></schedule> – Chirag Patel Jul 17 at 12:43
0

Create custom module and follow step by step.

Step1 : app/code/Adamsmage/Cron/etc/crontab.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default"> <!-- Doesn't need to be unique -->
        <job name="cron_example" instance="Adamsmage\Cron\Cron\Example" method="execute">
            <schedule>*/1 * * * *</schedule>
        </job>
    </group>
</config>

Step2 : app/code/Adamsmage/Cron/Cron/Example.php

<?php
namespace Adamsmage\Cron\Cron;
class Example {

    protected $_logger;

    public function __construct(\Psr\Log\LoggerInterface $logger) {
        $this->_logger = $logger;
    }

    public function execute() {
        $this->_logger->info(__METHOD__);

        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/templog.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info("Cron is working !");
        return $this;
    } }

Step3 : run below command to execute cron.

magento cron:run [--group="cron_group_name"]

  • How to call my script in this class – Developper Magento Jul 18 at 6:43
  • add your code in execute function – Anas Mansuri Jul 18 at 6:44
  • i tried this code but i can't see the file /var/log/cron.log and how to know that this code works fine so that the duplicatedoptions are deleted – Developper Magento Jul 18 at 9:52
  • please check now, I update my code. which is generate templog.log file when cron execute. – Anas Mansuri Jul 18 at 13:07
  • ok but i tried you code yesterday i did not find any log file and the option duplicated and not deleted after 1 minute – Developper Magento Jul 19 at 6:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.