Magento 2 – Custom Attribute for Specific Product Type

attributesconfigurable-productcustom-attributesmagento2

When creating attribute I notice that in magento2 no option for the select product type.

i.e I want my attribute will available for configurable product only.

But that attribute is visible for all simple product too.

Even I create a custom attribute when creating adding a configurable product.

When adding a simple product why that attribute is visible?

* How to create an attribute for configurable product only?

Best Answer

Yes , You can create specific attribute for specific product type programmatically.

Below i have created Boolean type of attribute for configurable product only.

You need to pass 'apply_to' parameter and its value as configurable

try below code in your InstallData.php file :

<?php

namespace Vendor\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;
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,
            'attribute_for_config',
            [
                'group' => 'Product Details',
                'type' => 'varchar',
                'backend' => '',
                'frontend' => '',
                'sort_order' => 50,
                'label' => 'Can be wrapped?',
                'input' => 'boolean',
                'class' => '',
                'source' => '',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => '',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false,
                'apply_to'=>'configurable'
            ]
        );
    }
}

Note : Same way if you needed this for all types of product you need to pass all values in same parameters like : 'apply_to'=>'simple,configurable,bundle,grouped'

Related Topic