0

I'm trying to send a $price variable from a controller where I add to cart my product to checkout_cart_product_add_after event observer.

Here is my Controller:

public function execute(){
        $request = $this->getRequest()->getPostValue();
        $product_id = $request['product_id'];
        $params = array(
            'formKey' => $this->formKey,
            'product_id' => $product_id,
            'qty' => 1
        );

        $productFactory = $this->product->create();
        try{
            $product = $productFactory->load($product_id);
            $this->cart->addProduct($product,$params);
            $this->cart->save();
        }
        catch(\Exception $e){
            return $request;
        }
    }

Here is my Observer

 public function execute(\Magento\Framework\Event\Observer $observer){
        $item = $observer->getEvent()->getData('quote_item');         
        $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
        $price = 44; //I wan't to get this from Controller
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);
    }

So basically I just wan't to pass from Controller a param to Observer, the $price.

Creating a variable session seems too much trouble considering that hundreds of customers will use the ecommerce at the same time. Maybe a cookie?

Thanks and greetings!

UPDATE

I have tried this on controller:

             foreach($items as $item) {
                $this->eventManager->dispatch(
                    'checkout_cart_product_add_after',
                    ['quote_item' => $item, 'price' => 50]
                );
              }

And this on Observer

$price = $observer->getEvent()->getData('price'); 

But it's not working

1

you can use session variable to set and retrive value/variable anywhere in magento.

class yourController {
        protected $session;
    
        public function __construct(
            \Magento\Framework\Session\SessionManagerInterface $session,
            ...
        ){
            $this->session = $session;
            ...
        }
    
        public function execute(){
            $this->session->start();
            $this->session->setCustomPrice($price);
            /*below 2 line add in your observer*/
            $this->session->getCustomPrice();
            $this->session->unsCustomPrice();
         }
    }
2
  • Thanks I did this before you answered, but I will give you the poin :D May 26 '21 at 3:44
  • thanx for accept and happy to see you did it. May 26 '21 at 3:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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