Magento 2.1 Store ID – Saving Update Product in ‘All Store Views’

magento-2.1store-id

I want to update product information for "All Store Views" but it seems that when I try to update a product, Magento ignores setStoreId(0). Instead the product information will be saved to store view 1.

For reference I have 4 store views: 1, 2, 3, 4 + store view 0 (admin).

enter image description here

My code:

$collection = $this->filter->getCollection($this->collectionFactory->create());

foreach ($collection->getAllIds() AS $productId)
{
    $product = $this->productRepository->getById($productId);

    $product->setStoreId(0);
    $product->setSpecialPrice(111);

    $this->productRepository->save($product);
}

Best Answer

If you only need to change a single product attribute, the product model has an addAttributeUpdate() method that takes store_id as a parameter:

$store_id = 0; // or 1,2,3,... ?
$attribute_code = 'name';
$value = 'Storeview Specific Name';

$product->addAttributeUpdate($attribute_code, $value, $store_id);

Looking at the method in ./vendor/magento/module-catalog/Model/Product.php - it automatically does the "save the current store code and switch back after the update" thing that mcyrulik's answer does,

## ./vendor/magento/module-catalog/Model/Product.php

/**
 * Save current attribute with code $code and assign new value
 *
 * @param string $code  Attribute code
 * @param mixed  $value New attribute value
 * @param int    $store Store ID
 * @return void
 */
public function addAttributeUpdate($code, $value, $store)
{
    $oldValue = $this->getData($code);
    $oldStore = $this->getStoreId();

    $this->setData($code, $value);
    $this->setStoreId($store);
    $this->getResource()->saveAttribute($this, $code);

    $this->setData($code, $oldValue);
    $this->setStoreId($oldStore);
}