Кнопка "в корзину" + количество на странице категории PrestaShop 1.7

Доброго времени суток дорогие наши пользователи. В первую очередь хотим поздравить Вас с праздником.
Великая Пасха — праздник всех православных. В столь праздничный день хочется пожелать добра здоровья, мира, процветания всем. Пусть каждый день ваш дом наполняется уютом, теплом, счастьем, благополучием. Дарите друг другу внимание и заботу, любовь и верность. С Праздником Светлой Пасхи!
А теперь можно и приступить к уроку. Будет добавлять кнопку «в корзину» + количество на главную страницу сайта и на страницу категории.
Кнопка "в корзину" + количество на странице категории PrestaShop 1.7

Наши цели

  • Поле для ввода количества товара
  • Кнопку «в корзину» на странице категории
  • Функция которая будет обрабатывать добавление товара в корзину без перегрузки страницы
  • Симпатичная анимация при нажатии на кнопку «в корзину»
  • Модификация стилей CSS

Редактируем файл шаблона

Открываем файл:
/themes/classic/templates/catalog/_partials/miniatures/product.tpl

В нем ищем:
{block name='product_price_and_shipping'}
    {if $product.show_price}
        <div class="product-price-and-shipping">
            {if $product.has_discount}
                {hook h='displayProductPriceBlock' product=$product type="old_price"}
                <span class="regular-price">{$product.regular_price}</span>
                {if $product.discount_type === 'percentage'}
                    <span class="discount-percentage">{$product.discount_percentage}</span>
                {/if}
            {/if}
 
            {hook h='displayProductPriceBlock' product=$product type="before_price"}
 
            <span itemprop="price" class="price">{$product.price}</span>
 
            {hook h='displayProductPriceBlock' product=$product type='unit_price'}
 
            {hook h='displayProductPriceBlock' product=$product type='weight'}
        </div>
    {/if}
{/block}

Этот код отвечает за вывод цены, а кнопку нам нужно разместить немного ниже.
Перед закрывающемся
</div>

Добавим следующий код:
<div class="clearfix atc_div">
                <input name="qty" type="text" class="form-control atc_qty" value="1" onfocus="if(this.value == '1') this.value = '';" onblur="if(this.value == '') this.value = '1';"/>
                <button class="add_to_cart btn btn-primary btn-sm" onclick="mypresta_productListCart.add({literal}$(this){/literal});">
                    <i class="material-icons">add_shopping_cart</i>{l s='Add to cart' d='Shop.Theme.Actions'}
                </button>
            </div>

В итоге получаем такой код:
{block name='product_price_and_shipping'}
    {if $product.show_price}
        <div class="product-price-and-shipping">
            {if $product.has_discount}
                {hook h='displayProductPriceBlock' product=$product type="old_price"}
                <span class="regular-price">{$product.regular_price}</span>
                {if $product.discount_type === 'percentage'}
                    <span class="discount-percentage">{$product.discount_percentage}</span>
                {/if}
            {/if}
 
            {hook h='displayProductPriceBlock' product=$product type="before_price"}
 
            <span itemprop="price" class="price">{$product.price}</span>
 
            {hook h='displayProductPriceBlock' product=$product type='unit_price'}
 
            {hook h='displayProductPriceBlock' product=$product type='weight'}
            <div class="clearfix atc_div">
                <input name="qty" type="text" class="form-control atc_qty" value="1" onfocus="if(this.value == '1') this.value = '';" onblur="if(this.value == '') this.value = '1';"/>
                <button class="add_to_cart btn btn-primary btn-sm" onclick="mypresta_productListCart.add({literal}$(this){/literal});">
                    <i class="material-icons">add_shopping_cart</i>{l s='Add to cart' d='Shop.Theme.Actions'}
                </button>
            </div>
        </div>
    {/if}
{/block}

С шаблоном закончили, перейдем к стилям.

Редактируем стиль

Открываем файл:
/themes/classic/assets/css/custom.css

Он будет у Вас пусто и вставляем в него код:
.atc_qty {
    display: inline-block;
    width: 40px;
    border: 1px solid #cecece;
    background: #FFF;
    padding: 10px 0px;
    text-align: center;
    top: 2px;
    margin: auto;
    position: relative;
    margin: 0px 5px 0px 0px;
}
 
.product-description {
    min-height:130px;
}
 
#products .thumbnail-container {
    min-height:368px;
}
 
.atc_div {
    margin-top:10px;
}
 
 
.atc_spinner {
    -webkit-animation-name: spin;
    -webkit-animation-duration: 4000ms;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
    -moz-animation-name: spin;
    -moz-animation-duration: 4000ms;
    -moz-animation-iteration-count: infinite;
    -moz-animation-timing-function: linear;
    -ms-animation-name: spin;
    -ms-animation-duration: 4000ms;
    -ms-animation-iteration-count: infinite;
    -ms-animation-timing-function: linear;
     
    animation-name: spin;
    animation-duration: 4000ms;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
}
@-ms-keyframes spin {
    from { -ms-transform: rotate(0deg); }
    to { -ms-transform: rotate(360deg); }
}
@-moz-keyframes spin {
    from { -moz-transform: rotate(0deg); }
    to { -moz-transform: rotate(360deg); }
}
@-webkit-keyframes spin {
    from { -webkit-transform: rotate(0deg); }
    to { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
    from {
        transform:rotate(0deg);
    }
    to {
        transform:rotate(360deg);
    }
}
 
 
#products .thumbnail-container:hover .highlighted-informations, .featured-products .thumbnail-container:hover .highlighted-informations, .product-accessories .thumbnail-container:hover .highlighted-informations, .product-miniature .thumbnail-container:hover .highlighted-informations {
    bottom: 9.525rem;
}
 
#products .highlighted-informations, .featured-products .highlighted-informations, .product-accessories .highlighted-informations, .product-miniature .highlighted-informations {
    bottom: 5rem;
}

Осталось добавить Ajax обработку добавления товара в корзину.

Javascript для обработки Ajax

Открываем файл:
/themes/classic/assets/js/custom.js

Он также будет у Вас пустым и добавляем в него код:
var _0x7035=["\x61\x74\x63\x5F\x73\x70\x69\x6E\x6E\x65\x72","\x61\x64\x64\x43\x6C\x61\x73\x73","\x61\x75\x74\x6F\x72\x65\x6E\x65\x77","\x68\x74\x6D\x6C","\x69","\x66\x69\x6E\x64","\x64\x61\x74\x61\x2D\x69\x64\x2D\x70\x72\x6F\x64\x75\x63\x74\x2D\x61\x74\x74\x72\x69\x62\x75\x74\x65","\x61\x74\x74\x72","\x70\x61\x72\x65\x6E\x74","\x76\x61\x6C","\x2E\x61\x74\x63\x5F\x71\x74\x79","\x64\x61\x74\x61\x2D\x69\x64\x2D\x70\x72\x6F\x64\x75\x63\x74","\x50\x4F\x53\x54","\x6E\x6F\x2D\x63\x61\x63\x68\x65","\x63\x61\x72\x74","\x70\x61\x67\x65\x73","\x75\x72\x6C\x73","\x3F\x72\x61\x6E\x64\x3D","\x67\x65\x74\x54\x69\x6D\x65","\x6A\x73\x6F\x6E","\x61\x63\x74\x69\x6F\x6E\x3D\x75\x70\x64\x61\x74\x65\x26\x61\x64\x64\x3D\x31\x26\x61\x6A\x61\x78\x3D\x74\x72\x75\x65\x26\x71\x74\x79\x3D","\x31","\x26\x69\x64\x5F\x70\x72\x6F\x64\x75\x63\x74\x3D","\x26\x74\x6F\x6B\x65\x6E\x3D","\x73\x74\x61\x74\x69\x63\x5F\x74\x6F\x6B\x65\x6E","\x26\x69\x70\x61\x3D","","\x26\x69\x64\x5F\x63\x75\x73\x74\x6F\x6D\x69\x7A\x61\x74\x69\x6F\x6E\x3D","\x75\x6E\x64\x65\x66\x69\x6E\x65\x64","\x72\x65\x6D\x6F\x76\x65\x43\x6C\x61\x73\x73","\x61\x64\x64\x5F\x73\x68\x6F\x70\x70\x69\x6E\x67\x5F\x63\x61\x72\x74","\x75\x70\x64\x61\x74\x65\x43\x61\x72\x74","\x61\x64\x64\x2D\x74\x6F\x2D\x63\x61\x72\x74","\x65\x6D\x69\x74","\x61\x6A\x61\x78"];var mypresta_productListCart={add:function(_0x4bd3x2){_0x4bd3x2[_0x7035[5]](_0x7035[4])[_0x7035[3]](_0x7035[2])[_0x7035[1]](_0x7035[0]);idCombination= _0x4bd3x2[_0x7035[8]]()[_0x7035[8]]()[_0x7035[8]]()[_0x7035[8]]()[_0x7035[8]]()[_0x7035[7]](_0x7035[6]);quantity= _0x4bd3x2[_0x7035[8]]()[_0x7035[5]](_0x7035[10])[_0x7035[9]]();idProduct= _0x4bd3x2[_0x7035[8]]()[_0x7035[8]]()[_0x7035[8]]()[_0x7035[8]]()[_0x7035[8]]()[_0x7035[7]](_0x7035[11]);$[_0x7035[34]]({type:_0x7035[12],headers:{"\x63\x61\x63\x68\x65\x2D\x63\x6F\x6E\x74\x72\x6F\x6C":_0x7035[13]},url:prestashop[_0x7035[16]][_0x7035[15]][_0x7035[14]]+ _0x7035[17]+  new Date()[_0x7035[18]](),async:true,cache:false,dataType:_0x7035[19],data:_0x7035[20]+ ((quantity&& quantity!= null)?quantity:_0x7035[21])+ _0x7035[22]+ idProduct+ _0x7035[23]+ prestashop[_0x7035[24]]+ ((parseInt(idCombination)&& idCombination!= null)?_0x7035[25]+ parseInt(idCombination):_0x7035[26]+ _0x7035[27]+ (( typeof customizationId!== _0x7035[28])?customizationId:0)),success:function(_0x4bd3x3,_0x4bd3x4,_0x4bd3x5){_0x4bd3x2[_0x7035[5]](_0x7035[4])[_0x7035[3]](_0x7035[30])[_0x7035[29]](_0x7035[0]);prestashop[_0x7035[33]](_0x7035[31],{reason:{idProduct:idProduct,idProductAttribute:idCombination,linkAction:_0x7035[32]}})}})}}

На этом все. Так как мы вносили изменения в css и js то нужно выполнить очистку кэша, чтобы увидеть результат. Если боитесь вносить правки, то для начала можете посмотреть видео.

Видео


Платные услуги

Вы всегда можете обратиться к нам, чтобы ми внесли изменения. Для заказа пишите нам на почту buy@prestaservice.org или в личные сообщения.

1 комментарий

avatar
Добрый день. Сделал все как на примере, все работает. Но если ввести количество большее, чем есть в наличии кнопка также нажимается и всплывает окно с удачным добавлением товара ( в корзину товар не добавляет). Вопрос: как сделать запрет на нажатие кнопки в корзину, при превышении доступного количества товаров.
Только зарегистрированные и авторизованные пользователи могут оставлять комментарии.