Skip to content

How to edit and save a Bundled Product “Bundle Items” link fields on Magento 2.4.6 PHP 8.1

I am writing a program that is checking product data and updating where required.

My problem is that I can’t save a Bundled Products Bundle Items linked product fields such as price, price_type, qty, default etc. I can create a new linked item as part of an option, but I can’t save the edited linked item.

My question is:

How do I save a linked products field such as price for a bundled product?

My code so far:

<?php
namespace VendorModuleProcess;

use MagentoBundleApiProductLinkManagementInterface;
use MagentoCatalogModelProduct;
use MagentoCatalogModelProductRepository;

class UpdateBundleProductLinks
{
  private ProductLinkManagementInterface  $productLinkManagement;
  private ProductRepository               $productRepository;

  public function __construct(
    ProductLinkManagementInterface        $productLinkManagement,
    ProductRepository                     $productRepository
  ) {
    $this->productLinkManagement          = $productLinkManagement;
    $this->productRepository              = $productRepository;
  }

 
  public function execute(Product $product, array $productData): void
  {
    $productLinks = $this->productLinkManagement->getChildren($product->getSku());

    /* Iterate over each item in the $productData array */
    foreach ($productData['bundle_items'] as $bundleItem) {
      /* $productData['bundle_items'] has array of each linked products data, price, qty, price_type etc. */
      
      /* Iterate over links to find the match */
      foreach ($productLinks as $link) {
        
        if ($link->getSku() == $bundleItem['sku']) {
          $update = false;

          /* Check if links data matches */
          if ($link->getPrice() != $bundleItem['price']) {
            $link->setPrice($bundleItem['price']);
            $update = true;
          }
          
          /* Check all links attributes here also ... */

          if ($update) {
            /* THIS IS WHERE I AM HAVING ISSUES SAVING THE LINK CHANGED DATA */

            $this->productLinkManagement->saveChild($product->getSku(), $link);

            /* I have tried saving the product after this point also without success */
            $this->productRepository->save($product);
          }
          break;
        }
      }

    }
  }
}

Image below shows the admin product page section that I am trying to edit and save.

enter image description here