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.

2 Answers 2

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 :)

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

create di.xml file in

<type name="Magento\Catalog\Model\Product">
        <plugin name="change_product" type="Letscms\PinCodeBasedProductPrice\Plugin\Product" sortOrder="1" />
    </type> 



<?php

namespace YourNamespace\YourModule\Plugin;

class Product
{


    public function afterGetPrice(\Magento\Catalog\Model\Product $subject, $result)
    {
       
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();       
        $productId = $subject->getId();     
        $Productprice = $objectManager->get(\YourNamespace\YourModule\Plugin\Price::class);  
        $price=$Productprice->GetpriceOnProduct($productId);
        if($price!=0 && !is_null($price)){            
            return $price;
        }             
        
        return $result;
    }
}

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.