Magento 2 – Adding Product Attribute

attributesmagento2product-attribute

Since I am just adding a product attribute which is stored in EAV tables, this is how InstallData.php looks like

<?php

namespace Namespace\Modulename\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;


/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'customer_product_points',
            [
                'type' => 'decimal',
                'backend' => '',
                'frontend' => '',
                'label' => 'Customer Product Points',
                'input' => '',
                'class' => '',
                'source' => '',
                'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => 0,
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => false,
                'unique' => false,
                'apply_to' => ''
            ]
        );
    }
}

Executing php magento setup:upgrade I was able to see new attribute in the system.

But the attribute is not visible while adding a new product. Have I missed anything here ? I need to add points to products and same will be reflected on frontend.

Best Answer

You need add attribute in default attribute set. You can use \Magento\Eav\Setup\EavSetup::addAttributeToGroup for this

       $categorySetup->addAttributeToGroup(
            $entityTypeId,
            $attributeSetId,
            $groups[$attributeProp['group']]['id'],
            $attributeCode,
            $attributeProp['sort']
        );