Magento - 控制器到Ajax Estimate Shipping:加载阻止并显示phtml

时间:2014-02-06 11:27:28

标签: ajax magento layout block shipping

我复制了estimatePostAction并制作了estimateAjaxPostAction(覆盖核心 - 我没有破解核心)。控制器动作也起作用(类Mage_Checkout_CartController)。

现在我想在估计ajax运输后获得/创建一个替换运输区块。我试过这个:

public function estimateAjaxPostAction()
{
    $country    = (string) $this->getRequest()->getParam('country_id');
    $postcode   = (string) $this->getRequest()->getParam('estimate_postcode');
    $city       = (string) $this->getRequest()->getParam('estimate_city');
    $regionId   = (string) $this->getRequest()->getParam('region_id');
    $region     = (string) $this->getRequest()->getParam('region');

    $this->_getQuote()->getShippingAddress()
    ->setCountryId($country)
    ->setCity($city)
    ->setPostcode($postcode)
    ->setRegionId($regionId)
    ->setRegion($region)
    ->setCollectShippingRates(true);
    $this->_getQuote()->save();
    //$this->_goBack();

    $this->loadLayout();
    $block = $this->getLayout()->createBlock('Mage_Checkout_Block_Cart_Shipping','checkout.cart.shipping.ajax',array('template' => 'checkout/cart/shipping.phtml'));
    if($block) {
        $response = array();
        $response['shipping'] = $block->toHtml();
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
    }
}

创建了块checkout.cart.shipping.ajax。但toHtml()什么都不返回。 我的JSON返回:

  

{ “发货”: “”}

为什么toHtml方法不起作用?

编辑:我的区号(checkout / cart / shipping.phtml)

<?php /** @var $this Mage_Checkout_Block_Cart_Shipping */ ?>
<div class="row contem-shipping">
    <div class="col-xs-10 shipping">
            <div class="text-ship">
            <h2><?php echo $this->__('Calcular o frete:') ?></h2>    
            <p><?php echo $this->__('Insira o CEP do endereço<br />no campo ao lado.') ?></p>
          </div>

        <div class="shipping-form">
           <form action="<?php echo $this->getUrl('checkout/cart/estimatePost') ?>" method="post" id="shipping-zip-form">
                <ul class="form-list">
                    <li class="no-display">
                        <div class="input-box">
                            <?php echo Mage::getBlockSingleton('directory/data')->getCountryHtmlSelect($this->getEstimateCountryId()) ?>
                        </div>
                    </li>
                <?php if($this->getStateActive()): ?>
                    <li>
                        <label for="region_id"<?php if ($this->isStateProvinceRequired()) echo ' class="required"' ?>><?php if ($this->isStateProvinceRequired()) echo '<em>*</em>' ?><?php echo $this->__('State/Province') ?></label>
                        <div class="input-box">
                            <select id="region_id" name="region_id" title="<?php echo $this->__('State/Province') ?>" style="display:none;"<?php echo ($this->isStateProvinceRequired() ? ' class="validate-select"' : '') ?>>
                                <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
                            </select>
                           <script type="text/javascript">
                           //<![CDATA[
                               $('region_id').setAttribute('defaultValue',  "<?php echo $this->getEstimateRegionId() ?>");
                           //]]>
                           </script>
                           <input type="text" id="region" name="region" value="<?php echo $this->escapeHtml($this->getEstimateRegion()) ?>"  title="<?php echo $this->__('State/Province') ?>" class="input-text" style="display:none;" />
                       </div>
                    </li>
                <?php endif; ?>
                <?php if($this->getCityActive()): ?>
                    <li>
                        <label for="city"<?php if ($this->isCityRequired()) echo ' class="required"' ?>><?php if ($this->isCityRequired()) echo '<em>*</em>' ?><?php echo $this->__('City') ?></label>
                        <div class="input-box">
                            <input class="input-text<?php if ($this->isCityRequired()):?> required-entry<?php endif;?>" id="city" type="text" name="estimate_city" value="<?php echo $this->escapeHtml($this->getEstimateCity()) ?>" />
                        </div>
                    </li>
                <?php endif; ?>
                    <li>                    
                        <div class="input-box">
                            <input class="input-text validate-postcode<?php if ($this->isZipCodeRequired()):?> required-entry<?php endif;?>" type="text" id="postcode" name="estimate_postcode" value="<?php echo $this->escapeHtml($this->getEstimatePostcode()) ?>" />
                        </div>
                    </li>
                </ul>
                <div class="buttons-set">
                    <button id="button-cep" style="width: 100px;" type="button" title="<?php echo $this->__('Get a Quote') ?>" onclick="calculaFreteAjax(jQuery('#postcode').val()); return false;" class="btn btn-2 btn-2a"><?php echo $this->__('Get a Quote') ?></button>
                </div>
            </form>
            <script type="text/javascript">
            //<![CDATA[
                new RegionUpdater('country', 'region', 'region_id', <?php echo $this->helper('directory')->getRegionJson() ?>);
            //]]>
            </script>

            <?php $_shippingRateGroups = $this->getEstimateRates(); ?>
            <?php if ($_shippingRateGroups): ?>
            <form id="co-shipping-method-form" action="<?php echo $this->getUrl('checkout/cart/estimateUpdatePost') ?>">
                <dl class="sp-methods">
                    <?php foreach ($_shippingRateGroups as $code => $_rates): ?>
                        <dt><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></dt>
                        <dd>
                            <ul>
                            <?php foreach ($_rates as $_rate): ?>
                                <li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
                                   <?php if ($_rate->getErrorMessage()): ?>
                                        <?php echo $this->escapeHtml($_rate->getErrorMessage()) ?>
                                   <?php else: ?>
                                        <input name="estimate_method" type="radio" value="<?php echo $this->escapeHtml($_rate->getCode()) ?>" id="s_method_<?php echo $_rate->getCode() ?>"<?php if($_rate->getCode()===$this->getAddressShippingMethod()) echo ' checked="checked"' ?> class="radio" />
                                        <label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
                                        <?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('tax')->displayShippingPriceIncludingTax()); ?>
                                        <?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
                                        <?php echo $_excl; ?>
                                        <?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
                                            (<?php echo $this->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
                                        <?php endif; ?>
                                        </label>
                                   <?php endif ?>
                                </li>
                            <?php endforeach; ?>
                            </ul>
                        </dd>
                    <?php endforeach; ?>
                </dl>

            </form>
            <?php endif; ?>
            <script type="text/javascript">
            //<![CDATA[
                var coShippingMethodForm = new VarienForm('shipping-zip-form');
                var countriesWithOptionalZip = <?php echo $this->helper('directory')->getCountriesWithOptionalZip(true) ?>;

                coShippingMethodForm.submit = function () {
                    var country = $F('country');
                    var optionalZip = false;

                    for (i=0; i < countriesWithOptionalZip.length; i++) {
                        if (countriesWithOptionalZip[i] == country) {
                            optionalZip = true;
                        }
                    }
                    if (optionalZip) {
                        $('postcode').removeClassName('required-entry');
                    }
                    else {
                        $('postcode').addClassName('required-entry');
                    }
                    return VarienForm.prototype.submit.bind(coShippingMethodForm)();
                }
            //]]>
            </script>
        </div>
    </div>
    <div class="col-xs-6">
        <?php 
            $totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount(); //total items in cart
            $totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
            $subtotal = $totals["subtotal"]->getValue(); //Subtotal value
            $grandtotal = $totals["grand_total"]->getValue(); //Grandtotal value
            if(isset($totals['discount']) && $totals['discount']->getValue()) {
            $discount = $totals['discount']->getValue(); //Discount value if applied
            } else {
            $discount = '';
            }
            $shipping = Mage::helper('checkout')->getQuote()->getShippingAddress()->getData();
            $tax =  $shipping["shipping_amount"];

            /*if( $totals["tax"]->getValue()) {
            $tax = $totals["tax"]->getValue(); //Tax value if present
            } else {
            $tax = '';
            }*/
        ?>
        <table class="totals-cart">
            <tr>
                <td class="total-tile">
                    Subtotal do pedido:
                </td>
                <td class="total-price">
                     <?php echo Mage::helper('core')->currency($subtotal, true, false); ?>
                </td>
            </tr>
            <tr>
                <td class="total-tile">
                    Frete:
                </td>
                <td class="total-price">
                     <?php echo Mage::helper('core')->currency($tax, true, false); ?>
                </td>
            </tr>
            <?php if ($discount):?>
                <tr>
                    <td class="total-tile">
                        Desconto:
                    </td>
                    <td class="total-price">
                        <?php echo Mage::helper('core')->currency($discount, true, false); ?>
                    </td>
                </tr>
            <?php endif;?>
        </table>
    </div>
</div>
<div class="row">
    <div class="col-xs-16">
        <div class="grand-total">
            <p class="text">Total:</p>
            <p class="price"><?php echo Mage::helper('core')->currency($grandtotal, true, false);?></p>
        </div>
    </div>
</div>

<script type="text/javascript">
function calculaFreteAjax(cep) {
    jQuery('.contem-shipping .shipping').html('<span class="remove-frete" style="display: block; margin: 0 auto; width: 20px;" id="login-please-wait"><img src="http://sites.xpd.com.br/cpaps/skin/frontend/xpd/default/images/opc-ajax-loader.gif" class="v-middle" alt=""/></span>');
    var param = {'country_id': 'BR','estimate_postcode': cep};
    console.log(param);
    jQuery.ajax({
        type: "GET",
        url: '<?php echo Mage::getBaseUrl().'checkout/cart/estimateAjaxPost/'; ?>', //My Custom Controller
        data: param,
        success: function(response) {
            response = jQuery.parseJSON(response);
            if(response.shipping) {
                jQuery('.contem-shipping').parent().html(response.shipping);
            }
            else {
                alert('Falha ao calcular o frete. Tente novamente.');
            }
        }
    });

    jQuery('#co-shipping-method-form dd input.radio').click(function(){
        //I will submit the shipping method selected
    });
}
</script>

2 个答案:

答案 0 :(得分:3)

丹尼斯......我有修改代码,请检查

    public function estimateAjaxPostAction()
{
    $country    = (string) $this->getRequest()->getParam('country_id');
    $postcode   = (string) $this->getRequest()->getParam('estimate_postcode');
    $city       = (string) $this->getRequest()->getParam('estimate_city');
    $regionId   = (string) $this->getRequest()->getParam('region_id');
    $region     = (string) $this->getRequest()->getParam('region');

    $this->_getQuote()->getShippingAddress()
    ->setCountryId($country)
    ->setCity($city)
    ->setPostcode($postcode)
    ->setRegionId($regionId)
    ->setRegion($region)
    ->setCollectShippingRates(true);
    $this->_getQuote()->save();
         $response = array();
        $response['shipping']=$this->eastmatesajax();
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
        }
       protected function eastmatesajax()
    {

        $layout=$this->getLayout();
        $layout->getMessagesBlock()->setMessages(Mage::getSingleton('checkout/session')->getMessages(true),Mage::getSingleton('catalog/session')->getMessages(true)); 
        $block = $this->getLayout()->createBlock('checkout/cart_shipping')->setTemplate( 'checkout/cart/shipping.phtml');
        return $block->toHtml();
    }

答案 1 :(得分:3)

$this->_getQuote()->collectTotals();

之前使用$this->_getQuote()->save();解决了更新的阻止问题