Skip to content
TheCoachSMB
  • Follow Us:
Email: info@gmail.com
Call: +123-456-7890
TheCoachSMB

We Make It Happen

  • Blog
    • Magento2
    • HTML5
    • PHP Tutorial
  • Our Courses
  • Services
    • Magento 2 Installation Service
    • Magento Development Services
    • Support & Maintenance Services
    • Migration Services
    • Magento 2 Upgrade Service
    • Magento Security Patches
    • Magento Site Audit
    • Magento Speed & Performance
    • Magento Extension Development
    • Magento Consulting Services
    • SEO Services
    • Designing Services
  • Book A Call
  • Profile
  • About Us

    Lorem Ipsum is simply dummy text of the printing and typesetting industry.

    Contact Us
    Contact Info

    684 West College St. Sun City, United States America, 064781.

    (+55) 654 - 545 - 1235

    info@gmail.com

  • Get In Touch
  • Follow Us:
Email: info@gmail.com
Call: +123-456-7890
TheCoachSMB

We Make It Happen

  • Get In Touch
  • Blog
    • Magento2
    • HTML5
    • PHP Tutorial
  • Our Courses
  • Services
    • Magento 2 Installation Service
    • Magento Development Services
    • Support & Maintenance Services
    • Migration Services
    • Magento 2 Upgrade Service
    • Magento Security Patches
    • Magento Site Audit
    • Magento Speed & Performance
    • Magento Extension Development
    • Magento Consulting Services
    • SEO Services
    • Designing Services
  • Book A Call
  • Profile

Create Product Attribute programmatically in magento2

  • Home
  • Create Product Attribute programmatically in magento2
  • Sonal Motghare-Balpande Sonal Motghare-Balpande
  • May, Mon, 2022
  • Magento 2
Create Product Attribute programmatically in magento2

In this article, we will find out how to create a product attribute in Magento 2 programatically. As you know, Magento 2 manage Product by EAV model, so we cannot simply add an attribute for product by adding a column for product table.

Today  I am going to explain, how we can create text & drop down attribute for Products in Magento 2.
There are two ways to create the drop down attribute in Magento.
1 -> Manually : Go To admin panel,  Store -> Attributes -> Product .
2 -> Programmatically .

Overview of Adding Product Attribute Programmatically

Create file InstallData.php

We will start with the InstallData class which located in app/code/Thecoachsmb/ProductAttribute/Setup/InstallData.php. The content for this file:

1. Create Text custom attribute

Here are all lines code of InstallSchema.php to create product attribute programmically.

<?php
namespace Thecoachsmb\ProductAttribute\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,
			'sample_attribute',
			[
				'type' => 'text',
				'backend' => '',
				'frontend' => '',
				'label' => 'Sample Atrribute',
				'input' => 'text',
				'class' => '',
				'source' => '',
				'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
				'visible' => true,
				'required' => true,
				'user_defined' => false,
				'default' => '',
				'searchable' => false,
				'filterable' => false,
				'comparable' => false,
				'visible_on_front' => false,
				'used_in_product_listing' => true,
				'unique' => false,
				'apply_to' => ''
			]
		);
	}
}

As you can see, all the addAttribute method requires is:

  • The type id of the entity which we want to add attribute
  • The name of the attribute
  • An array of key value pairs to define the attribute such as group, input type, source, label…

All done, please run the upgrade script php bin/magento setup:upgrade to install the module and the product attribute sample_attribute will be created.

After run upgrade complete, please run php bin/magento setup:static-content:deploy and go to product from admin to check the result.

2. Create Dropdown custom attribute

Today  I am going to explain, how we can create drop down attribute for Products in Magento 2.
There are two ways to create the drop down attribute in Magento.
1 -> Manually : Go To admin panel,  Store -> Attributes -> Product .
2 -> Programmatically .

In this blog I am covering how we can create the drop down attribute programmatically,
So let’s start :
Step 1 : create InstallData.php file : Thecoachsmb\ProductAttribute\Setup\InstallData.php
Now In this file, create an Array of the attributes that you want to add as below.

$attributeGroup = 'Test Group';
        $attributes = [
            'attribute_code' => [
                'group'              => $attributeGroup,
                'input'              => 'select',
                'type'               => 'int',
                'label'              => 'Attribute Label',
                'visible'            => true,
                'required'           => false,
                'user_defined'               => true,
                'searchable'                 => false,
                'filterable'                 => false,
                'comparable'                 => false,
                'visible_on_front'           => false,
                'visible_in_advanced_search' => false,
                'is_html_allowed_on_front'   => false,
                'used_for_promo_rules'       => true,
                'source'                     => 'Thecoachsmb\ProductAttribute\Model\Config\Source\Options',
                'frontend_class'             => '',
                'global'                     =>  \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                'unique'                     => false,
                'apply_to'                   => 'simple,grouped,configurable,downloadable,virtual,bundle'
            ],...
          ];

Step 2 : Now Add and Assign Attribute to Group and Attribute Set.

// Add Attribute
// Magento\Eav\Setup\EavSetupFactory  $this->eavSetupFactory
// Magento\Framework\Setup\ModuleDataSetupInterface $setup
 $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
            foreach ($attributes as $attribute_code => $attributeOptions) {
                $eavSetup->addAttribute(
                    \Magento\Catalog\Model\Product::ENTITY,
                    $attribute_code,
                    $attributeOptions
                );
            }
//Assign 
            foreach ($attributes as $attribute_code => $attributeOptions) {

                // Class \Magento\Eav\Model\AttributeManagement

                $this->attributeManagement->assign(
                    'catalog_product',
                    $attributeSet->getId(),
                    $groupId,
                    $attribute_code,
                    $attributeSet->getCollection()->getSize() * 10
                );
            }

Note :
$attributeSet : you can load the attribute collection and loop for it or Can pass specific id instead.
$groupId : Magento\Eav\Model\Entity\Attribute\Group : you can get the group id with the help of this class.

Now , Options for drop down attribute , you can add options directly as a array.
and another approach is to use class Magento\Eav\Model\Entity\Attribute\Source\AbstractSource  as follows :

<?php

namespace Thecoachsmb\ProductAttribute\Model\Config\Source;

class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    /**
    * Get all options
    *
    * @return array
    */
    public function getAllOptions()
    {
        $this->_options = [
                ['label' => __('No'), 'value'=>'0'],
                ['label' => __('Yes'), 'value'=>'1'],
                ['label' => __('Other'), 'value'=>'2']
            ];

    return $this->_options;

    }

}

Please read each line carefully, so that you can create the attributes easily.

Related Posts:

  • Events and Observers in Magento2
  • Magento 2 Useful Commands List 2022
  • HTML5
  • How to perform different operations on table in…
  • How to create Admin Module in Magento2
  • Install Magento 2 on Ubuntu 21.04 [Complete Guide]
Comments (1)
Sonal Motghare-Balpande

Hello Readers, My passion is to guide people by sharing the knowledge I have. If I can contribute even little to the people life, its very big achievement for me. Thank You, Sonal

One thought on “Create Product Attribute programmatically in magento2”

  1. kresosusec.suec1 says:
    July 6, 2022 at 5:01 AM

    Hi Sonal, i am new in Magento 2, so i will have lots of questions. Will this code have output on frontend? ,I’m aiming for the select menu. Because on adobe tutorials they have backend,source, and frontend folders.,.i have try Mage2gen generator,. and there, there is no frontend,and backend., and i dont have displayed atribut status on frontend of the store,. but on backend everything works fine. Thanks

    Reply

Leave a Reply Cancel reply

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

Search
Recent Posts

  • Install/debug Magento2 delivery date extensionNovember 18, 2024
  • Install Magento 2.4.6 on Ubuntu 22.04 [Complete Guide]October 16, 2024
  • Install Magento 2.4.7 on Ubuntu 22.04 [Complete Guide]October 16, 2024
Categories

  • Accounting
  • Agency
  • Business
  • Consultant
  • Finance
  • Investment
  • Magento 2
  • Masonry
Calendar
May 2025
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Nov    
Tags

6 Steps to Install Magento 2 on XAMPP Windows Using Composer Agency Business composer install magento 2 download xampp for windows Graphics how to install magento how to install magento2 in localhost how to install magento2 in localhost ubuntu how to install magento2 in localhost wamp how to install magento 2 in windows 10 How To Install Magento2 in Windows on localhost using Xampp how to install magento 2 on xampp How to install Magento 2 using Composer in windows How to install Magento 2.4 in localhost XAMPP how to install magento 2.4 on xampp install magento 2 in windows10 install magento 2 using composer install magento 2 using composer windows install magento 2 windows xampp install Magento 2 with Sample Data install magento2.4 Install Magento 2.4 xampp windows 10 install magento 2.4.3 install magento2.4.3 install xampp on windows 10 Latest magento2 magento 2 composer install magento 2 install magento2 install magento 2 installation magento 2 installation steps magento 2 installation using composer magento 2 system requirement magento2.4 magento2.4.3 magento download magento for windows magento installation on xampp Magento with windows magneto2 Multisite thecoachsmb xampp download

LATEST BUSINESS IDEAS

Subscribe to Our Newsletter
& Stay Update

Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.

Thank you to visit our site and doing business with us.

We give our 100% to help you and to grow together.

About Us

Ready To Start Work With Us?

Felis consequat magnis est fames sagittis ultrices placerat sodales porttitor quisque.

Get a Quote
Contact Us
  • Courses
  • Blog
  • Magento2 Tutorial
  • Shop
Quick Links
  • Appointment
  • Price Plans
  • Investment Strategy
  • Financial Advices
  • Strategy Growth
  • Services
  • Business Planning
Links
  • Privacy Policy
  • Terms and Conditions
  • My Account
  • Contact Us
  • About Us
Latest Posts
  • Install/debug Magento2 delivery date extensionNovember 18, 2024
  • Install Magento 2.4.6 on Ubuntu 22.04 [Complete Guide]October 16, 2024
  • Install Magento 2.4.7 on Ubuntu 22.04 [Complete Guide]October 16, 2024
Open Hours

Our support available to help you.

  • Monday-Friday: 10am to 10pm
  • Email: support@thecoachsmb.com
  • Call: +91 7020500374
Opening Hours
Week Days 10:00 - 17:00
Saturday 10:00 - 15:00
Sunday Day Off
Contact us
Copyright © 2025 TheCoachSMB
🚀 Let’s Connect on LinkedIn! 🚀

Want to level up your skills and knowledge? 🚀
Follow us on LinkedIn to get:
✅ Expert insights on business growth
✅ Daily tips to sharpen your skills
✅ Exclusive updates from The Coach SMB

Let's grow together!

Follow me on LinkedIn

No thanks, I’m not interested!

WhatsApp

WhatsApp

Skype

Skype

Hide