Выделять добавленный товар в minishop2
Самое главное в файле "core/components/minishop2/model/minishop2/mscarthandler.class.php" в функции public function status($data = array()) добавить идентификатор товара + количество в запрос выдаваемый miniShop2.Callbacks.Cart.add.response.success.
Для этого изменяем код на следующий:
public function status($data = array())
{
$id = $this->cart[$data['key']]['id'];
$count_tovar = $this->cart[$data['key']]['count'];
$status = array(
'total_count' => 0,
'total_cost' => 0,
'total_weight' => 0,
'id' => $id,
'count_tovar' => $count_tovar,
'total_discount' => 0,
'total_positions' => count($this->cart),
);
foreach ($this->cart as $item) {
if (empty($item['ctx']) || $item['ctx'] == $this->ctx) {
$status['total_count'] += $item['count'];
$status['total_cost'] += $item['price'] * $item['count'];
$status['total_weight'] += $item['weight'] * $item['count'];
$status['total_discount'] += $item['discount_price'] * $item['count'];
}
}
$status = array_merge($data, $status);
$response = $this->ms2->invokeEvent('msOnGetStatusCart', array(
'status' => $status,
'cart' => $this,
));
if ($response['success']) {
$status = $response['data']['status'];
}
return $status;
}
Пишем в отдельный файл скриптов код который будет записывать в куки идентификатор товара и добавленное количество. Далее считываем из cookie и если есть запись с данным ID товара то добавляем этой карточке класс
$(document).ready(function() {
console.log("cookie start");
console.log( document.cookie );
function getCookie(name) {
var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
miniShop2.Callbacks.Cart.add.response.success = function( response ) {
console.log("Переменные");
console.log("cookie");
//Пишем запись в куки
document.cookie = response['data']['id'] + '=' + response['data']['count_tovar'];
console.log( document.cookie );
var idt = "per-" +response['data']['id']
var idtcount = "count-" + response['data']['id']
document.getElementById(idt).classList.add("addcart");
document.getElementById(idtcount).value = response['data']['count_tovar'];
};
//удаление всех куков после полной очистки корзины
miniShop2.Callbacks.Cart.clean.response.success = function( response ) {
var cookies = document.cookie.split(/;/);
for (var i = 0, len = cookies.length; i < len; i++) {
var cookie = cookies[i].split(/=/);
document.cookie = cookie[0] + "=;max-age=-1";
}
};
});
Тут код обработчик непосредственно на саму страницу товара Чанк вывода товара. Классы подставляем свои
function getCookie(name) {
var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
$(document).ready(function() {
var selected = document.cookie.match(/22=(.+?)/);
var count = getCookie('22'); // получили count у id = 15
if (selected) {
$('#msProduct').addClass('addcart2');
$('#product_price').val(count);
count = getCookie('22');
price = * count;
$('#card-product__price').text(price);
}else{
$('#msProduct').removeClass('addcart2');
$('#product_price').val(1);
}
$( "#product_price" ).change(function(){ // задаем функцию при срабатывании события change на элементе с которым взаимодействует пользователь
count = $('#product_price').val();
price = * count;
$('#card-product__price').text(price);
});
});
Тут код обработчик карточек товара в категории. Чанк вывода карточки товара. Классы подставляем свои
$(document).ready(function() {
var selected = document.cookie.match(/=(.+?)/);
var count = getCookie(''); // получили count у id = 15
if (selected) {
$('#per-').addClass('addcart');
$('#count-').val(count);
count = getCookie('');
price = {$price | replace : " " : ""} * count;
$('#card-product__price-').text(price);
}else{
$('#per-').removeClass('addcart');
$('#count-').val(1);
}
$( "#count-" ).change(function(){ // задаем функцию при срабатывании события change на элементе с которым взаимодействует пользователь
count = $('#count-').val();
price = {$price | replace : " " : ""} * count;
$('#card-product__price-').text(price);
});
});
Комментарии ()