I have shared the tutorial to create product attribute in Magento 2 earlier. However, developers may need to create multi-select product attributes in Magento 2 development tasks.
Developing multi select product attributes may be required a number of times. For example, you want to develop an extension to allow the selection of more than one customer groups, locations, or select multiple options to apply a rule on.
There is no limit when it comes to how you use this solution as per your business or client requirements. Like we use to Magento 2 week days list system configuration for the admin to select the days of the week to book appointment or offer delivery, etc.
The programmatic method to do so makes the task easier and quicker.
Method to Programmatically Create Multi Select Product Attribute in Magento 2:
1. Create InstallData.php file at Vendor\Extension\Setup\ folder
<?php namespace Vendor\Extension\Setup; use Magento\Eav\Setup\EavSetupFactory; use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; class InstallData implements InstallDataInterface { private $eavSetupFactory; public function __construct(EavSetupFactory $eavSetupFactory) { $this->eavSetupFactory = $eavSetupFactory; } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Catalog\Model\Product::ENTITY, 'eway_option', [ 'group' => 'Groupe Name', 'label' => 'Multiselect Attribute', 'type' => 'text', 'input' => 'multiselect', 'source' => 'Vendor\Extension\Model\Config\Product\Extensionoption', 'required' => false, 'sort_order' => 30, 'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_STORE, 'used_in_product_listing' => true, 'backend' => 'Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend', 'visible_on_front' => false ] ); $setup->endSetup(); } }
2. Create Extensionoption.php file at Vendor\Extension\Model\Config\Product folder
<?php namespace Vendor\Extension\Model\Config\Product; use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; class Extensionoption extends AbstractSource { protected $optionFactory; public function getAllOptions() { $this->_options = []; $this->_options[] = ['label' => 'Label 1', 'value' => 'value 1']; $this->_options[] = ['label' => 'Label 2', 'value' => 'value 2']; return $this->_options; } }
With the above code you can create multi select product attributes as shown below:

I’d be very grateful if you helped share this helpful post on social media to fellow developers!
Thanks!