как я установил наблюдателя в magento2?


Это мой код в 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;
    }

}

Как я конвертирую это в magento 2

Author: Rahul Katoch, 2017-01-27

2 answers

Вот аналогичный наблюдатель для Magento 2:

Установить индивидуальную цену товара

Сначала создайте events.xml файл в папке Webkul/Hello/etc/frontend и используйте событие 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>

Теперь создайте файл CustomPrice.php в папке Наблюдателя.

<?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);
    }

}

Источник

 1
Author: Siarhey Uchukhlebau, 2017-01-27 06:31:19

Следуйте Событиям и руководству наблюдателя , чтобы создать наблюдателя, а затем обновите эту строку в events.xml с вашим собственным событием.

<event name="checkout_cart_product_add_after">

И execute() функция класса Observer с вашим вышеприведенным кодом.Выбирайте свое мероприятие с умом, для этого вы можете ознакомиться с этим руководством.

 2
Author: Shahzaib Hayat Khan, 2017-01-27 07:23:48