2

this is my code in magento 1

class Namespac_Modulename_Model_Observer
{ 
    public function modifyPrice(Varien_Event_Observer $obs) 
    {

        // Get the quote item
        $item = $obs->getQuoteItem();
        // Ensure we have the parent item, if it has one
        $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
        // Load the custom price
        $price = $this->_getPriceByItem($item);
        // Set the custom price
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        // Enable super mode on the product.
        $item->getProduct()->setIsSuperMode(true);
    }

    protected function _getPriceByItem(Mage_Sales_Model_Quote_Item $item)
    {


        $price;
        $price = $_POST['finalPrice'];
        return $price;
    }

}

how i convert this in the magento 2

1

Here is similar observer for the Magento 2:

Set Custom Price of Product

First create events.xml file in folder Webkul/Hello/etc/frontend and use event checkout_cart_product_add_after.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
        <observer name="customprice" instance="Webkul\Hello\Observer\CustomPrice" />
    </event>
</config>

Now create CustomPrice.php file in Observer folder.

<?php
/**
 * Webkul Hello CustomPrice Observer
 *
 * @category    Webkul
 * @package     Webkul_Hello
 * @author      Webkul Software Private Limited
 *
 */
namespace Webkul\Hello\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class CustomPrice implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer) {
        $item = $observer->getEvent()->getData('quote_item');         
        $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
        $price = 100; //set your price here
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);
    }

}

Source

  • great thanks for reply @Siarhey Uchukhlebau can you tell me please one thing also protected function protected function _getPriceByItem(Mage_Sales_Model_Quote_Item $item) { $price; $price = $_POST['finalPrice']; return $price; } function how i use this in the magento 2 in this observer also – Rahul Katoch Jan 27 '17 at 7:12
2

Follow Events And Observer guide to make observer and then update this line in events.xml with your own event.

<event name="checkout_cart_product_add_after">

and execute() function of Observer class with your above code.Choose your event wisely you can look into this guide for that.

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.