In Magento 2, once we create an attribute type, we cannot change it by configuring the admin, but it is possible to change the attribute type programmatically.
For example, let us assume the following – an attribute called “size”, the input type of that attribute as “Text” and approximately 3000 products in the store. It is also assumed that we have already entered various attribute values like ‘small’, ‘medium’ and ‘large’, for, say, 1000 products.
At a later point in time, we begin to feel that the current ‘text’ attribute type is cumbersome and time-consuming. We would, instead, prefer to have a ‘dropdown’ attribute type. This drop down will be used to choose the values ‘S’ or ‘M’ or ‘L’ instead of typing the same in the ‘text’ attribute type.
Magento 2: Changing Product Attribute Type
Admin does not allow you to change the attribute type once it is created and values have been entered. But as mentioned above we can achieve this programmatically. We have to do this without losing the existing attribute values that (in the above example) have been entered for 1000 products.
When the attribute is in “Text”, the product value of this attribute is stored in the “catalog_product_entity_varchar”, but when we change the attribute type as “Dropdown”, the product value will be stored in “catalog_product_entity_int”.
By using the below code we can change the product attribute type from text box to drop down in a short time without losing the existing values.
Place this code in the root directory of Magento 2 files and execute it.
How To Execute This Code?
Step 1 – Copy the above code and paste the same in a new file called sample.php in the Magento 2 root directory.
Step 2 – Execute the sample.php file by entering the browser URL along with the file name (example – www.yourdomainname.com/sample.php)
Step 3 – Once the above code is executed, please do not forget to reindex and also clear all the cache.
Hope the blog and code were useful. Feel free to let us know your comments and feedback.
If you’re looking for Magento 2 migration, then you are at the right destination. Let’s started with your project now.