In Magento 2, I need to set the custom price of a product pro-grammatically when admin creates an order from backend.

For example, in this page


when an admin click's 'Add Selected Product(s) to Order' (after clicking 'add products'), I want to compute prices of that selected products through some formula then assign these prices as a custom price to that products.

So what I really need is a piece of code by which Magento assigns custom price to product.

1 Answer 1


Create events.xml file at app/code/YourNamespace/YourModule/etc/frontend

<?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="custompricemodule" instance="YourNamespace\YourModule\Observer\CustomPrice" />

Create CustomPrice.php file at app/code/YourNamespace/YourModule/Observer

namespace YourNamespace\YourModule\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


Hope this will help you :)

  • I have already solved that problem by this approach. But i am accepting your answer, thanks for your help :)
    – umair ayub
    Aug 12, 2017 at 9:37

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.