Добавить товар в корзину через Javascript (jQuery) в Prestashop 1.7.5.0 - PullRequest
0 голосов
/ 30 декабря 2018

Я создаю тему для prestashop 1.7 и пытаюсь создать вызов ajax из javascript (jQuery), который добавляет продукт с определенным именем в корзину покупок.(Я прочитал документацию, посмотрел на модули, гуглил несколько часов, но не повезло).

Так что в основном:

<button id="buyProduct" data-productname="myProduct">Buy Product</button>

$('#buyProduct).click(function(){
  var productname = $(this).data('productname');
  // Do Prestashop Magic
});

1 Ответ

0 голосов
/ 01 января 2019

Добавление товаров по названию - плохая идея.Вам нужны id_product и id_product_attribute (0 - если у продукта нет вариантов).

Проще всего сделать форму, подобную той, что на странице товара.http://fo.demo.prestashop.com/pl/men/1-1-hummingbird-printed-t-shirt.html#/1-rozmiar-s/8-kolor-bialy

Поиск исходного кода для <form action="http://fo.demo.prestashop.com/pl/koszyk" method="post" id="add-to-cart-or-refresh">

Это jas-код preastahop (в core.js) для добавления в корзину:

      $body.on('click', '[data-button-action="add-to-cart"]', function (event) {
    event.preventDefault();
    if ((0, _jquery2['default'])('#quantity_wanted').val() > (0, _jquery2['default'])('[data-stock]').data('stock') && (0, _jquery2['default'])('[data-allow-oosp]').data('allow-oosp').length === 0) {
      (0, _jquery2['default'])('[data-button-action="add-to-cart"]').attr('disabled', 'disabled');
    } else {
      var _ret = (function () {
        var $form = (0, _jquery2['default'])(event.target).closest('form');
        var query = $form.serialize() + '&add=1&action=update';
        var actionURL = $form.attr('action');

        var isQuantityInputValid = function isQuantityInputValid($input) {
          var validInput = true;

          $input.each(function (index, input) {
            var $input = (0, _jquery2['default'])(input);
            var minimalValue = parseInt($input.attr('min'), 10);
            if (minimalValue && $input.val() < minimalValue) {
              onInvalidQuantity($input);
              validInput = false;
            }
          });

          return validInput;
        };

        var onInvalidQuantity = function onInvalidQuantity($input) {
          $input.parents('.product-add-to-cart').first().find('.product-minimal-quantity').addClass('error');
          $input.parent().find('label').addClass('error');
        };

        var $quantityInput = $form.find('input[min]');
        if (!isQuantityInputValid($quantityInput)) {
          onInvalidQuantity($quantityInput);

          return {
            v: undefined
          };
        }

        _jquery2['default'].post(actionURL, query, null, 'json').then(function (resp) {
          _prestashop2['default'].emit('updateCart', {
            reason: {
              idProduct: resp.id_product,
              idProductAttribute: resp.id_product_attribute,
              linkAction: 'add-to-cart',
              cart: resp.cart
            },
            resp: resp
          });
        }).fail(function (resp) {
          _prestashop2['default'].emit('handleError', { eventType: 'addProductToCart', resp: resp });
        });
      })();

      if (typeof _ret === 'object') return _ret.v;
    }
  });
...