How Magento 2 Developers Programmatically Create Attribute Type Drop Down

  • author-img Nidhi Arora
  • 6 years
Programmatically Create Attribute Type Drop Down in Magento 2

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 Our team of certified Magento 2 Developers curates personalized solutions to create excellent drop downs. 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.

Download Blog

ENQUIRY

Ready to Get Started

Communication is the key for us to understand each other. Allow us to understand
your requirements or queries. Present us with an opportunity to serve you.

Fill out the form and out team will get back to you
within 24 hours

    Head Office

    815 Brazos St STE 500, Austin,
    TX 78701, USA