1

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

'www.site.com/admin/sales/order_create/index/key/a0f4c...

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.

3

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" />
    </event>
</config>

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

<?php
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
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);
    }

}

Hope this will help you :)

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

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.