Question

I am trying to update attribute option label with attribute optionid.

Used below code.

class Attribute
 {
  protected $eavAttributeFactory;
  public function __construct(
   \Magento\Eav\Model\Entity\AttributeFactory $eavAttributeFactory
  ) {
    $this->eavAttributeFactory = $eavAttributeFactory;
 }

public function attributeUpdate() { 
  $attribute_code = 'color';
  $optionid = 12345;
  $option_label = 'red';
  $attr = $this->productAttributeRepository->get($attribute_code );
             $options = $attr->getOptions();
             $values = 0;
             foreach ($options as $option) {
                if ($option->getValue() == $magento_id) {
                    $option->setLabel($option_label);
                    //$option->setStoreLabels([$option_label]);
                    $attr->setOptions([$option]);                               
                    $this->productAttributeRepository->save($attr);                     
                    break;
                }
                $values++;

            }

}

Option id 12345 is Green now. I need to Update to Red. What code i need to use to update label of option. Please anyone help on this. Right now it is updating only in admin end. not for all stores, like in Default store view Label in empty. Thanks

Was it helpful?

Solution

Try to use this below code :

protected $_attributeFactory;

public function __construct(
    ....
    \Magento\Framework\App\Action\Context $context,
    \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attributeFactory
    ....
) {
    ....
    $this->_attributeFactory = $attributeFactory;
    parent::__construct($context);
    ....
}
public function yourFunction()
{
    $attribute_id = 93; //color attribute id
    $attribute = $this->_attributeFactory->load(93);

    $option_id = 213; // your option ID
    $opt_default_name = 'Red Lab';
    $opt_default_store = 'Red Lab';
    // $opt_2nd_store = 'Red Lab German'; //For other store

    $attribute->setData('option', array('value' => array(
        $option_id => array($opt_default_name, $opt_default_store)), //$opt_2nd_store add param here for other store
    ));
    $attribute->save();
}

For more you can take a look at \Magento\Eav\Model\ResourceModel\Entity\Attribute::_saveStoreLabels(AbstractModel $object)

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top