【问题标题】:Magento -- Display price dynamically based on quantity/tiered pricingMagento -- 根据数量/分层定价动态显示价格
【发布时间】:2012-09-28 21:42:20
【问题描述】:

最近有几个人问我这个问题,我没有太多答案,在其他地方也找不到太多关于这个的信息。

默认情况下,在产品页面上,显示的价格会根据自定义选项动态更新。根据分层定价结构动态更新价格是否会是一个主要的痛苦?基本上,如果用户使用分级定价的产品,并输入符合分级定价条件的数量,价格会根据所选的分级定价和数量进行更新。

我认为一些 jQuery voodoo 不应该那么难构建,因此价格会根据值重新计算,但我很好奇是否有其他人以前做过这个,以及他们是否知道这样做的任何潜在陷阱这个。

这样做是否有很好的理由...或者换句话说,是否有很好的理由不将其构建为 Magento 核心的一部分? p>

【问题讨论】:

    标签: magento


    【解决方案1】:

    是的,您可以使用 javascript 来执行此操作,您只需将层数据放入模板中 <script> 内的某个 var 中,这样就可以工作(如果您想使用 jQuery):

    模板: 目录\产品\view.phtml

    <script type="text/javascript">
        jQuery(function($){
            // probably you want a custom method in your block for getting a better and safer tierPrices array here
            // for example with formatted prices
            var tierPrices = <?php echo json_encode($_product->getTierPrice()) ?>;
            var getPrice = function(qty){
                qty = Number(qty);
                var i = tierPrices.length;
                while(i--)
                {
                    if(qty >= tierPrices[i]['price_qty']){
                        return tierPrices[i]['price'];
                    }
                }
                return null;
            };
            var updatePrice = function(price){
                $('.price').html(price);
            };
            // you can use more events here if you want a live response while the user is typing
            $('#qty').change(function(){
                var price = getPrice(this.value);
                if(price !== null){
                    updatePrice(price);
                }
            });
        });
    </script>
    

    【讨论】:

    • 我只是在 HTML 中得到var tierPrices = [];。我错过了什么吗?
    【解决方案2】:

    我找到了一个简单的解决方案,我检索了货币汇率,它工作正常。 代码如下

    <script type="text/javascript">
    jQuery(function($$){
        var inst_price_format = <?php echo Mage::helper('core')->jsonEncode( Mage::app()->getLocale()->getJsPriceFormat() ); ?>;
        var rate = <?php echo Mage::app()->getStore()->getCurrentCurrencyRate(); ?>;
        var tierPrices = <?php echo json_encode($_product->getTierPrice()) ?>;
        var getPrice = function(qty){
            qty = Number(qty);
            var i = tierPrices.length;
            while(i--)
            {
                if(qty >= tierPrices[i]['price_qty']){
                    return tierPrices[i]['price'];
                }
            }
            return null;
        };
        var updatePrice = function(price) { 
            $$('.price-box .price').html( formatCurrency( (price*rate), inst_price_format) ); 
        };
        var updateTotalPrice = function(price, qty) { 
            $$('.total-price').html( formatCurrency( ((price*rate) * qty), inst_price_format) ); 
        };
    
        $$('#qty').change( function(){
            var price = getPrice(this.value);
            var qty = this.value;
            if(price !== null) { 
                updatePrice(price); 
                updateTotalPrice(price, qty); 
            } else { 
                updatePrice(<?php echo $_product->getPrice(); ?>); 
                updateTotalPrice(<?php echo $_product->getPrice(); ?>, qty);
            }
        });
    });
    

    【讨论】:

      【解决方案3】:

      我在周末花了一些时间并设法让它工作,但我不喜欢我正在修改 tierprices.phtml 模板以便我可以通过一个类来获取“price_qty”。我按照您的建议将其换掉并使用 $_product->getTierPrice() 代替。我最终得到的代码如下:

      ----编辑---- 我重写了一些东西来支持特价。

          <script type="text/javascript">
          var $j = jQuery;
          var $p = {};
          var prices = {};
          //dom elements being used
          $p["old"] = $j(".price-box .old-price .price");
          $p["special"] = $j(".price-box .special-price .price");
          $p["regular"] = $j(".price-box .regular-price .price");
      
          //save original price to reset back if quantity is reset
          //Checking for special price
          if ($p["special"].html()) {
              var specialPrice = $p["special"].html();
              var oldPrice = $p["old"].html();
          } else {
              var originalPrice = $p["regular"].html();
          }
      
          //lets get to work.
          $j(function(){
              var tiers = <?php echo json_encode($_product->getTierPrice()) ?>;
              var h = tiers.length;
              while (h--) {
                  var key = h;
                  var line = {};
                  //just build the prices object for use later
                  line["qty"] = parseInt(tiers[h]["price_qty"]);
                  line["price"] = parseFloat(tiers[h]["price"]).toFixed(2);
                  prices[key] = line;
              }
              //keyup event works nicely here
              $j("#qty").on("keyup",function(){
                  var quantity = $j(this).val();
                  for (var i in prices) {
                      var z = i;
                      //save lowest tier for reset back to original price
                      var lowest = prices[0]["qty"];
                      //set the range
                      var bottom = prices[i]["qty"];
                      var top = prices[z++]["qty"];
                      //format to currency -- should probably switch to magento's helper method.
                      var price = "<?php echo Mage::app()->getLocale()->currency(Mage::app()->getStore()->
           getCurrentCurrencyCode())->getSymbol() ?>"+prices[i]["price"];
                      //check if the price needs to be reset after quantity is reset < lowest
                      if (quantity < lowest) {
                          if (specialPrice) {
                              $p["special"].html(specialPrice);
                              $p["old"].html(oldPrice);
                          } else {
                              $p["regular"].html(originalPrice);
                          }
                          break;
                      }
                      //check the ranges, set the price accordingly.
                      if (quantity >= bottom) {
                          if (quantity >= top) {
                              if (specialPrice) {
                                  $p["special"].html(price);
                              } else {
                                  $p["regular"].html(price);
                              }
                              continue;
                          } else {
                              break;
                          }
                      }
                  }
              })
          })
      </script>
      

      我使用 $j("#qty").on("keyup",function(){}) 代替实时反馈。我可能可以清理它以使用 whiles 而不是我设置的 if 结构,但它可以工作,所以至少它是一种替代方法。

      感谢您的帮助。

      【讨论】:

        【解决方案4】:

        我现在为我们的多商店系统做了完全相同的事情。

        如果您只有一个价格集,我还添加了一个后备选项,并且我正在格式化输出以获得更好的用户体验。

        请随意使用此代码:

        <script type="text/javascript">
            jQuery(function($){
                // This was built using https://stackoverflow.com/questions/12647770/ and https://himansuboity.wordpress.com/2014/09/30/magento-tip-how-to-get-the-store-price-format-by-javascript/
                var inst_price_format = <?php echo Mage::helper('core')->jsonEncode( Mage::app()->getLocale()->getJsPriceFormat() ); ?>
        
                var tierPrices = <?php echo json_encode($_product->getTierPrice()) ?>;
        
                var getPrice = function(qty){
                    qty = Number(qty);
                    var i = tierPrices.length;
                    while(i--)
                    {
                        if(qty >= tierPrices[i]['price_qty']) { return tierPrices[i]['price']; }
                    }
                    return null;
                };
        
                var updatePrice = function(price, qty) { $('.price').html( formatCurrency( (price * qty), inst_price_format) ); };
        
                $('#qty').change( function() {
                    var price = getPrice(this.value);
                    var qty = this.value;
                    if(price !== null) { updatePrice(price, qty); }
                    // no tier prices set, use base price
                    else { updatePrice(<?php echo $product->getPrice(); ?>, qty); }
                });
            });
        </script>
        

        【讨论】:

          【解决方案5】:

          这不适用于多商店。 货币已更改,但价格以默认货币显示。

          【讨论】:

            【解决方案6】:

            此版本考虑了产品选项和一级价格:

            <script type="text/javascript">
            jQuery(function($){
                // probably you want a custom method in your block for getting a better and safer tierPrices array here
                // for example with formatted prices
                var tierPrices = <?php
                    $_tier_json = json_encode($_product->getTierPrice());
                    $_tier_json = substr($_tier_json,0,1) . '{"price":"'.$_product->getFinalPrice().'","price_qty":"1"},' . substr($_tier_json,1);
                    echo $_tier_json;
            
                 ?>;
                var getPrice = function(qty){
                    qty = Number(qty);
                    var i = tierPrices.length;
                    while(i--)
                    {
                        if(qty >= tierPrices[i]['price_qty']){
                            return tierPrices[i]['price'];
                        }
                    }
                    return null;
                };
            
                var formatPrice = function(price) {
                    return '$' + parseFloat(price).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                };
            
                var updatePrice = function(price){
            
                    // if product has options, use optionsPrice functionality
                    if ( typeof optionsPrice != 'undefined' && typeof optionsPrice.productPrice != 'undefined' ) {
                        optionsPrice.productPrice = price;
                        optionsPrice.reload();
                    } else {
                        // or if it is a simple product, change price directly in the html
                        $(".price-box .price").html( formatPrice(price) );
                    }
                };
            
                var updatePriceEvent = function() {
                    var price = getPrice( $('#qty').val() );
                    if(price !== null){
                        updatePrice(price);
                    }
                };
            
                $('#qty').change( updatePriceEvent );
                $('div.qty-changer .qty_inc, div.qty-changer .qty_dec').click( updatePriceEvent );
            
            });
            </script>
            

            如果是可配置产品,或带有自定义选项的产品,它将根据当前选择的选项调整价格。另外,$_product->getTierPrice() 返回从第二层开始的价格,这将在数量较少时显示错误的价格

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-06-25
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多