October 09, 2021

Pankaj Rajpurohit 0

In this tutorial I’m explain you how we can create Multi select product attribute. Many times merchants have requirement to display multi selected attribute option value in product detail page like in product specification tab and many more.

We can also create product attributes from admin side in attribute page which is located in Admin System > Attributes > Product path. If we have multiple instances for project development like staging and production then its good practice to make product attribute Programmatically using data patch so it will be installed when deploying an update in a specific instance otherwise we have to create product attribute manually in every instance.

In order to create product Multi-select attribute we need to create a small module for it and steps are below.

1) Create registration.php file inside app/code/Vendor/Extension directory

<?php
	\Magento\Framework\Component\ComponentRegistrar::register(
	    \Magento\Framework\Component\ComponentRegistrar::MODULE,
	    'Vendor_Extension',
	    __DIR__
	);

2) Create module.xml file inside app/code/Vendor/Extension/etc/ directory

<?xml version="1.0"?>
	<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	    <module name="Vendor_Extension" setup_version="1.0.0" />
	</config>

3) Create MultiSelectProductAttribute.php file inside app/code/Vendor/Extension/Setup/Patch/Data

<?php
	declare(strict_types=1);

	namespace Vendor\Extension\Setup\Patch\Data;

	use Magento\Catalog\Api\AttributeSetManagementInterface;
	use Magento\Catalog\Model\Product;
	use Magento\Eav\Api\AttributeGroupRepositoryInterface;
	use Magento\Eav\Api\Data\AttributeGroupInterfaceFactory;
	use Magento\Eav\Api\Data\AttributeSetInterfaceFactory;
	use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
	use Magento\Eav\Setup\EavSetup;
	use Magento\Eav\Setup\EavSetupFactory;
	use Magento\Framework\Exception\InputException;
	use Magento\Framework\Exception\LocalizedException;
	use Magento\Framework\Exception\NoSuchEntityException;
	use Magento\Framework\Setup\ModuleDataSetupInterface;
	use Magento\Framework\Setup\Patch\DataPatchInterface;
	use Magento\Framework\Setup\Patch\PatchRevertableInterface;

	class MultiSelectProductAttribute implements DataPatchInterface, PatchRevertableInterface
	{
	    const MULTISELECT_PRODUCT_ATTRIBUTE = 'availability';

	    /**
	     * @var ModuleDataSetupInterface
	     */
	    private $moduleDataSetup;
	    /**
	     * @var EavSetupFactory
	     */
	    private $eavSetupFactory;
	    /**
	     * @var AttributeSetInterfaceFactory
	     */
	    private $attributeSetFactory;
	    /**
	     * @var AttributeSetManagementInterface
	     */
	    private $attributeSetManagement;
	    /**
	     * @var AttributeGroupInterfaceFactory
	     */
	    private $attributeGroupFactory;
	    /**
	     * @var AttributeGroupRepositoryInterface
	     */
	    private $attributeGroupRepository;
	    /**
	     * @var Product
	     */
	    private $product;

	    /**
	     * Constructor
	     *
	     * @param ModuleDataSetupInterface $moduleDataSetup
	     * @param EavSetupFactory $eavSetupFactory
	     * @param Product $product
	     * @param AttributeSetInterfaceFactory $attributeSetInterfaceFactory
	     * @param AttributeSetManagementInterface $attributeSetManagement
	     * @param AttributeGroupInterfaceFactory $attributeGroupFactory
	     * @param AttributeGroupRepositoryInterface $attributeGroupRepository
	     */
	    public function __construct(
	        ModuleDataSetupInterface          $moduleDataSetup,
	        EavSetupFactory                   $eavSetupFactory,
	        Product                           $product,
	        AttributeSetInterfaceFactory      $attributeSetInterfaceFactory,
	        AttributeSetManagementInterface   $attributeSetManagement,
	        AttributeGroupInterfaceFactory    $attributeGroupFactory,
	        AttributeGroupRepositoryInterface $attributeGroupRepository
	    ) {
	        $this->moduleDataSetup = $moduleDataSetup;
	        $this->eavSetupFactory = $eavSetupFactory;
	        $this->product = $product;
	        $this->attributeSetFactory = $attributeSetInterfaceFactory;
	        $this->attributeSetManagement = $attributeSetManagement;
	        $this->attributeGroupFactory = $attributeGroupFactory;
	        $this->attributeGroupRepository = $attributeGroupRepository;
	    }

	    /**
	     * {@inheritdoc}
	     */
	    public static function getDependencies()
	    {
	        return [

	        ];
	    }

	    /**
	     * {@inheritdoc}
	     */
	    public function apply()
	    {
	        $this->moduleDataSetup->getConnection()->startSetup();
	        /** @var EavSetup $eavSetup */
	        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
	        $attributes = [
	            self::MULTISELECT_PRODUCT_ATTRIBUTE => [
	                'type' => 'varchar',
	                'label' => 'Availability',
	                'input' => 'multiselect',
	                'source' => '',
	                'required' => true,
	                'filterable' => false,
	                'visible_on_front' => false,
	                'used_in_product_listing' => false,
	                'attribute_group_name' => 'General',
	                'backend' => 'Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend',
	                'apply_to' => 'simple,configurable,virtual,bundle,downloadable,grouped,giftcard',
	                'options' => [
	                    'Sunday',
	                    'Monday',
	                    'Tuesday',
	                    'Wednesday',
	                    'Thursday',
	                    'Friday',
	                    'Saturday',
	                ]
	            ]
	        ];
	        $this->createProductAttribute($attributes);
	        $this->moduleDataSetup->getConnection()->endSetup();
	    }

	    /**
	     * Create Attribute
	     * @param $attributes
	     * @throws LocalizedException
	     */
	    private function createProductAttribute($attributes)
	    {
	        foreach ($attributes as $attribute => $data) {

	            /** @var EavSetup $eavSetup */
	            $eavSetup = $this->eavSetupFactory->create();
	            $productEntity = Product::ENTITY;
	            $attrSetName = null;
	            $attributeGroupId = null;

	            /**
	             * Initialise Attribute Set Id
	             */
	            if (isset($data['attribute_set_name'])) {
	                $attributeSetId = $eavSetup->getAttributeSetId($productEntity, $data['attribute_set_name']);

	                /**
	                 * If our attribute set name does not exist, we create it.
	                 * By default if Magento does not find an attribute set Id, it returns the default attribute set Id
	                 */
	                if ($attributeSetId == $eavSetup->getDefaultAttributeSetId($productEntity)
	                                                                    && $data['attribute_set_name'] != 'Default') {
	                    $attrSetName = $data['attribute_set_name'];
	                    $this->createAttributeSet($attrSetName);
	                    $attributeSetId = $eavSetup->getAttributeSetId($productEntity, $attrSetName);
	                }
	            } else {
	                $attributeSetId = $this->product->getDefaultAttributeSetId();
	            }

	            /**
	             * Initialise Attribute Group Id
	             */
	            if (isset($data['attribute_group_name'])) {
	                $attributeGroupId = $eavSetup->getAttributeGroupId(
	                    $productEntity,
	                    $attributeSetId,
	                    $data['attribute_group_name']
	                );

	                /**
	                 * If our attribute group name does not exist, we create it
	                 */
	                if ($attributeGroupId == $eavSetup->getDefaultAttributeGroupId($productEntity)
	                                                                        && $data['attribute_group_name'] != 'General') {
	                    $attributeGroupName = $data['attribute_group_name'];
	                    $this->createAttributeGroup($attributeGroupName, $attrSetName);
	                    $attributeGroupId = $eavSetup->getAttributeGroupId(
	                        $productEntity,
	                        $attributeSetId,
	                        $attributeGroupName
	                    );
	                }
	            }

	            /**
	             * Add attributes to the eav/attribute
	             */
	            $eavSetup->addAttribute(
	                $productEntity,
	                $attribute,
	                [
	                    'group' => $attributeGroupId ? '' : 'General', // Let empty, if we want to set an attribute group id
	                    'type' => $data['type'],
	                    'backend' => $data['backend'],
	                    'frontend' => '',
	                    'label' => $data['label'],
	                    'input' => $data['input'],
	                    'class' => '',
	                    'source' => $data['source'],
	                    'global' => ScopedAttributeInterface::SCOPE_STORE,
	                    'visible' => true,
	                    'user_defined' => true,
	                    'default' => '',
	                    'searchable' => false,
	                    'filterable' => $data['filterable'],
	                    'comparable' => false,
	                    'visible_on_front' => $data['visible_on_front'],
	                    'used_in_product_listing' => $data['used_in_product_listing'],
	                    'unique' => false
	                ]
	            );


	            /**
	             * Set attribute group Id if needed
	             */
	            if (!is_null($attributeGroupId)) {
	                /**
	                 * Set the attribute in the right attribute group in the right attribute set
	                 */
	                $eavSetup->addAttributeToGroup($productEntity, $attributeSetId, $attributeGroupId, $attribute);
	            }


	            /**
	             * Add options if needed
	             */
	            if (isset($data['options'])) {
	                $options = [
	                    'attribute_id' => $eavSetup->getAttributeId($productEntity, $attribute),
	                    'values' => $data['options']
	                ];
	                $eavSetup->addAttributeOption($options);
	            }
	        }
	    }

	    /**
	     * @param $attrSetName
	     * @throws InputException
	     * @throws NoSuchEntityException
	     */
	    private function createAttributeSet($attrSetName)
	    {
	        $defaultAttributeSetId = $this->product->getDefaultAttributeSetId();
	        $attributeSet = $this->attributeSetFactory->create();
	        $attributeSet->setAttributeSetName($attrSetName);
	        $this->attributeSetManagement->create($attributeSet, $defaultAttributeSetId);
	    }

	    /**
	     * @param $attributeGroupName
	     * @param null $attrSetName
	     * @throws InputException
	     * @throws LocalizedException
	     * @throws NoSuchEntityException
	     */
	    private function createAttributeGroup($attributeGroupName, $attrSetName = null)
	    {

	        /** @var EavSetup $eavSetup */
	        $eavSetup = $this->eavSetupFactory->create();
	        $productEntity = Product::ENTITY;

	        if ($attrSetName) {
	            $this->createAttributeSet($attrSetName);
	            $attributeSetId = $eavSetup->getAttributeSetId($productEntity, $attrSetName);
	        } else {
	            $attributeSetId = $this->product->getDefaultAttributeSetId();
	        }


	        $attributeGroup = $this->attributeGroupFactory->create();

	        $attributeGroup->setAttributeSetId($attributeSetId);
	        $attributeGroup->setAttributeGroupName($attributeGroupName);
	        $this->attributeGroupRepository->save($attributeGroup);
	    }

	    public function revert()
	    {
	        $this->moduleDataSetup->getConnection()->startSetup();
	        /** @var EavSetup $eavSetup */
	        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
	        $eavSetup->removeAttribute(Product::ENTITY, self::MULTISELECT_PRODUCT_ATTRIBUTE);

	        $this->moduleDataSetup->getConnection()->endSetup();
	    }

	    /**
	     * {@inheritdoc}
	     */
	    public function getAliases()
	    {
	        return [];
	    }
	}

Using this code Availability product attribute will be create and assign to default attribute set. If you want to assign in specific attribute set then you have to pass ‘attribute_set_name’ => ‘value’ option in self::MULTISELECT_PRODUCT_ATTRIBUTE option array.

Kindly note that if attribute set is not exist which you will pass as attribute_set_name value then it will create new attribute set and assign this Multi Select “Availability” product attribute to this new attribute set. Ultimately this tutorial will help you to create product Multi Select attribute, attributeSet and AttributeGroup programmatically.

Do let me know if you have any query once review this tutorial and create product Multi Select attribute then post your comments in comment section. We would love to help you.

Thank you for reading…We hope it helps you out. For any assistance contact us.

Follow us on Linkedin

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *