1

i want to edit values of my attributes product so i tried with event after save but nothing changed so i tried this :

<?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="Magento\Catalog\Model\Product\Action">
        <plugin name="update-attributes" type="Md\ConfigAttribute\Model\Plugin\UpdateAttributes" />
    </type>
</config>

and here is my model :

<?php
namespace Md\ConfigAttribute\Model\Plugin;

use Magento\Catalog\Model\Product\Action\Interceptor;


class UpdateAttributes
{
    /**
     * @param Interceptor $interceptor
     * @param \Closure $closure
     * @param $productIds
     * @param $attrData
     * @param $storeId
     * @return Interceptor
     */
    protected $registry;
    private $configurableProductType;
    protected $action;
    public function __construct(

        \Magento\Framework\Registry $registry,
        \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $configurableProductType,
        \Magento\Catalog\Model\ResourceModel\Product\Action $action
    ){

        $this->registry = $registry;
        $this->configurableProductType = $configurableProductType;
        $this->action=$action;
    }

public function aroundUpdateAttributes(
        Interceptor $interceptor,
        \Closure $closure,
        $productIds,
        $attrData,
        $storeId
    ) {

        $_product= $this->registry->registry('current_product');
        $productIds = $_product->getId();
    $result = $closure($productIds, $attrData, $storeId);
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $attributeCode = 'choix_prix_product';

    $attribute = $objectManager->create('Magento\Eav\Model\Config')
        ->getAttribute('catalog_product', $attributeCode);

    $options = $attribute->getSource()->getAllOptions();


    foreach ($options as $option) {
        $products = $objectManager->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 = $objectManager->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 = $objectManager->create('Magento\Eav\Model\Entity\Attribute\Option')->load($optionId);
                        try {
                            $optionModel->delete();
                            echo '<font color="green">"' . $key . ' (' . $optionId . ')" Option Deleted!</font><br />';
                        } catch (Exception $e) {
                            echo '<font color="red">' . $e->getMessage() . '</font><br />';
                        }
                    }
                }
            }
        }
    }
    $_name = $_product->getName();
    $_sku = $_product->getSku();
    $_id = $_product->getId();

    $config = $this->configurableProductType->getParentIdsByChild($_id);// to know if a product is a variant of a configurable product

    if ($config) {


        $optionId = $_product->getData('choix_prix_product');

        $isAttributeExist = $_product->getResource()->getAttribute('choix_prix_product');
        if ($isAttributeExist && $isAttributeExist->usesSource()) {
            $optionText = $isAttributeExist->getSource()->getOptionText($optionId);
        }


        $choixAtt = explode("-", $optionText);
        $var7 = $choixAtt[0];
        $var8=substr($var7,6);



        $choixvalue = substr($var7, 6);

        //add code choice in the sku of article and add the desgnation to the name of the child
        $this->action->updateAttributes([$_id], ['name' => $_name . " " . $var7], $storeId);
        var_dump( $this->action->updateAttributes([$_id], ['name' => $_name . " " . $var7], $storeId));
        die('here');

        //$_product->setName($_name . " " . $var7);

        $newsku= explode("-",$_sku);

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();
        $tableName = $resource->getTableName('table_choix');


        $fields = array('code_choix');


        $sql = $connection->select()
            ->from($tableName, $fields)
            ->where('designation_choix' . '=?', $var8);



        $result = $connection->fetchAll($sql);
        $var9 = $result[0]['code_choix'];
        $sku=$newsku.$var9;


         $_product->setSku($sku);
        $this->action->updateAttributes([$_id], ['sku' => $sku], $storeId);


$_product->save();


    }




        return $result;
    }
}

updated question using event after save

<event name="catalog_product_save_after">
        <observer name="test_name" instance="Md\ConfigAttribute\Observer\Productsaveafter" />
    </event>

and here is my class observer:

<?php

namespace Md

\ConfigAttribute\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{
    private $configurableProductType;
    protected $action;
    protected $_storeManager;

    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\Action $action,
        \Magento\Store\Model\StoreManagerInterface $storeManager,


        \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $configurableProductType
    )
    {

        $this->configurableProductType = $configurableProductType;
        $this->action = $action;
        $this->_storeManager = $storeManager;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getProduct();  // you will get product object
        $_name = $_product->getName();
        $_sku = $_product->getSku();
        $_id = $_product->getId();
        $config = $this->configurableProductType->getParentIdsByChild($_id);// to know if a product is a variant of a configurable product


        if ($config) {


            $optionId = $_product->getData('choix_prix_product');

            $isAttributeExist = $_product->getResource()->getAttribute('choix_prix_product');
            if ($isAttributeExist && $isAttributeExist->usesSource()) {
                $optionText = $isAttributeExist->getSource()->getOptionText($optionId);
            }


            $choixAtt = explode("-", $optionText);
            $var7 = $choixAtt[0];
            $var8 = substr($var7, 6);


            $choixvalue = substr($var7, 6);

            //add code choice in the sku of article and add the desgnation to the name of the child

            $_product->setName($_name . " " . $var7);


            $newsku = explode("-", $_sku);

            /*$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
            $connection = $resource->getConnection();
            $tableName = $resource->getTableName('table_choix');


            $fields = array('code_choix');


            $sql = $connection->select()
                ->from($tableName, $fields)
                ->where('designation_choix' . '=?', $var8);


            $result = $connection->fetchAll($sql);
            $var9 = $result[0]['code_choix'];
            $sku = $newsku . $var9;


            /* $_product->setSku($sku);
           */


        }


    }
}`
  • Can you specify actualy what things you are looking for? – Dhiren Vasoya May 15 at 11:54
  • i want to change the name of the child of configurable product according to custom attribute – Developper Magento May 15 at 12:11
  • Then you can use magento event there. – Dhiren Vasoya May 15 at 12:19
  • yes i tried with event save after but nothing changed – Developper Magento May 15 at 12:22
  • i will put my code – Developper Magento May 15 at 12:22

Your Answer

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

Browse other questions tagged or ask your own question.