Ajax пересчет количества кнопками плюс минус

Главные вкладки

Аватар пользователя pazgaz pazgaz 27 декабря 2017 в 10:41

Здравствуйте, подскажите как подружить два модуля Commerce Extra Quantity и Commerce Cart Ajax. При нажатии кнопок по увеличению количества не работает пересчёт.
Ошибка TypeError: Drupal.commerce_extra_quantity_quantity is not a function
Подскажите как исправить или есть ли другое решение.

Комментарии

Аватар пользователя bumble bumble 27 декабря 2017 в 11:17

Скорее всего не подключаются нужные библиотеки.

Нужно альтернуть вывод и добавить на страницы использующие указанный функционал недостающие скрипты.

Аватар пользователя pazgaz pazgaz 27 декабря 2017 в 11:23

Может кому пригодится, решение по ссылке
https://www.drupal.org/project/dc_cart_ajax/issues/2323891

In fact, the solution to this problem was simple: for some reason, the file "commerce_extra_quantity.js" is not loaded on cart's page.
My solution is:
1. Create the views template of cart's page, as a rule: views-view--commerce-cart-form.tpl.php
2. In template add this code:
drupal_add_js(drupal_get_path('module', 'commerce_extra') . '/modules/quantity/commerce_extra_quantity.js');
3. Clear cache and quantity widget is ready to work Smile

Аватар пользователя bumble bumble 27 декабря 2017 в 11:30

Так себе решенице, если честно... Правильнее не в шаблоне это делать, а в препроцессоре:

<?php
/**
 * Implements hook_preprocess_views_view()
 */
function THEME_preprocess_views_view(&$vars) {
  if (
$vars['view']->name == 'view_machine_name' && $vars['view']->current_display == 'view_display_name') {
    
// И вот тут уже
    
drupal_add_js(drupal_get_path('module''commerce_extra') . '/modules/quantity/commerce_extra_quantity.js');
    
    
// Или так
    
$vars['#attached']['js'][] = drupal_get_path('module''commerce_extra') . '/modules/quantity/commerce_extra_quantity.js';
  }
}
?>
Аватар пользователя pazgaz pazgaz 27 декабря 2017 в 11:35

Это в какой файл добавить этот код?

я в views-view.tpl.php
добавил

<?php
drupal_add_js
(drupal_get_path('module''commerce_extra') . '/modules/quantity/commerce_extra_quantity.js');
?>
Аватар пользователя pazgaz pazgaz 27 декабря 2017 в 11:44

Спасибо за помощь.
Сейчас кнопки плюс минус обновляют суму только при нажатии на кнопку пересчитать.
Как к кнопкам плюс минус привязать ajax?
Извиняюсь за глупые вопросы, просто я не программист.

Аватар пользователя bumble bumble 27 декабря 2017 в 11:48

Описать весь процесс не так просто, и в рамках комментария - вряд ли получится.

Краткое описание Вы можете найти тут.

Более подробное описание можете поискать в сети, информации очень много.

Аватар пользователя pazgaz pazgaz 27 декабря 2017 в 15:08

Моё решение

sites\all\modules\commerce_extra\modules\quantity
скопировать из commerce_extra_quantity.js код и добавить его

sites\all\modules\dc_cart_ajax\misc\js
в файл dc_cart_ajax.js

и добавить ещё этот код из темы

https://www.drupal.org/project/dc_cart_ajax/issues/2323891

Sorry, it turned out that it is not enough to just download last devel realease of the module, you also must do this:

1. Add such js code to your js file:

(function($){
  Drupal.behaviors.updateQuantity = {
    attach: function (context, settings) {
      $('#views-form-commerce-cart-form-default .form-type-textfield input', context).change(function(){
        $('#edit-submit',context).mousedown();
      });
    }
  }
})(jQuery);

2. Edit commerce_extra_quantity.js file and add such code after
"$(selector).val(new_quantity);"
(line 22)
$(selector).trigger('change');

в итоге в файле dc_cart_ajax.js

(function($){
  var $wrapper = null;

  Drupal.ajax = Drupal.ajax || {};
  Drupal.ajax.prototype.commands.dc_cart_ajax = function(ajax, response, status) {
    $wrapper = $wrapper || $('#' + response['form-id']).parents('.view.view-commerce-cart-form:eq(0)').parent();

    $wrapper
      .find('div.messages').remove().end()
      .prepend(response['message']);

    if (response.output != '') {
      $wrapper.find('#dc-cart-ajax-form-wrapper').html(response.output);
      return;
    }

    var fake_link = '#dc-cart-ajax-' + response['form-id'];
    $(fake_link).trigger('click');
  };

})(jQuery);

(function ($) {

  // Increase/decrease quantity
  Drupal.commerce_extra_quantity_quantity = function(selector, way) {

    // Find out current quantity and figure out new one
    var quantity = parseInt($(selector).val());
    if (way == 1) {
      // Increase
      var new_quantity = quantity+1;
    }
    else if (way == -1) {
      // Decrease
      var new_quantity = quantity-1;
    }
    else {
      var new_quantity = quantity;
    }
    // Set new quantity
    if (new_quantity >= 1) {
      $(selector).val(new_quantity);
        //add 48 string
          $(selector).trigger('change');
    }

    // Set disabled class depending on new quantity
    if (new_quantity <= 1) {
      $(selector).prev('span').addClass('commerce-quantity-plusminus-link-disabled');
    }
    else {
      $(selector).prev('span').removeClass('commerce-quantity-plusminus-link-disabled');
    }

  }

}(jQuery));

//add  function
(function($){
  Drupal.behaviors.updateQuantity = {
    attach: function (context, settings) {
      $('#views-form-commerce-cart-form-default .form-type-textfield input', context).change(function(){
        $('#edit-submit',context).mousedown();
      });
    }
  }
})(jQuery);

Аватар пользователя bumble bumble 27 декабря 2017 в 15:46
1

pazgaz wrote:

Думаю они больше не обновляться.

Советую оставить попытки предсказания, и делать правильно, если Вы не Вангострадамус...