Magento--基于数量/分层定价动态显示价格

Magento--基于数量/分层定价动态显示价格,magento,Magento,最近有几个人问我这件事,我没有太多的答案,在其他地方也找不到太多关于这件事的信息 默认情况下,在产品页面上,显示的价格会根据自定义选项动态更新。在分层定价结构的基础上动态更新价格是否也是一大难题?基本上,如果用户访问具有分层定价的产品,并输入符合分层定价条件的数量,则价格将根据所选的分层定价和数量进行更新 我认为一些jQuery voodoo应该不那么难构建,因此价格会根据这些值重新计算,但我很好奇以前是否有人这样做过,以及他们是否意识到这样做可能会有任何陷阱 有没有很好的理由不这样做。。。或者

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

默认情况下,在产品页面上,显示的价格会根据自定义选项动态更新。在分层定价结构的基础上动态更新价格是否也是一大难题?基本上,如果用户访问具有分层定价的产品,并输入符合分层定价条件的数量,则价格将根据所选的分层定价和数量进行更新

我认为一些jQuery voodoo应该不那么难构建,因此价格会根据这些值重新计算,但我很好奇以前是否有人这样做过,以及他们是否意识到这样做可能会有任何陷阱


有没有很好的理由不这样做。。。或者换句话说,这不是作为Magento核心的一部分构建的原因吗?

是的,您可以使用javascript来实现这一点,您只需要将层数据放入模板中
中的某个变量中,类似的操作就可以了(如果您想使用jQuery):

模板: catalog\product\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>

jQuery(函数($){
//您可能希望在块中使用自定义方法,以便在此处获得更好、更安全的tierPrices数组
//例如格式化价格
var tierPrices=;
var getPrice=函数(数量){
数量=数量(数量);
var i=tierPrices.length;
而(我--)
{
如果(数量>=tierPrices[i][“价格\数量]){
退货提价[i][‘价格’];
}
}
返回null;
};
var updatePrice=函数(价格){
$('.price').html(price);
};
//如果希望在用户键入时获得实时响应,则可以在此处使用更多事件
$('#数量')。更改(函数(){
var价格=getPrice(此.value);
如果(价格!==null){
更新价格(价格);
}
});
});

我在周末花了一些时间,设法让它工作起来,但我不喜欢修改tierprices.phtml模板,以便通过类获取“price\u qty”。我把它换掉了,并按照您的建议使用了$\u 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>

var$j=jQuery;
var$p={};
var价格={};
//正在使用的dom元素
$p[“旧”]=$j(“.price box.old price.price”);
$p[“特殊”]=$j(“.price box.special price.price”);
$p[“常规”]=$j(“.price box.regular price.price”);
//如果重置数量,则保存原价以重置回原价
//查看特价
如果($p[“特殊”].html()){
var specialPrice=$p[“special”].html();
var oldPrice=$p[“old”].html();
}否则{
var originalPrice=$p[“regular”].html();
}
//让我们开始工作吧。
$j(函数(){
风险值=;
var h=层长度;
而(h--){
var-key=h;
变量行={};
//只需构建prices对象以供以后使用
行[“数量”]=parseInt(层[h][“价格数量”);
行[“价格”]=parseFloat(第[h][“价格”])。toFixed(2);
价格[关键]=行;
}
//keyup事件在这里工作得很好
$j(“#数量”)。在(“键控”,函数()上{
var数量=$j(this.val();
对于(价格中的var i){
var z=i;
//保存最低层以重置回原价
var最低=价格[0][“数量”];
//设定范围
var底部=价格[i][“数量”];
var top=价格[z++][“数量”];
//格式转换为货币——可能应该切换到magento的助手方法。
var price=“”+价格[i][“价格”];
//检查数量重置<最低后是否需要重置价格
如果(数量<最低){
如果(特殊价格){
$p[“特殊”].html(特殊价格);
$p[“old”].html(oldPrice);
}否则{
$p[“常规”].html(原价);
}
打破
}
//检查范围,相应地设定价格。
如果(数量>=底部){
如果(数量>=顶部){
如果(特殊价格){
$p[“特殊”].html(价格);
}否则{
$p[“常规”].html(价格);
}
继续;
}否则{
打破
}
}
}
})
})
我在(“keyup”,function(){})上使用$j(“#qty”)。来代替实时反馈。我可能会用whiles来清理它,而不是我设置的if结构,但它可以工作,所以至少它是一种替代方法


谢谢您的帮助。

我现在为我们的多存储系统做了完全相同的事情

如果您只有一个价格集,并且我正在格式化输出以获得更好的用户体验,那么我还添加了一个回退

请随意使用此代码:

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

jQuery(函数($){
//这是使用https://stackoverflow.com/questions/12647770/ 及https://himansuboity.wordpress.com/2014/09/30/magento-tip-how-to-get-the-store-price-format-by-javascript/
var仪表价格格式=
var tierPrices=;
var getPrice=函数(数量){
数量=数量(数量);
var i=tierPrices.length;
而(我--)
{
<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);
        }
    });
});
<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>