0

Background: Some products option detail (e.g. text field data) is not correctly held through the process... User enters data on the product page and it is missing in the basket page. A simple fix is to save the product in the admin (no changes)... so am building a script to save all products with product options.

Problem: The script isn't fixing the problem, so it is not performing the same actions as the admin save with the GUI. Why?

Here is my script:

require __DIR__ . '/app/bootstrap.php';

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$instance = \Magento\Framework\App\ObjectManager::getInstance();

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

$arrProductIDs = [...];

foreach ($arrProductIDs as $iProductID) {
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($iProductID);
    $product->save();
    echo $iProductID.' saved - ';
}

I have also tried changing some data a little, but no better:

$desc_orig = $product->getDescription();
$product->setDescription($desc_orig.' ');

Can anyone please help me understand fix this so that I can replicate going into the admin and saving all of these products?

1 Answer 1

2

You should make use of service contracts, as the load() and save() methods are officially deprecated.

Use \Magento\Catalog\Model\ProductRepository or even better \Magento\Catalog\Api\ProductRepositoryInterface to load and save products.

$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
foreach ($arrProductIDs as $iProductID) {
    $product = $productRepository->getById($iProductID);
    $productRepository->save($product);
    echo $iProductID.'-';
}

If you're still having problems, it would maybe help to get more informations. Also, you might want to look into the product's saving process. IIRC, the admin always saves new custom options in some Magento versions, while this isn't necessarily done when simply running a script.

1
  • \Magento\Catalog\Model\ProductRepository didn't work, but I've updated to use \Magento\Catalog\Api\ProductRepositoryInterface which does work, thank you!
    – Barry
    Dec 13, 2019 at 9:52

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.