Magento 2 Create Product Attribute Programmatically

Magento 2 Create Product Attribute Programmatically

Hello friends welcome to another session of Magento 2. In this session we will learn how to create product attribute in Magento 2 programmatically in Magento 2. If you go to any core module of magento 2, you will find Setup directory in particular module. Inside that there is InstallData.php file. This InstallData.php file plays role for adding data to database when you installing any module. Magento 2 Create Product Attribute Programmatically

So lets start.

Create InstallData.php file in Vendor/Module/Setup directory.

[php]

<?php
namespace Vendor\Module\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’,
[
‘type’ => ‘text’,
‘backend’ => ‘Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend’,
‘frontend’ => ”,
‘label’ => ‘Custom Attribute’,
‘input’ => ‘select’, // choose here like text, checbox, select form input element
‘class’ => ”,
‘source’ => ”,
‘global’ => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
‘visible’ => true,
‘required’ => false,
‘user_defined’ => true,
‘default’ => ”,
‘searchable’ => false,
‘filterable’ => false,
‘comparable’ => false,
‘visible_on_front’ => true,
‘used_in_product_listing’ => true,
‘unique’ => false,
‘apply_to’ => ‘simple,configurable,virtual,bundle,downloadable,grouped’,
‘group’=> ‘General’
]
);
}

}

[/php]

 

That’s all,  Run the upgrade script

php bin/magento setup:upgrade

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.