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?
-
Please try with this - cadence-labs.com/2018/03/…Anas Mansuri– Anas Mansuri2019年06月26日 05:13:13 +00:00Commented Jun 26, 2019 at 5:13
-
This seems to be a Magento bug: github.com/magento/magento2/issues/17284 Or did anyone magaged to solve it?j.m.– j.m.2019年10月16日 14:10:08 +00:00Commented Oct 16, 2019 at 14:10
2 Answers 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
-
This successfully updated the attribute for each store, but not for "All Store Views".brackfost– brackfost2019年06月26日 13:50:00 +00:00Commented Jun 26, 2019 at 13:50
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
Explore related questions
See similar questions with these tags.