1

I'm trying to update a certain attribute of all of my products programmatically. So far, I've used Magento\Catalog\Model\ResourceModel\Product\CollectionFactory and iterating through the products, setting data and using save() on each product. This was successful, but just for the primary store view (ID 1) but not globally or for any of the three other multistore views.

I've tried calling $product->setStoreId(0) on each product, but this doesn't work.

What's the best way to programmatically update an attribute for all views?

asked Jun 25, 2019 at 14:46
2

2 Answers 2

2

Try This

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$storeIds = array_keys($storeManager->getStores());
$action = objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Action');
$updateAttributes['name'] = "test";
$updateAttributes['price'] = 100;
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('sku', 'A960-CQ');
$collection->addAttributeToSelect('*');
foreach ($collection as $product) 
{
 foreach ($storeIds as $storeId) {
 $action->updateAttributes([$product->getId()], $updateAttributes, $storeId);
 }
}

given as answer here

Programmatically Update products attribute by sku for all store view

answered Jun 26, 2019 at 9:13
1
  • This successfully updated the attribute for each store, but not for "All Store Views". Commented Jun 26, 2019 at 13:50
0

Somehow (from my perspective) Product doesn't match the semantics of most other parts of Magento - maybe there is legacy support in there or something because for product both ResourceModel and Repository both have different saving logic than other models like Block in module-cms.

Try the class Magento\Catalog\Model\ResourceModel\Product\Action->updateAttributes(), you can specify storeId there

I also had the same issue with products saving attributes to the wrong storeId with other methods

answered Jan 13, 2021 at 11:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.