如果商城中有好几个快递运送方式...
如何能实现最优算法呢 ??先解释下所谓的最优算法...
1.只显示能配送到该地区的快递公司
2.在上面的基础上默认选中最便宜的快递公司
3.在前两条的基础上选中最快的快递公司
需求已经明确我们来看看magento中onepage中实现shipping method的地方,
一顿乱点..发现magento默认就帮我们实现了第一条需求
我现在暂且没有去抠magento是如何实现的,我们继续完成我们的第二条需求.找到
1 | design/fronted/xxx/template/checkout/onepage/shipping_method/available.phtml |
01 | <?php if (!( $_shippingRateGroups = $this ->getShippingRates())): ?> |
02 | <p><?php echo $this ->__( 'Sorry, no quotes are available for this order at this time.' ) ?></p> |
04 | <dl class = "sp-methods" > |
06 | <?php $_sole = count ( $_shippingRateGroups ) == 1; foreach ( $_shippingRateGroups as $code => $_rates ): ?> |
07 | <dt><?php echo $this ->getCarrierName( $code ) ?></dt> |
10 | <?php $_sole = $_sole && count ( $_rates ) == 1; foreach ( $_rates as $_rate ): ?> |
12 | <?php if ( $_rate ->getErrorMessage()): ?> |
13 | <ul class = "messages" ><li class = "error-msg" ><ul><li><?php echo $_rate ->getErrorMessage() ?></li></ul></li></ul> |
16 | <span class = "no-display" ><input name= "shipping_method" type= "radio" value= "<?php echo $_rate->getCode() ?>" id= "s_method_<?php echo $_rate->getCode() ?>" checked= "checked" /></span> |
18 | <input name= "shipping_method" type= "radio" value= "<?php echo $_rate->getCode() ?>" id= "s_method_<?php echo $_rate->getCode() ?>" <?php if ( $_rate ->getCode()=== $this ->getAddressShippingMethod()) echo ' checked="checked"' ?> class = "radio" /> |
20 | <label for = "s_method_<?php echo $_rate->getCode() ?>" ><?php echo $_rate ->getMethodTitle() ?> |
21 | <?php $_excl = $this ->getShippingPrice( $_rate ->getPrice(), $this ->helper( 'tax' )->displayShippingPriceIncludingTax()); ?> |
22 | <?php $_incl = $this ->getShippingPrice( $_rate ->getPrice(), true); |
23 | $min [ 's_method_' . $_rate ->getCode()]= $_rate ->getPrice(); |
26 | <?php if ( $this ->helper( 'tax' )->displayShippingBothPrices() && $_incl != $_excl ): ?> |
27 | (<?php echo $this ->__( 'Incl. Tax' ); ?> <?php echo $_incl ; ?>) |
35 | <?php endforeach ; ?><?php |
36 | foreach ( $min as $key => $val ) if ( empty ( $minval ) || $val < $minval ) $minval = $val ; |
37 | foreach ( $min as $key => $val ) if ( $val == $minval ){ $max_arr [ $key ]= $val ; $maxkey = $key ;} ; |
39 | <script type= "text/javascript" > |
40 | jQuery( '<?php echo"#".$maxkey?>' ).attr( "checked" ,true) |
大家直接复制过去就好了,我再来解释下如何实现默认选中最便宜的快递方式
首先我们定义一个空的数组..$min然后在
1 | <?php $_sole = $_sole && count ( $_rates ) == 1; foreach ( $_rates as $_rate ): ?> |
这个循环中加入
1 | $min [ 's_method_' . $_rate ->getCode()]= $_rate ->getPrice(); |
这个数组是用每个快递方式的input的id值作为数组的key,用邮费作为值
然后我们再求出数组中最小的值就OK了
1 | foreach ( $min as $key => $val ) if ( empty ( $minval ) || $val < $minval ) $minval = $val ; |
2 | foreach ( $min as $key => $val ) if ( $val == $minval ){ $max_arr [ $key ]= $val ; $maxkey = $key ;} ; |
最后还是通过jQuery的方式来默认选中我们的单选框
1 | <script type= "text/javascript" > |
2 | jQuery( '<?php echo"#".$maxkey?>' ).attr( "checked" , true ) |
测试..效果出来了,收工