cancel
Showing results for 
Search instead for 
Did you mean: 

how to call product collection in observer

   Did you know you can see the translated content as per your choice?

Translation is in progress. Please check again after few minutes.

how to call product collection in observer

 
public function execute(\Magento\Framework\Event\Observer $observer)
{
$product = $observer->getProduct();
$_product_sku = $product->getSku();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $_actual_product = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface')->get($_product_sku);
$attributes = $product->getAttributes();
}
 
this is not wrorking? can any one help on how to get the productObject in observer?
 
3 REPLIES 3

Re: how to call product collection in observer

Hello @Mag.Net ,

 

1. To create an observer, you must place your class file under your <module-root>/Observer directory.

2 .Your observer class should implement Magento\Framework\Event\ObserverInterface and define its execute function.

 

 

 

If my answer is useful, please Accept as Solution & give Kudos

Re: how to call product collection in observer

Hi @Mag.Net 

 

Here is solution, for Magento 1 and Magento 2. Please check.

 

Magento 1:

$products = Mage::getModel('catalog/product')->getCollection();
foreach($products as $prod) {
$product = Mage::getModel('catalog/product')->load($prod->getId());
}

Magento 2:

You can directly get product collection by using Object Manager observer file. Although it's not recommended to use Object Manager directly in Magento 2.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$collection = $productCollection->addAttributeToSelect('*')->load();
foreach ($collection as $product){
     echo 'Name  =  '.$product->getName().'<br>';
} 

Let me know if you are looking for something similar.

 

Thanks

--

If my answer is useful, please Accept as Solution & give Kudos 

Re: how to call product collection in observer

Hi @Mag.Net,

You can get product object using below way:

$product = $observer->getEvent()->getProduct();

If you want to use object manger, then you can use below code.

BTW Magento don't recommend to use object manager directly.

<?php
$productId = 8;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$currentproduct = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
echo $currentproduct->getName();
?>

I hope it will help you!