2

I wrote module that is updating prices when I click save product. It's using catalog_product_save_before and its loading extra attributes like:

    $price1 = $product->getprice_extra1();
    $price2 = $product->getprice_extra2();
    $price3 = $product->getprice_extra3();

and its work perfectly, however to calculate all prices I need to manually open product and save.

I was trying to use prices catalog_product_attribute_update_before event and save using selection of products and change attributes in product list but its throwing php error:

PHP Fatal error: Uncaught Error: Call to a member function getprice_extra1() on null in ...

Same error when I try to use events: update after import and cron.

I think when I'm using this different events I need to load something else.

Or maybe some of attributes are without value and this is causing error.

UPDATE:

It looks like on update attributes all products data is not loaded I need add something with @var \Magento\Framework\Registry

1 Answer 1

2

That means your $product object is null.

Your event catalog_product_attribute_update_before is written as this:

public function updateAttributes($productIds, $attrData, $storeId)
{
    $this->_eventManager->dispatch(
        'catalog_product_attribute_update_before',
        ['attributes_data' => &$attrData, 'product_ids' => &$productIds, 'store_id' => &$storeId]
    );

You may have noticed, there is product_ids are passed but not product object.

So, you will need to loop to all the ids and then load the product object, then do your logic.

Try this:

protected $_product;

//in construction
// \Magento\Catalog\Model\ProductFactory $product

$this->_product = $product;

//now load it in your function

$productIds = $observer->getProductIds();
foreach($productIds as $id){
    $product = $this->_product->create()->load($id);
    if($product->getId()){
       //do your stuff here
    }
}

Hope, this helps.

1
  • 1
    Thank You I change your construct to $this->_product = $product; and removed from my function $product = $observer->getProduct(); and its working
    – BartZalas
    Sep 24, 2018 at 13:21

Your Answer

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

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