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

1
2
3
4
5
6
<?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

1
2
3
4
5
<?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

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
<?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 *