Как получить стоимость доставки на странице просмотра товара?

magento.stackexchange https://magento.stackexchange.com//questions/87416

  •  13-12-2019
  •  | 
  •  

Вопрос

Я хочу отобразить утилиту smalll следующим образом shipping calculator на странице просмотра продукта.

мы знаем, что родной magento предоставляет этот раздел на странице корзины.

Как я могу реализовать это на странице просмотра продукта?

У меня есть небольшая форма, в которой содержатся такие поля, как выпадающий список страны и почтовый индекс.enter image description here

Когда кто-то нажимает на Calculate затем предложение о доставке должно отображаться с помощью Ajax.

Я изрядно здесь задержался.Пожалуйста, помогите мне.

Я создал controller & calculateAction() метод.Какой код я могу записать в это calculateaction() функция?

Это было полезно?

Решение

Пожалуйста, добавьте приведенный ниже код в файле .phtml в форму вашего калькулятора доставки для вызова ajax.

<script type="text/javascript">
            //<![CDATA[
                var coShippingEstimateForm = new VarienForm('your_form_id',true);
            //]]>
            function getEstimateShipping(){
                if (coShippingEstimateForm.validator.validate()) {
                    new Ajax.Updater(
                        { success:'result_container_id' }, "<?php echo $this->getUrl('your_route_name/your_controller/calculate') ?>", {
                            method:'post',
                            asynchronous:true,
                            evalScripts:false,
                            onSuccess:function(transport) {
                                var shiphtml = transport.responseText;
                                if(shiphtml != "" && shiphtml != null){
                                    $('result_container_id').insert(shiphtml).show();
                                }else{
                                    alert("No shipping method available");
                                }
                                $('submit').disabled = false;
                            },
                            onLoading:function(request, json){
                                $('submit').disabled = true;
                            },
                            parameters:jQuery('form').serialize(true)
                        }
                    );
                }
            }
        </script>

Теперь вам нужно создать действие контроллера для обработки ajax-запроса.Пожалуйста, обратитесь к приведенному ниже фрагменту кода для этого.

public function calculateAction()
    {
        $country    = (string) $this->getRequest()->getParam('country_id');
        $postcode   = (string) $this->getRequest()->getParam('estimate_postcode');
        $qty = intval($this->getRequest()->getParam('qty'));
        if($qty == 0 || $qty == null){
            $qty = 1;
        }

        $currentProductId = $this->getRequest()->getPost('currunt_product');
        $quote = Mage::getModel('sales/quote')->setStoreId(Mage::app()->getStore('default')->getId());
        $_product = Mage::getModel('catalog/product')->load($currentProductId);
        $params = $this->getRequest()->getParams();
        $reqOb = new Varien_Object($params);
        $_product->getStockItem()->setUseConfigManageStock(false);
        $_product->getStockItem()->setManageStock(false);
        $quote->addProduct($_product, $reqOb);
        $quote->getShippingAddress()->setCountryId($country)->setPostcode($postcode);
        $quote->getShippingAddress()->collectTotals();
        $quote->getShippingAddress()->setCollectShippingRates(true);
        $quote->getShippingAddress()->collectShippingRates();

        $groups = $quote->getShippingAddress()->getGroupedAllShippingRates();

        $shippingRates = array();
        $shippingHtml = "";
        $shippingBlock = new Mage_Checkout_Block_Cart_Shipping();
        foreach($groups as $code=>$_rates){
            $shippingHtml .= "<dt>" . $shippingBlock->getCarrierName($code) . "</dt><dd><ul>";
            foreach ($_rates as $_rate) {
                //if($_rate->getPrice() > 0) {
                $shippingHtml .= "<li><label>";
                $shippingHtml .= $_rate->getMethodTitle();
                $shippingHtml .= " - ";
                $shippingHtml .= Mage::helper('core')->currency($_rate->getPrice(), true, false);
                $shippingHtml .= "</label></li>";
            }
            $shippingHtml .= "</ul></dd>";
        }
        $this->getResponse()->setBody($shippingHtml);
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с magento.stackexchange
scroll top