Magento – Magento 2 : Add attribute options programmatically in custom attribute

customer-attributemagento2

I have created custom attribute which type is Select. That attribute is available inside custom eav entity type. I want to add attribute options inside that attribute. How to do that?

Any help would be appreciated.

Best Answer

You can create options for select element while creating the attribute.

Let's take an example:

app/code/Namespace/Modulename/Setup/InstallData.php

<?php
namespace Namespace\Modulename\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;

class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        /**
         * Add attributes to the eav_attribute
         */
        $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY, 'product_select_attribute');
        $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY, 'product_custom_attribute');

        $statusOptions = 'Namespace\Modulename\Model\Config\Source\StatusOptions';
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'product_select_attribute',
            [
                'group' => 'Custom Product Attribute',
                'type' => 'int',
                'backend' => '',
                'frontend' => '',
                'label' => 'Product Status',
                'input' => 'select',
                'class' => '',
                'source' => $statusOptions,
                'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => '',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'is_used_in_grid' => true,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false
            ]
        );
    }
}

In above code i used 'source' => $statusOptions, it is defind select option dynamically.

You need to create Model file for define our custom option of select box, $statusOptions = ‘Namespace\Modulename\Model\Config\Source\StatusOptions’;

create StatusOptions.php file under Model and define our enable and disable option value.

app/code/Namespace/Modulename/Model/Config/Source/StatusOptions.php

<?php
namespace Namespace\Modulename\Model\Config\Source;

use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;

class StatusOptions extends AbstractSource
{
    /**
     * Get all options
     *
     * @return array
     */
    public function getAllOptions()
    {
        if (null === $this->_options) {
            $this->_options=[
                                ['label' => __('Enable'), 'value' => 1],
                                ['label' => __('Disable'), 'value' => 0]
                            ];
        }
        return $this->_options;
    }
}

Run below command :

php bin/magento setup:upgrade

php bin/magento cache:flush

php bin/magento indexer:reindex


Update :

Change below function code for dynamic data

public function getAllOptions()
{
    $collection = $this->CollectionFactory->create();
    foreach ($collection as $item) {
        $this->_options[] = [
                'label' => __($item['title']),
                'value' => $item['id'],
            ];
    }

    return $this->_options;
}

I hope it helps!

Related Topic