How to Programmatically Create Attribute Type Drop Down in Magento 2?

  • Posted by Envision Ecommerce
  • /
  • October 27, 2017

This blog post is the 2nd of our “Magento 2 Attribute Creation” blog series, you will now learn how to programmatically create attribute type drop down in Magento 2. If you have not read first blog post “How to Add an Attribute in Magento 2?” yet, we strongly recommend you to do so.

To Programmatically Create Attribute Type Drop Down in Magento 2, you need to follow the coding structure as mentioned below:

$eavSetup->addAttribute(

\Magento\Catalog\Model\Product::ENTITY,

'image_label',

[

'group' => 'General',

'type' => 'int',

'backend' => '',

'frontend' => '',

'label' => 'Select image label',

'input' => 'select',

'class' => '',

'source' => 'Eecom\TestMod\Model\Config\Source\Options',

'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::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

]

);

Source for dropdown will be ‘Eecom\TestMod\Model\Config\Source\Options’, where you have to create the options array for a dropdown.

Eecom -> Namespace

TestMod -> your module

Options.php

<?php

namespace Eecom\TestMod\Model\Config\Source;

use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory;

use Magento\Framework\DB\Ddl\Table;

/**

* Custom Attribute Renderer

*/

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

{

/**

* @var OptionFactory

*/

protected $optionFactory;

/**

* @param OptionFactory $optionFactory

*/

/**

* Get all options

*

* @return array

*/

public function getAllOptions()

{

/* your Attribute options list*/

$this->_options=[ ['label'=>'Select Options', 'value'=>''],

['label'=>'Bestsellers', 'value'=>'0'],

['label'=>'Newest', 'value'=>'1'],

['label'=>'Hot', 'value'=>'2'],

['label'=>'Favourite', 'value'=>'3']

];

return $this->_options;

}

}

}

We recommend you to keep an eye on our next upcoming Magento 2 related blog posts to take your Magento 2 competence to the next level.