Подтвердить что ты не робот

Изменение цены при заказе при добавлении товара в корзину: magento

Я хочу изменить цену продукта, добавив этот товар в корзину.

Как это возможно, дайте мне знать...

4b9b3361

Ответ 1

Способ сделать это - добавить наблюдателя, который ищет это событие 'sales_quote_add_item':

<events>
    <sales_quote_add_item>
        <observers>
            <priceupdate_observer>
                <type>singleton</type>
                <class>mymodule/observer</class>
                <method>updatePrice</method>
            </priceupdate_observer>
        </observers>
    </sales_quote_add_item>
</events>

У наблюдателя должен быть метод, который делает что-то вроде этого:

public function updatePrice($observer) {
    $event = $observer->getEvent();
    $quote_item = $event->getQuoteItem();
    $new_price = <insert logic>
    $quote_item->setOriginalCustomPrice($new_price);
    $quote_item->save();
}

Ответ 2

Вы можете использовать класс наблюдателя для прослушивания checkout_cart_product_add_after и использовать продукты "Super Mode" для установки пользовательских цен в отношении позиции котировки.

В вашем /app/code/local/ {namespace}/{yourmodule}/etc/config.xml:

<config>
    ...
    <frontend>
        ...
        <events>
            <checkout_cart_product_add_after>
                <observers>
                    <unique_event_name>
                        <class>{{modulename}}/observer</class>
                        <method>modifyPrice</method>
                    </unique_event_name>
                </observers>
            </checkout_cart_product_add_after>
        </events>
        ...
    </frontend>
    ...
</config>

И затем создайте класс Observer в /app/code/local/ {namespace}/{yourmodule}/Model/Observer.php

    <?php
        class <namespace>_<modulename>_Model_Observer
        {
            public function modifyPrice(Varien_Event_Observer $obs)
            {
                $customPrice = Mage::getSingleton(’core/session’)->getCustomPriceCalcuation(); // Provide you price i have set with session
                $p = $obs->getQuoteItem();
                $p->setCustomPrice($customPrice)->setOriginalCustomPrice($customPrice); 
            }

        }

Ответ 3

Суп к орехам.

Файл:/app/etc/modules/config.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
  <modules>
    <Ajax_ProductAdjust>
      <codePool>local</codePool>
      <active>true</active>
    </Ajax_ProductAdjust>
  </modules>
</config>

Файл:/app/code/local/Ajax/ProductAdjust/etc/config.xml

<?xml version="1.0"?>
      <config>
       <modules>
         <Ajax_ProductAdjust>
           <version>1.0.1</version>
         </Ajax_ProductAdjust>
       </modules>
       <global>
           <models>
             <Ajax_ProductAdjust>
               <class>Ajax_ProductAdjust_Model</class>
             </Ajax_ProductAdjust>
           </models>
           <events>
              <sales_quote_add_item>
                  <observers>
                     <ajax_productadjust_model_observer>
                        <type>singleton</type>
                        <class>Ajax_ProductAdjust_Model_Observer</class>
                        <method>updatePrice</method>
                     </ajax_productadjust_model_observer>
                 </observers>
              </sales_quote_add_item>
          </events>
      </global>
     </config>

Файл:/app/code/local/Ajax/ProductAdjust/Model/Observer.php

<?php
//Notes
class Ajax_ProductAdjust_Model_Observer
{

    public function _construct()
      {
      }

    public function getNewPrice()
      {
        //Your new functionality here
        //
        $newprice = "";

        return $newprice;
      }

     public function updatePrice( Varien_Event_Observer $observer ) 
     {
        $event = $observer->getEvent();
        $quote_item = $event->getQuoteItem();
        $new_price = $this->getNewPrice();
        $quote_item->setOriginalCustomPrice($new_price);
        $quote_item->save();
      }
 }

Приветствия,

Ответ 4

Как правильно ответил Гершон Херцег, Юрген Телен и Xman Classical. Вам нужно будет написать наблюдателя событие sales_quote_add_item. Когда какой-либо продукт добавляется в корзину, ваш наблюдатель будет запущен. Если продукт настраивается, это событие будет запущено дважды, вам нужно будет что-то подобное, чтобы получить простой продукт.

    $item = $observer->getEvent()->getQuoteItem();
    $quote = $item->getQuote();
    $product = $item->getProduct();
    if ($product->getTypeId() != "configurable") {
       //Do your thing here
    }

Ответ 5

Проблема с настраиваемым продуктом была решена. Вы просто удалите

$quote_item- > Save();

а затем для продукта не будет добавлено в корзину дважды. Но одна другая очень серьезная проблема остается в этой функции. То есть, с помощью этой функции мы можем обновить цену товара в корзине, но после добавления в корзину цена продукта не изменяется в соответствии с другой валютой. Таким образом, эта функция не может использоваться для магазина с несколькими валютами.

Если кто-нибудь найдет решение по этой проблеме, пожалуйста, поделитесь с нами...

Ответ 6

В вопросе не указано, следует ли это сделать, добавив некоторую логику в код или нет. Поэтому, поскольку у вас есть ответы для разработчиков, есть также что-то, что называется правилами цены корзины (в панели администратора перейдите в раздел "Акции" > "Правила цен в корзине покупок" ), где вы можете создавать разные правила для продажи и скидки (с купонами или без талона).

Ответ 7

    To change product price while adding product to cart, use an observer event.
    Follow the steps given below
    1. Add an observer in your module config.xml file.
    2. Create an observer file in your model
    3. add checkout_cart_product_add_after event

Файл: app/code/local/Namespace/Module/etc/config.xml

например: app/code/local/MGS/Rileytheme/etc/config.xml

     <frontend>
           <routers>
              <routeurfrontend>
                  <use>standard</use>
                  <args>
                     <module>MGS_Rileytheme</module>
                     <frontName>rileytheme</frontName>
                  </args>
               </routeurfrontend>
           </routers>
           <layout>
            <updates>
             <rileytheme>
              <file>rileytheme.xml</file>
             </rileytheme>
            </updates>
           </layout>
            <events>
              <checkout_cart_product_add_after>
                <observers>
                    <rileytheme>
                    <class>rileytheme/observer</class>
                    <method>modifyPrice</method>
                    </rileytheme>
                </observers>
               </checkout_cart_product_add_after>
            </events></b>
     <frontend>

Файл: app/code/local/MGS/Rileytheme/Model/Observer.php

class MGS_Rileytheme_Model_Observer {
    public function modifyPrice(Varien_Event_Observer $observer) {
         //$order = Mage::registry('current_order'); For getting current order 
         //$orderid = $order->getRealOrderId(); For getting orderid
          $quote_item = $observer->getQuoteItem();
          $payment = 30; //add your custom product price here and do your logic here
          $quote_item->setOriginalCustomPrice($payment);
          $quote_item->save();
          return $this;
    }
 }