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 ?
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 ?
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.
If you want to add more options to dropdown/select attribute using code then you can do it by following steps.
Step 1 : Create construct method
protected $_eavSetupFactory;
protected $_storeManager;
protected $_attributeFactory;
public function __construct(
Context $context,
\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\ResourceModel\Eav\Attribute $attributeFactory
) {
$this->_eavSetupFactory = $eavSetupFactory;
$this->_storeManager = $storeManager;
$this->_attributeFactory = $attributeFactory;
parent::__construct($context);
}
Step 2 : Create an array of options which you want to add to attribute
$attribute_arr = ['Yellow','White','Black'];
Step 3 : Load attribute by attribute code “color_test” to get attribute id
$attributeInfo=$this->_attributeFactory->getCollection()
->addFieldToFilter('attribute_code',['eq'=>"color_test"])
->getFirstItem();
$attribute_id = $attributeInfo->getAttributeId();
Step 4 : Now create attribute options array
$option=array();
$option['attribute_id'] = $attributeInfo->getAttributeId();
foreach($attribute_arr as $key=>$value){
$option['value'][$value][0] = $value;
$option['value'][$value][1] = $value;
}
Step 5 : Now add this option array to attribute
$eavSetup = $this->_eavSetupFactory->create();
$eavSetup->addAttributeOption($option);
Now execute this code, you will see the attribute with these options in Magento.
You can not set value of dropdown attribute like this as value you are trying to set M it is a label and not the value. To set size M to the product you have to get the Value for the Size M and then set that value to the product.
You can check this answer to get Option Value by Label.