0

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?

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

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)
  • Thanks for the info, will give it a shot tomorrow. – brackfost Aug 26 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 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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