Magento – Magento 2: Set product dropdown attribute

magento2product

I want to set a value to a dropdown attribute.

I try to use $product->setSize("M") but it is set to null.

Do I need to create the option of dropdown attribute ?

Best Answer

I am amused , you want dynamic drop-down for Product attribute then you should create custom attribute with dynamic Source: from Setup/UpgradeData.php script:

if (version_compare($context->getVersion(), '1.0.3') < 0) {
        //code to upgrade to 1.0.3
        $eavSetup->addAttribute(\Magento\Catalog\Model\Product::ENTITY, 'product_channel', [
            'type' => 'varchar',
            'label' => 'Size',
            'input' => 'select',
            'source' => 'Custom\Product\Model\Products\Attribute\Source\sizeattribute',
            'backend' => 'Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend',
            'required' => false,
            'sort_order' => 20,
            'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_GLOBAL,
            'group' => 'General',
            'visible' => true,
            'is_used_in_grid' => true,
            'is_visible_in_grid' => true,
            'is_filterable_in_grid' => true,
        ]);
    }

I hope it will help you.