How To Create Attribute In Magento 2
Recently, we receive some questions on Magento 2 custom product attributes and options – how to add them programmatically instead of the dull manual task as the default. Without a tiny doubt, enriching products with more and more diverse options becomes the daily work of online merchants. As a developer, if you know how to speed it up the right way; then be ready to get right payment!
Do not want to beat around the bush anymore, you are ready to get straight to our topic today: "How to Add Product Attributes and Options Programmatically in Magento 2". Then, let's begin.
People ALSO READ >>> How to Create/Save Attributes to Customer Grid
Step 1: Create a new module named Bss_AddProductAttribute
In the app/code/Bss/AddProductAttribute/registration.php please add the code
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, ' Bss_AddProductAttribute' , __DIR__ );
In the app/code/Bss/AddProductAttribute/composer.json create as below:
{ "name": "bss/add product attribute", "description": "Bss Add Product Attribute", "require": { "php": "~5.6.0|7.0.2|~7.0.6" }, "type": "magento2-module", "version": "1.0.0", "license": [ "OSL-3.0", "AFL-3.0" ], "extra": { "map": [ [ "*", "Bss/Add Product Attribute" ] ] } }
And, add the following code in the app/code/Bss/AddProductAttribute/etc/module.xml
<?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="Bss_AddProductAttribute" setup_version="1.0.0" /> </config>
Step 2: Create the file InstallData.php
<?php namespace Bss\AddProductAttribute\Setup; use Magento\Eav\Setup\EavSetup; 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) { $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); $eavSetup->addAttribute( \Magento\Catalog\Model\Product::ENTITY, 'custom_attribute', [ 'group' => 'General', 'attribute_set_id' => 'Bag', 'type' => 'varchar, 'backend' => '', 'frontend' => ''', 'label' => 'Custom Attribute', 'input' => 'text', 'class' => '', 'source' => ''', 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL, 'visible' => true, 'required' => false, 'user_defined' => true, 'default' => 0, 'searchable' => true, 'filterable' => true, 'comparable' => true, 'visible_on_front' => true, 'sort_order' => 101, 'option' => [ 'values' => [], ] ] ] ); } }
You must get to know the following setup on creating new attributes:
- group : Name of groups that you want the created attribute to display in such as General, Bundle, Items, Images, Content, etc. Set Group to General to assign the attribute to all groups.
- attribute_set_id : Define the attribute set to which the attribute is added, for example, Bag, Default, Gear, Bottom, etc.
- type : Select the type of custom value saved in the database.
- input : Specify the input type of the attributes such as select, text, boolean.
- label : Set the label of the attribute displayed both in the frontend and in the backend.
- source model : there provide a list of options.
- frontend : Define how to display the attribute in the frontend.
- backend : the admin can take some specific actions when loading or saving the attribute.
- global : select scope of the attribute among global, website, or store.
- require : decide whether the attribute is required or optional.
- visible_on_store : decide whether the attribute is displayed in "More Information" tab of the frontend.
- sort order : define the order of attribute.
Step 3: Run php bin/magento setup:upgrade
Please follow Admin panel ⇒ Stores ⇒ Product to find the custom attribute already added.
On Product Edit Page , you could see the attribute to be displayed.
Step 4: Create Attributes with Options
Above, we learn how to create basic Magento 2 custom product attributes without options. Hence, if you only want to create attributes with input types such as text or text area; you can skip the following steps.
In case, you want to create product attributes with options programmatically, in step 2, please modify some codes, as below:
'source' => '' into :
'source' => Bss\AddProductAttribute\Model\Attribute\Source\CustomAttribute
Step 5: Add source model
In the app/code/Bss/AddProductAttribute/Model/Attribute/Source/CustomAttribute.php please add the code:
<?php namespace Bss\AddProductAttribute\Model\Attribute\Backend; class CustomAttribute extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource { /** * Get all options * @return array */ public function getAllOptions() { if (!$this->_options) { $this->_options = [ ['label' => __('One'), 'value' => 'one'], ['label' => __('Two'), 'value' => 'two'], ['label' => __('Three'), 'value' => 'three'], ['label' => __('Four'), 'value' => 'four'], ['label' => __('Five'), 'value' => 'five'], ['label' => __('Six'), 'value' => 'six'], ]; } return $this->_options; } /** * Get a text for option value * * @param string|integer $value * @return string|bool */ public function getOptionText($value) { foreach ($this->getAllOptions() as $option) { if ($option['value'] == $value) { return $option['label']; } } return false; } }
Then, run php bin/magento setup:upgrade và setup:static-content:deploy -f .
Here we get the result:
We complete the guide through how to add product attributes and options programmatically in Magento 2. If you have any questions, feel free to leave it below. We are willing to help you out as soon as possible.
About BSS Commerce:
We are one of the leading Magento extension providers and web development services in the world. With experienced and certified Magento developers, we commit to bring high-quality products and services to optimize our business effectively. Let us know about your problems. We are willing to support you every time.
CONTACT US NOW for more information.
admin
How To Create Attribute In Magento 2
Source: https://bsscommerce.com/confluence/create-magento-2-product-attributes-custom-options-programmatically/
Posted by: fischerbessed1987.blogspot.com
0 Response to "How To Create Attribute In Magento 2"
Post a Comment