What is the right(official) way to programmatically add product attribute option in M2? E.g. for manufacturer product attribute. Obviously existing option would be matched by "Admin" title value.


Here's the approach I've come up with for handling attribute options. Helper class:

namespace My\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
     * @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface
    protected $attributeRepository;

     * @var array
    protected $attributeValues;

     * @var \Magento\Eav\Model\Entity\Attribute\Source\TableFactory
    protected $tableFactory;

     * @var \Magento\Eav\Api\AttributeOptionManagementInterface
    protected $attributeOptionManagement;

     * @var \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory
    protected $optionLabelFactory;

     * @var \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory
    protected $optionFactory;

     * Data constructor.
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository
     * @param \Magento\Eav\Model\Entity\Attribute\Source\TableFactory $tableFactory
     * @param \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement
     * @param \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory $optionLabelFactory
     * @param \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository,
        \Magento\Eav\Model\Entity\Attribute\Source\TableFactory $tableFactory,
        \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
        \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory $optionLabelFactory,
        \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory
    ) {

        $this->attributeRepository = $attributeRepository;
        $this->tableFactory = $tableFactory;
        $this->attributeOptionManagement = $attributeOptionManagement;
        $this->optionLabelFactory = $optionLabelFactory;
        $this->optionFactory = $optionFactory;

     * Get attribute by code.
     * @param string $attributeCode
     * @return \Magento\Catalog\Api\Data\ProductAttributeInterface
    public function getAttribute($attributeCode)
        return $this->attributeRepository->get($attributeCode);

     * Find or create a matching attribute option
     * @param string $attributeCode Attribute the option should exist in
     * @param string $label Label to find or add
     * @return int
     * @throws \Magento\Framework\Exception\LocalizedException
    public function createOrGetId($attributeCode, $label)
        if (strlen($label) < 1) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('Label for %1 must not be empty.', $attributeCode)

        // Does it already exist?
        $optionId = $this->getOptionId($attributeCode, $label);

        if (!$optionId) {
            // If no, add it.

            /** @var \Magento\Eav\Model\Entity\Attribute\OptionLabel $optionLabel */
            $optionLabel = $this->optionLabelFactory->create();

            $option = $this->optionFactory->create();


            // Get the inserted ID. Should be returned from the installer, but it isn't.
            $optionId = $this->getOptionId($attributeCode, $label, true);

        return $optionId;

     * Find the ID of an option matching $label, if any.
     * @param string $attributeCode Attribute code
     * @param string $label Label to find
     * @param bool $force If true, will fetch the options even if they're already cached.
     * @return int|false
    public function getOptionId($attributeCode, $label, $force = false)
        /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
        $attribute = $this->getAttribute($attributeCode);

        // Build option array if necessary
        if ($force === true || !isset($this->attributeValues[ $attribute->getAttributeId() ])) {
            $this->attributeValues[ $attribute->getAttributeId() ] = [];

            // We have to generate a new sourceModel instance each time through to prevent it from
            // referencing its _options cache. No other way to get it to pick up newly-added values.

            /** @var \Magento\Eav\Model\Entity\Attribute\Source\Table $sourceModel */
            $sourceModel = $this->tableFactory->create();

            foreach ($sourceModel->getAllOptions() as $option) {
                $this->attributeValues[ $attribute->getAttributeId() ][ $option['label'] ] = $option['value'];

        // Return option ID if exists
        if (isset($this->attributeValues[ $attribute->getAttributeId() ][ $label ])) {
            return $this->attributeValues[ $attribute->getAttributeId() ][ $label ];

        // Return false if does not exist
        return false;

Then, either in the same class or including it via dependency injection, you can add or get your option ID by calling createOrGetId($attributeCode, $label).

For example, if you inject My\Module\Helper\Data as $this->moduleHelper, then you can call:

$manufacturerId = $this->moduleHelper->createOrGetId('manufacturer', 'ABC Corp');

If 'ABC Corp' is an existing manufacturer, it will pull the ID. If not, it will add it.

UPDATED 2016-09-09: Per Ruud N., the original solution used CatalogSetup, which resulted in a bug starting in Magento 2.1. This revised solution bypasses that model, creating the option and label explicitly. It should work on 2.0+.

  • 3
    It's as official as you're going to get. All of the lookups and option adding go through core Magento. My class is just a wrapper for those core methods that makes them easier to use. – Ryan Hoerr Feb 29 '16 at 15:35
  • 1
    Hi Ryan, you shouldn't set the value on the option, this is the internal id magento uses and I found out the hard way that if you set the value to a string value with a leading number like '123 abc corp' it causes some serious problems due to the implementation of Magento\Eav\Model\ResourceModel\Entity\Attribute::_processAttributeOptions. See for yourself, if you remove the $option->setValue($label); statement from your code, it will save the option, then when you fetch it Magento will return the value from an auto-increment on the eav_attribute_option table. – quickshiftin Sep 12 '16 at 19:37
  • 2
    if I add this in a foreach function, in the second iteration I will get the error "Magento\Eav\Model\Entity\Attribute\OptionManagement::setOptionValue() must be of the type string, object given" – JELLEJ Dec 12 '18 at 14:57
  • 1
    Yes this code not working – Sourav Mar 23 at 11:45
  • 1
    @JELLEJ If you are getting issue Uncaught TypeError: Argument 3 passed to Magento\Eav\Model\Entity\Attribute\OptionManagement::setOptionValue() must be of the type string, object given in foreach function then change $option->setLabel($optionLabel); to $option->setLabel($label); at line 102 – Nadeem0035 Apr 17 at 7:21

Using the Magento\Eav\Setup\EavSetupFactory or even the \Magento\Catalog\Setup\CategorySetupFactory class may lead to the following problem: https://github.com/magento/magento2/issues/4896.

The classes you should use:

protected $_logger;

protected $_attributeRepository;

protected $_attributeOptionManagement;

protected $_option;

protected $_attributeOptionLabel;

 public function __construct(
    \Psr\Log\LoggerInterface $logger,
    \Magento\Eav\Model\AttributeRepository $attributeRepository,
    \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
    \Magento\Eav\Api\Data\AttributeOptionLabelInterface $attributeOptionLabel,
    \Magento\Eav\Model\Entity\Attribute\Option $option
    $this->_logger = $logger;
    $this->_attributeRepository = $attributeRepository;
    $this->_attributeOptionManagement = $attributeOptionManagement;
    $this->_option = $option;
    $this->_attributeOptionLabel = $attributeOptionLabel;

Then in your function do something like this:

 $attribute_id = $this->_attributeRepository->get('catalog_product', 'your_attribute')->getAttributeId();
$options = $this->_attributeOptionManagement->getItems('catalog_product', $attribute_id);
/* if attribute option already exists, remove it */
foreach($options as $option) {
  if ($option->getLabel() == $oldname) {
    $this->_attributeOptionManagement->delete('catalog_product', $attribute_id, $option->getValue());

/* new attribute option */
  $this->_attributeOptionManagement->add('catalog_product', $attribute_id, $this->_option);
  • 1
    Thanks, you are correct. I've updated my answer accordingly. Note that $attributeOptionLabel and $option are ORM classes; you should not inject them directly. The proper approach is to inject their factory class, then create an instance as needed. Also note you aren't using the API data interfaces consistently. – Ryan Hoerr Sep 9 '16 at 14:55
  • 3
    Hi @Rudd, see my comment on Ryan's answer. You don't want to call $option->setValue() as that is for an internal magento option_id field on the eav_attribute_option table. – quickshiftin Sep 12 '16 at 19:42
  • Thank you. That's what I found out too. Will edit my answer accordingly. – Ruud N. Sep 14 '16 at 5:49

tested on Magento 2.1.3.

I didn't find any workable way how to create attribute with options at once. So initially we need to create an attribute and then add options for it.

Inject following class \Magento\Eav\Setup\EavSetupFactory


 /** @var \Magento\Eav\Setup\EavSetup $eavSetup */
 $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

Create new attribute:

        'type' => 'varchar',
        'input' => 'select',
        'required' => false,

Add custom options.

Function addAttribute doesn't return anything useful which can be used in future. So after attribute creation we need to retrieve attribute object by ourself. !!!Important We need it because function expects only attribute_id, but don't want to work with attribute_code.

In that case we need to get attribute_id and pass it to attribute creation function.

$attributeId = $eavSetup->getAttributeId('catalog_product', 'attribute_code');

Then we need to generate options array in the way magento expects:

$options = [
        'values' => [
        'sort_order1' => 'title1',
        'sort_order2' => 'title2',
        'sort_order3' => 'title3',
    'attribute_id' => 'some_id',

As example:

$options = [
        'values' => [
        '1' => 'Red',
        '2' => 'Yellow',
        '3' => 'Green',
    'attribute_id' => '32',

And pass it to function:

  • 3rd param of addAttribute can take the array parameter ['option'] – DWils May 7 at 19:38

This is NOT an answer. Just a workaround.

It assumes that you have access to Magento Backend using browser and you are on the edit attribute page (url looks like admin/catalog/product_attribute/edit/attribute_id/XXX/key..)

Go to Browser console (CTRL + SHIFT + J on chrome) and paste the following code after changing the array mimim.

$jq=new jQuery.noConflict();
var mimim=["xxx","yyy","VALUES TO BE ADDED"];
$jq("#manage-options-panel tbody tr:last-child td:nth-child(3) input").val(b);

-- tested on Magento 2.2.2

Detailed article - https://tutes.in/how-to-manage-magento-2-product-attribute-values-options-using-console/

  • 1
    This is a terrible long term solution. You can't reliably expect those selectors to stay the same. This is a workaround at best, if it actually works as expected. – domdambrogia Apr 21 '18 at 0:24
  • @domdambrogia agree. It is a workaround. – th3pirat3 Apr 23 '18 at 17:26

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.