0

I am using below script to create product attribute with options.

  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $setup = $objectManager->get('Magento\Framework\Setup\ModuleDataSetupInterface');
$eav_setup_factory = $obj->get('Magento\Eav\Setup\EavSetupFactory');

    $setup->startSetup();
    $eavSetup = $eav_setup_factory->create(['setup' => $setup]);
    // Product Attribute
    $eavSetup->addAttribute(
        \Magento\Catalog\Model\Product::ENTITY,
        'customattribute',
        [
            'type' => 'int',
            'label' => 'Custom Attribute Label',
            'backend' => '',
            'input' => 'select',
            'wysiwyg_enabled'   => false,
            'source' => '',
            'required' => false,
            'filterable' => true,
            'sort_order' => 3,
            'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
            'group' => 'custom attribute group',
            'used_in_product_listing' => true,
            'visible_on_front' => true,
            'option'     => [
            'values' => [
                0 => 'Small',
                1 => 'Medium',
                2 => 'Large',
            ]
        ],
        ]
    );

The options are not getting created with the above code. How can we create options?

The attribute is created once used the above code. Also, can we specify the attribute set to this code? by default, it is adding to the Default attribute set.

Can anybody help me with the above issue?

1

First we need to create a installer file name InstallData.php in our custom module Setup folder

app/code/Vendor/Module/Setup

<?php

namespace Vendor\Module\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;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    private $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,'yourcustomattribute_id');
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'yourcustomattribute_id',
            [
                'group' => 'Product Details',
                'type' => 'int',
                'backend' => '',
                'frontend' => '',
                'label' => 'Your Custom Attribute Label',
                'input' => 'select',
                'class' => '',
                'source' => 'Vendor\Module\Model\Config\Source\Options',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => true,
                'user_defined' => false,
                'default' => '',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false
            ]
        );
    }
}

Now we create option source file class Options for custom attribute options list

app/code/Vendor/Module/Model/Config/Source/Options.php

<?php

namespace Vendor\Module\Model\Config\Source;

use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory;
use Magento\Framework\DB\Ddl\Table;

class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{


    public function getAllOptions()
    {
        /* your Attribute options list*/
        $this->_options = [
            ['label' => 'Select Options', 'value' => ''],
            ['label' => 'Option1', 'value' => '1'],
            ['label' => 'Option2', 'value' => '2'],
            ['label' => 'Option3', 'value' => '3'],
        ];
        return $this->_options;
    }

    public function getOptionText($value)
    {
        foreach ($this->getAllOptions() as $option) {
            if ($option['value'] == $value) {
                return $option['label'];
            }
        }
        return false;
    }

    public function getFlatColumns()
    {
        $attributeCode = $this->getAttribute()->getAttributeCode();
        return [
            $attributeCode => [
                'unsigned' => false,
                'default' => null,
                'extra' => null,
                'type' => Table::TYPE_INTEGER,
                'nullable' => true,
                'comment' => 'Custom Attribute Options  ' . $attributeCode . ' column',
            ],
        ];
    }
}

Reference

  • i mam reading option from json, how to parse it? below is the json "Attribute": "Test Attribute", "data_type" :"text", "OptionValues": { "Value": "Advanced Diploma" } – jafar pinjar Jan 11 at 12:35
  • $json_decoded = $this->jsonHelper->jsonDecode($json_encoded); It will return array then you can read it. – Rohan Hapani Jan 11 at 12:38
  • , can we not create attribute with custom rest api? like this magento.stackexchange.com/questions/257047/… – jafar pinjar Jan 11 at 12:53
  • I will look it and give update soon. – Rohan Hapani Jan 11 at 13:23
  • after creating attribute , can we get the attribute_id? – jafar pinjar Jan 11 at 14:16

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.