cancel
Showing results for 
Search instead for 
Did you mean: 

Magento2 how to use setCustomAttribute properly

Magento2 how to use setCustomAttribute properly

I'm trying to set custom attribute to quote item by method setCustomAttribute from Magento\Quote\Model\Quote\Item. Below is my code

events.xml

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_quote_item_set_product">
        <observer name="product_point_quote" instance="Vendor\Producer\Model\Observer\Sales\Quote\Item\SetCustomAttribute"/>
    </event>
</config>

SetCustomAttribute.php

<?php
namespace Vendor\Producer\Model\Observer\Sales\Quote\Item;

use Magento\Framework\Event\ObserverInterface;


class SetCustomAttribute implements ObserverInterface
{

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $product = $observer->getProduct();
        $quoteItem = $observer->getQuoteItem();
        $quoteItem->setCustomAttribute('producer', $product->getProducer());
    }
}

But it doesn't work. Below is code of setCustomAttribute from Magento\Quote\Model\Quote\Item

public function setCustomAttribute($attributeCode, $attributeValue)
{
    $customAttributesCodes = $this->getCustomAttributesCodes();
    /* If key corresponds to custom attribute code, populate custom attributes */
    if (in_array($attributeCode, $customAttributesCodes)) {
        $attribute = $this->customAttributeFactory->create();
        $attribute->setAttributeCode($attributeCode)
            ->setValue($attributeValue);
        $this->_data[self::CUSTOM_ATTRIBUTES][$attributeCode] = $attribute;
    }
    return $this;
}

It doesn't work because the method getCustomAttributesCodes() returns an empty array. The question is how to use method setCustomAttribute() in the proper way? How to populate array with custom attributes codes from getCustomAttributesCodes()?