Vladimir Fishchenko
There is a common way to add a new product option programmatically.
<?php
// AttributeOptionInterfaceFactory
$option = $this->optionFactory->create();
$option->setLabel($label);
// ProductAttributeOptionManagementInterface
$this->productAttributeOptionManagement->add(
$attributeCode,
$option
);
But it won’t work if a type of attribute is “Swatch”. At least in Magento 2.2.1 and 2.2.2
The problem is already fixed in the development branch and will be available in 2.2.3 and similar 2.1.* release.
But for now, you have to apply the fix by yourself.
You need to rewrite the \Magento\Swatches\Model\Plugin\EavAttribute
class and update setProperOptionsArray
method.
That’s how to do it step by step.
-
Create a new class, for example
VF\BestPractices\Model\Swatches\Plugin\EavAttribute
. -
Rewrite the
setProperOptionsArray
method with the latest version from magento repository, so the class will look like this.<?php namespace VF\BestPractices\Model\Swatches\Plugin; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; /** * Class EavAttribute * * TODO: Temporary fix - remove after update to magento to 2.2.3 or higher */ class EavAttribute extends \Magento\Swatches\Model\Plugin\EavAttribute { /** * {@inheritdoc} */ protected function setProperOptionsArray(Attribute $attribute) { $canReplace = false; if ($this->swatchHelper->isVisualSwatch($attribute)) { $canReplace = true; $defaultValue = $attribute->getData('defaultvisual'); $optionsArray = $attribute->getData('optionvisual'); $swatchesArray = $attribute->getData('swatchvisual'); } elseif ($this->swatchHelper->isTextSwatch($attribute)) { $canReplace = true; $defaultValue = $attribute->getData('defaulttext'); $optionsArray = $attribute->getData('optiontext'); $swatchesArray = $attribute->getData('swatchtext'); } if ($canReplace == true) { if (!empty($optionsArray)) { $attribute->setData('option', $optionsArray); } if (!empty($defaultValue)) { $attribute->setData('default', $defaultValue); } else { $attribute->setData('default', [0 => $attribute->getDefaultValue()]); } if (!empty($swatchesArray)) { $attribute->setData('swatch', $swatchesArray); } } } }
-
Add to your module’s
di.xml
<!-- TODO: Temporary fix - remove after upgrade to magento 2.2.3 or higher --> <type name="Magento\Catalog\Model\ResourceModel\Eav\Attribute"> <plugin name="save_swatches_option_params" type="VF\BestPractices\Model\Swatches\Plugin\EavAttribute"/> </type>
That’s it.