Пункты "Цена", "Цена доставки".

Здравствуйте!

Я ещё новичок в MODX, сильно не бейте.

Хотел в магазине вывести пункты стоимости всей корзины и стоимости доставки.
Стоимость корзины пробовал вывести через:
{$total.cost} //Ничего не выводило
{$order.cost} //выводило стоимость с доставкой
Стоимость доставки через:
{$delivery.cost} //Ничего
Подумал о том что можно вывести стоимость обоих зная хотя бы ещё одно значения одного из них, но тогда встаёт вопрос как проводить вычислительные операции так как такой способ не работает (случайный пример):
[[+num:decr=`[[+tv.price-before]]`:mpy=`[[$sale]]`:div=`100`:add=`[[+tv.price-before]]`]]
Код самой корзины:
msCart
<table class="table__table">
                <tr class="header">
                    <th class="image"> </th>
                    <th class="title">{'ms2_cart_title' | lexicon}</th>
                    <th class="count">{'ms2_cart_count' | lexicon}</th>
                    <!--<th class="weight">{'ms2_cart_weight' | lexicon}</th>-->
                    <th class="price">{'ms2_cart_price' | lexicon}</th>
                    <th class="remove">{'ms2_cart_remove' | lexicon}</th>
                </tr>

                {foreach $products as $product}
                    <tr id="{$product.key}" class="table__tr">
                        <td class="image">
                            {if $product.thumb?}
                                <img src="{$product.thumb}" alt="{$product.pagetitle}" title="{$product.pagetitle}"/>
                            {else}
                                <img src="{'assets_url' | option}components/minishop2/img/web/ms2_small.png"
                                     srcset="{'assets_url' | option}components/minishop2/img/web/ms2_small@2x.png 2x"
                                     alt="{$product.pagetitle}" title="{$product.pagetitle}"/>
                            {/if}
                        </td>
                        <td class="title">
                            {if $product.id?}
                                <a href="{$product.id | url}">{$product.pagetitle}</a>
                            {else}
                                {$product.name}
                            {/if}
                            {if $product.options?}
                                <div class="small">
                                    {$product.options | join : '; '}
                                </div>
                            {/if}
                        </td>
                        
                        <td class="count">
                            <form method="post" class="ms2_form form-inline" role="form">
                                <input type="hidden" name="key" value="{$product.key}"/>
                                <div class="form-group">
                                    
                                     <button class="form-group__minus">-</button>
                                    <input class="form-group__number" type="number" data-min="1" data-max="9999" name="count" value="{$product.count}"/>
                                    <button class="form-group__plus">+</button>
                                </div>
                                    <button class="btn btn-default" type="submit" name="ms2_action" value="cart/change"></button>
                                
                            </form>
                        </td>
                        <!--<td class="weight">
                            <span>{$product.weight}</span> {'ms2_frontend_weight_unit' | lexicon}
                        </td>-->
                        <td class="price">
                            <span>{$product.price}</span> {'ms2_frontend_currency' | lexicon}
                            {if $product.old_price?}
                            <span class="old_price">{$product.old_price}</span> {'ms2_frontend_currency' | lexicon}
                                {/if}
                        </td>
                        <td class="remove">
                            <form method="post" class="ms2_form">
                                <input type="hidden" name="key" value="{$product.key}">
                                <button class="btn btn-default" type="submit" name="ms2_action" value="cart/remove"><i class="fa fa-times" aria-hidden="true"></i></button>
                            </form>
                        </td>
                    </tr>
                {/foreach}

                <tr class="">
                    <th class="total" colspan="2">{'ms2_cart_total' | lexicon}:</th>
                    <th class="total_count">
                        <span class="ms2_total_count">{$total.count}</span>
                        {'ms2_frontend_count_unit' | lexicon}
                    </th>
                    <!--<th class="total_weight">
                        <span class="ms2_total_weight">{$total.weight}</span>
                        {'ms2_frontend_weight_unit' | lexicon}
                    </th>-->
                    <th class="total_cost">
                        <span class="ms2_total_cost">{$total.cost}</span>
                        {'ms2_frontend_currency' | lexicon}
                    </th>
                    <th> </th>
                </tr>
            </table>
msOrder
//Вывод доставки
{foreach $deliveries as $delivery index=$index}
                        {var $checked = !$order.delivery && $index == 0 || $delivery.id == $order.delivery}
                        <label>
                           
                                <input id="{$delivery.id}" type="radio" name="delivery" class="radio" value="{$delivery.id}" id="delivery_{$delivery.id}"
                                       data-payments="{$delivery.payments | json_encode}"
                                        {$checked ? 'checked' : ''}>
                                         <label for="{$delivery.id}" class="label">{if $delivery.logo?}
                                    <img src="{$delivery.logo}" alt="{$delivery.name}" title="{$delivery.name}"/>
                                {else}
                                    {$delivery.name}
                                {/if}
                                {*if $delivery.description?}
                                    <p class="small">
                                        {$delivery.description}
                                    </p>
                                {/if*}</span>
                                
                            
                        </label>
                    {/foreach}
//Вывод цены с доставкой
<div class="col-md-12"><strong>{'ms2_frontend_order_cost' | lexicon}:
                <span id="ms2_order_cost">{$order.cost ?: 0}</span>
                руб.</strong>
</div>
Дайте пару советов или ссылок как это решить. Буду очень благодарен.
Oleg
22 марта 2019, 20:02
modx.pro
1 142
-2

Комментарии: 13

    Игорь Гришанов
    23 марта 2019, 16:33
    3
    +2
    Павел абсолютно прав) Только что делал таким образом

    Порядок действий такой
    1) Находишь файл core/components/minishop2/model/minishop2/msorderhandler.class.php
    2) находишь там функцию getCost и заменяешь ее тем что в приведенной Павлом ссылке
    3) добавляешь скрипт из той же ссылки на страницу Оформления заказа в самом низу
    4) выводишь ссылку в нужном месте
    <span id="deliveryprice">Стоимость доставки: <span id="ms2_delivery_cost"></span> руб.</span>

    это будет цена доставки
    5) если еще надо цену заказа БЕЗ доставки то добавляешь в скрипт в функцию miniShop2.Callbacks.Order.getcost.response.success
    такие строки например
    var cartcost = response.data['cost'] - rdc;
        $('#ms2_cost').text(cartcost);
    тогда ссылка на цену без доставки будет так
    <span  id="ms2_cost"></span>
      Баха Волков
      24 марта 2019, 14:15
      0
      Пункты 1 и 2 неправильные, нужно переопределить расширив класс, а не заменять
        Oleg
        24 марта 2019, 18:31
        0
        Т.е. нужно создать новый класс и переопределить его? Расскажите подробнее. Создавать нужно с таким же именем «msorderhandler.class.php»? Это отключит предыдущий подобный класс? У меня (возможно как и у всех) есть куча необходимых функций. Извините мою любознательность и тупость.
          Игорь Гришанов
          24 марта 2019, 20:11
          0
          здесь товарищ пишет
          Метод подключения кастомного класса из инструкции не работает.
          проверять его слова не стал. меня и так устраивает
          https://modx.pro/help/8210">
          Oleg
          24 марта 2019, 18:54
          0
          Удалил часть кода
          interface msOrderInterface {
              //Тут было ещё несколько функций
              public function getCost();
          }
          И в конец добавил то что было в ссылке, ничего не произошло.
          Возможно скрипт вставляю неправильно, через
          <script type="text/javascript">
          ведь?
            Игорь Гришанов
            24 марта 2019, 21:01
            0
            скрипт надо вставлять после тэга
            </body>
            чтобы он оказался после скрипта минишопа
              Oleg
              24 марта 2019, 21:54
              0
              Тут часто пишут о переопределении классов, а как это делается? (нет инфу в гугле не нашёл)
                Игорь Гришанов
                24 марта 2019, 21:56
                0
                я делал так как написал выше. о переопределении спроси тех кто об этом упоминает
                  Oleg
                  24 марта 2019, 22:26
                  0
                  Вставил код после минишопа, в футер. Всё равно не работает.
                  Вот часть кода из "msorderhandler.class.php", где прописан getCost:
                  interface msOrderInterface
                  {
                  
                      /**
                       * Initializes order to context
                       * Here you can load custom javascript or styles
                       *
                       * @param string $ctx Context for initialization
                       *
                       * @return boolean
                       */
                      public function initialize($ctx = 'web');
                  
                  
                      /**
                       * Add one field to order
                       *
                       * @param string $key Name of the field
                       * @param string $value .Value of the field
                       *
                       * @return boolean
                       */
                      public function add($key, $value);
                  
                  
                      /**
                       * Validates field before it set
                       *
                       * @param string $key The key of the field
                       * @param string $value .Value of the field
                       *
                       * @return boolean|mixed
                       */
                      public function validate($key, $value);
                  
                  
                      /**
                       * Removes field from order
                       *
                       * @param string $key The key of the field
                       *
                       * @return boolean
                       */
                      public function remove($key);
                  
                  
                      /**
                       * Returns the whole order
                       *
                       * @return array $order
                       */
                      public function get();
                  
                  
                      /**
                       * Returns the one field of order
                       *
                       * @param array $order Whole order at one time
                       *
                       * @return array $order
                       */
                      public function set(array $order);
                  
                  
                      /**
                       * Submit the order. It will create record in database and redirect user to payment, if set.
                       *
                       * @return array $status Array with order status
                       */
                      public function submit();
                  
                  
                      /**
                       * Cleans the order
                       *
                       * @return boolean
                       */
                      public function clean();
                  
                  
                      /**
                       * Returns the cost of delivery depending on its settings and the goods in a cart
                       *
                       * @return array $response
                       */
                      public function getCost();
                      
                   
                  }
                  Может в нём чтото не так.
            Oleg
            25 марта 2019, 12:51
            0
            Значит переопределением называется «пересоздание» класса?
              Баха Волков
              25 марта 2019, 13:43
              1
              +1
              Пересоздание/создание собственного класса который наследует оригинальный класс и в котором переопределяется один или несколько методов оригинального класса
            Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
            13