Update product attribute value programmatically via observer

In order to update a Value for a Product Attribute, you need to use Class [Magento\Catalog\Model\Product\Action].

Here is example


namespace PL\Snippets\Observer;

use Magento\Catalog\Model\Product;

use Magento\Framework\Event\Observer;

class UpdateProductAttribute implements \Magento\Framework\Event\ObserverInterface

{

    const SNIPPET_YOUTUBE_LINK = 'snippet_youtube_link';

    protected $productAction;

    protected $storeManager;

    public function __construct(

        \Magento\Catalog\Model\Product\Action $productAction,

        \Magento\Store\Model\StoreManagerInterface $storeManager

    ) {

        $this->productAction = $productAction;

        $this->storeManager = $storeManager;

    }

    public function execute(Observer $observer)

    {

        $productIds = $observer->getEvent()->getData('productIds');

        if(is_array($productIds) && count($productIds) > 0) {

            $storeId = $this->storeManager->getStore()->getId();

            $this->productAction->updateAttributes($productIds, array(self::SNIPPET_YOUTUBE_LINK => null), $storeId);

        }

    }

}
Back to Top