Adding a product attribute is one of the most popular operations in both Magento 1 and Magento 2. Attributes are a powerful way to solve many practical tasks related to a product.
This is quite a broad topic, but in this video we will discuss the simple process of adding a dropdown-type attribute to a product.
For this exercise, assume that the sample data set is installed.
- We will add an attribute called clothing_material with the possible values: Cotton, Leather, Silk, Denim, Fur, and Wool.
- We will make this attribute visible on the product view page, in bold text.
- We will assign it to the Default attribute set and add a restriction that any “bottom” clothing, like slacks, cannot be the material Fur.
We will need to take the following steps to add the new attribute:
- Create a new module.
- Add an InstallData script.
- Add a source model.
- Add a backend model.
- Add a frontend model.
- Execute the InstallData script and verify that it works.
Let’s go through each step.
Step 1: Create a new module
As Magento is modular based, we start the process by creating a new module called
Now, create two files:
Step 2 Create an InstallData script
Next, we need to create the InstallData script. Because adding an attribute technically adds records into several tables, such as
catalog_eav_attribute, this is data manipulation, not a schema change. Therefore we use InstallData instead of InstallSchema.
Create the file
Let’s take a minute to look at the code.
First of all, we need to use a special setup object, not the one that comes as a parameter. This is because Catalog is an EAV entity, so to add an attribute, we have to use eavSetup rather than standard one. This holds true for any EAV entity in Magento 2 (category, product, customer, and so on).
This is why we added eavSetupFactory in a constructor.
install() method, all we have to do is call the
addAttribute() method with 3 parameters: entity type, attribute code, and properties.
Those properties define how an attribute behaves. A full list of properties can be seen in the
eav_attribute tables. Note that there is a mapping between the fields in those tables and the properties in the
To see all the mappings, you should look at the
For now, we’ll just quickly go through most important ones:
- group: Means that we add an attribute to the attribute group “General”, which is present in all attribute sets.
- type: varchar means that the values will be stored in the catalog_eav_varchar table.
- label: A label of the attribute (that is, how it will be rendered in the backend and on the frontend).
- source/frontend/backend: Special classes associated with the attribute:
- source model: provides a list of options
- frontend: defines how it should be rendered on the frontend
- backend: allows you to perform certain actions when an attribute is loaded or saved. In our example, it will be validation.
- Global: defines the scope of its values (global, website, or store)
- visible_on_front: A flag that defines whether an attribute should be shown on the “More Information” tab on the frontend
- is_html_allowed_on_front: Defines whether an attribute value may contain HTML
Step 3: Add a source model
Next, we need to create the source model:
As the name implies, the
getAllOptions method provides a list of all available options.
Step 4: Add a backend model
Now we will create a backend model:
In our example, we implement only the
The backend model may have
afterLoad methods that allow the execution of some code at the moment an attribute is saved or loaded. The backend model is what makes attribute management a really powerful method of customization.
Note that we hardcoded
attributeSetId here for the sake of time. In other cases, it could be different. Make sure to check the
eav_attribute_set table for the right ID.
Step 5: Add a frontend model
And finally, we create a frontend model to make our value bold:Show code
As with the backend model, this is also a very simple class.
Step 6: Execute the InstallData script and verify that it works
Now we can run our code and check the results:
php bin/magento setup:upgrade
After you run this, the new attribute should have been added to the database. You can check the
catalog_eav_attribute tables to verify that the attribute and its properties are there. We see ClothingMaterial down here, with the primary key of 155, and its corresponding entry in
catalog_eav_attribute, with the primary key being 155.
Now, let’s go to the backend, open any configurable product, and we should see that clothing material dropdown. We’ll set our filters to be a configurable product with the attribute set of “bottom”.
We’ll select the first item. First, we’ll set the clothing material to Fur and attempt to save our attribute. We see that our backend model has executed successfully, so now we’ll set it to Wool and save it.
Having saved the product, we’ll now move to the frontend. It should be visible and in bold text.
Product Attribute Option Creation
A product attribute of type multiselect or select will present selectable options to the user. These options may be added manually through the admin panel or by upgrade script. The script process is slightly different depending on whether the options are being added at the moment of attribute creation or whether the options are being added at a later time to an existing attribute.
Add options to a new prouduct attribute
Basic instructions for creating a product attribute by setup or upgrade script can be found above. Before scripting the attribute creation, pick one of these two use cases for your options:
- You want a set of options which cannot be modified by a user through the admin panel and which can only be changed through a future code push.
- You want a set of options which can be modified, added or deleted through the admin panel.
For use case
1 (an ‘immutable’ set of options), follow the above instructions “Add a source model”. You will create a model that contains and dynamically returns the attribute’s selectable options to the client.
For use case
2 (a ‘mutable’ set of options), see “EAV and extension attributes”. Make sure to declare ‘Magento\Eav\Model\Entity\Attribute\Source\Table’ as the value for the ‘source’ attribute option. This ensures that Magento will store options in the appropriate database table.
\Magento\Eav\Setup\EavSetup.php::addAttributeOptions() you can add a series of options with the following array:
1 'option' => ['values' => ['Option 1', 'Option 2', 'Option 3', etc.]];
Alternatively, you may designate a specific option sorting order as follows:
1 'option' => ['values' => [8 => 'Option 1', 3 => 'Option 2', 11 => 'Option 3', etc.]]
Add options to an existing product attribute
- To add options to an ‘immutable’ set of options, modify the custom source model with the additional options you wish to provide.
- Adding options to a ‘mutable’ set of options leverages the same
EavSetupobject as you use when creating an attribute with options, but requires an additional step because
EavSetupneeds to know to which attribute you want to assign new options.
- Assign an array of new options to a variable:
1 $options = ['attribute_id' => null, 'values' => 'Option 1', 'Option 2', etc]];
- Update your array with the attribute ID from the database:
1 $options['attribute_id'] = $eavSetup->getAttributeId($eavSetup->getEntityTypeId('catalog_product'), 'your_attribute_code');
- Add your options: