2

I'm running a script that bootstraps Magento to bulk-edit some products programmatically.

At the moment, this is done like so:

error_reporting(E_ALL);
ini_set('display_errors', 1);

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(Magento\Framework\App\State::class);
$state->setAreaCode('adminhtml');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 

$productCollectionFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$products = $collection->addAttributeToSelect('paid_shipping')->load();

foreach($products as $product){
  $product->setPaidShipping(1);
  $product->save();
}

While this successfully updates the products, the customizable options all disappear. Why does this happen? How can I avoid this?

2
  • Can you confirm your magento 2 full version? Aug 22, 2019 at 21:51
  • @DavaGordon -- 2.3.2
    – brackfost
    Aug 23, 2019 at 12:40

1 Answer 1

5

Note that calling Magento\Framework\Model\AbstractModel::save() directly has been deprecated since Magento 2.1.10 (see https://github.com/magento/magento2/blob/2.1.10/lib/internal/Magento/Framework/Model/AbstractModel.php#L629).

I have tested saving product using Magento\Catalog\Model\ProductRepository::save($product) and your issue did not happen.

Try updating the way you save product using this code:

/**
 * @var \Magento\Catalog\Model\ProductRepository $productRepository
 */
$productRepository->save($product)
3
  • Thanks for the info, will give it a shot tomorrow.
    – brackfost
    Aug 26, 2019 at 3:17
  • Hi @RendyEkoPrastiyo this works, thank you! Any idea why the tax class isn't updated when I use $product->setTaxClassId(2); $productRepository->save($product); ?
    – brackfost
    Aug 28, 2019 at 20:35
  • 1
    It should also be updated, as tested in Magento vanilla, there must be observer(s) or plugin(s) from external module(s) that handle or modify the tax class upon saving the product. Feb 18, 2020 at 3:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.