Jens
Jens

Reputation: 981

Magento 2: How to add an product attribute to multiple attribute sets programmatically?

How to add an product attribute to multiple attribute sets programmatically?

This question has been answered for Magento 1. How does it work with Magento 2?

Upvotes: 2

Views: 1167

Answers (1)

Lucas Pedroso
Lucas Pedroso

Reputation: 21

When you add an attribute, it is added as sets that are based on the pattern (\ Magento \ Catalog \ Model \ Product ::ENTITY).

All sets that were created based on Default will have this attribute on them, because they all have entity_type/code = 4 (catalog_product)

In order not to have the trouble of later having to remove some sets that you didn't want, see below.

The only way to avoid this automatically adding all sets behavior is to set user_defined: true

$eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'attribute_name',
            [
                'type' => 'varchar',
                'label' => 'Attribute Label',
                'input' => 'text',
                'required' => false,
                'sort_order' => 5,
                'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_STORE,
                'used_in_product_listing' => true,
                'visible_on_front' => true,
                // 'attribute_set' => 'AttributeSet Name', // Don't set this
                'user_defined' => true,
                // 'group' => 'Group Name', // Don't set this
            ]
        );

This way the attribute will be created and will not be linked with any set. To link the attribute to specific sets later, see below.

        $eavSetup->addAttributeToSet(
            Product::ENTITY,
            'AttributeSet Name',
            'GroupName of AttributeSet', // Ex: General
            'attribute_name'
        );
        $eavSetup->addAttributeToSet(
            Product::ENTITY,
            'Another AttributeSet Name',
            'GroupName of Another AttributeSet', // Ex: "Existing group"
            'attribute_name'
        );

Upvotes: 1

Related Questions