Magento – Magento2 programmatically set value for specific attribute

attributesfiltermagento2

I created a drop-down attribute called "marketing" with 2 values : "sale" & "new" and I like to use a cron script that check every day :

  • if a product has a special price (or a catalog rule) => attribute "marketing" set to "sale"
  • if a product has no special price => attribute "marketing" empty
  • if a product is set to new from/to date => attribute "marketing" set to "new" or nothing

Idea is to filter in a catalog list all products that are "on sale" or "new". I know ho to check the conditions but not how to set the correct value for this attribute.

Best Answer

In your cron script, you can add the below code to fetch marketing dropdown attribute all options and values.

$this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$eavConfig = $this->_objectManager->create('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'marketing');
$options = $attribute->getSource()->getAllOptions(false);

$attributeValue = [];
foreach($options as $option) {
    $attributeValue[$option['label']] = $option['value'];    
}

then you can use directly value to set the data in product like below:

$product->setMarketing($attributeValue['new'])
$product->setMarketing($attributeValue['sale'])

Hope this help !!

Related Topic