1

I have a problem with ProductProcessUrlRewriteSavingObserver when I try to save product attribute data by the Product resource saveAttribute method. Magento 2.4.3 changes one validation method in this observer. Now method wants to check differences between product origin data 'website_ids' and actual websites_ids. It works when I save a product, but it causes a warning when I use saveAttribute method.

When I try to save data for only one attribute it returns a warning: Warning: array_diff(): Expected parameter 1 to be an array, null given in /var/www/html/vendor/magento/module-catalog-url-rewrite/Observer/ProductProcessUrlRewriteSavingObserver.php on line 130.

Code to save attribute data:

    $product->setData('custom_attribute', $customValue);
    $this->productResource->saveAttribute($product, 'custom_attribute');

The new validation method looks like this:

/**
 * Is website assignment updated
 *
 * @param Product $product
 * @return bool
 */
private function isWebsiteChanged(Product $product)
{
    $oldWebsiteIds = $product->getOrigData('website_ids');
    $newWebsiteIds = $product->getWebsiteIds();

    return array_diff($oldWebsiteIds, $newWebsiteIds) || array_diff($newWebsiteIds, $oldWebsiteIds);
}

When I was debugging this code I found out $product->getOrigData('website_ids') returns null. I have no idea how I can fix this.

Thank you for any idea.

2 Answers 2

0

May be try to get the product with the repositories first ? Sometimes depending on how and where the product came from the behavior can be odd.

Something like :

private function isWebsiteChanged(Product $product){
    $prod = $this->productRepository->get($product->getId())       


    $oldWebsiteIds = $prod->getOrigData('website_ids');
    $newWebsiteIds = $prod->getWebsiteIds();

    return array_diff($oldWebsiteIds, $newWebsiteIds) 
                          || array_diff($newWebsiteIds, $oldWebsiteIds);
}
1
  • I have already tried such a solution, but it does not work. $oldWebsiteIds is still null. Also this code should be like this $prod = $this->productRepository->getById($product->getId()); Oct 5, 2021 at 6:44
0

I found out a solution.

 /**
 * Is website assignment updated
 *
 * @param Product $product
 * @return bool
 */
private function isWebsiteChanged(Product $product)
{
    $oldWebsiteIds = $product->getOrigData('extension_attributes')->getWebsiteIds();
    $newWebsiteIds = $product->getWebsiteIds();

    return array_diff($oldWebsiteIds, $newWebsiteIds) || array_diff($newWebsiteIds, $oldWebsiteIds);
}

Now $oldWebsiteIds is not null.

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.