Как можно на странице product.tpl и category.tpl проверить есть ли товар в Избранном/ Закладках? Хочу применить css стиль. Движок OpenCart 2.1.0.2 (rs.1)
делать нужно сначало в контроллере. Для примера посмотрите на \catalog\controller\account\wishlist.php Сами товары попадают в сессию пользователя при добавление в закладки Вот тут Код: $this->session->data['wishlist']; В ней находится массив с id товарами. В контроллерах товара вы можете перебирать данный массив и сравнивать с текущем id товара.
Подскажите. Вставил в catalog/model/account/wishlist.php Код: public function getAllWishlist() { if ($data = $this->getWishlist()) { $out = array(); foreach ($data as $key => $value) { $out[] = $value['product_id']; } return $out; } else if (isset($this->session->data['wishlist'])) { return $this->session->data['wishlist']; } else { return false; } } Добавил код в catalog/controller/product/category.php Код: $this->load->model('account/wishlist'); $data['AllWishlist'] = $this->model_account_wishlist->getAllWishlist(); И в файл catalog/view/theme/default/template/product/category.tpl Код: <?php if(in_array($product['product_id'], $AllWishlist)) { ?> Этот товар в закладках <?php } ?> Браузер выдает ошибку
не нужно в моделе что то добавлять. Все данные есть в сессии $this->session->data['wishlist'] Именно его вы можете перебрать, чтобы получить только id товара без ключа.
А если мне сделать такое сравнение товара с wishlist Код: $product_info = $this->model_catalog_product->getProduct($product_id); $this->load->model('account/wishlist'); if ($product_info) { if ($this->session->data['wishlist'] == $this->request->post['product_id']) { $data['AllWishlist'] = true; } } Или есть вот такой код: Код: if (isset($this->session->data['wishlist'])) { if (in_array($product_id, $this->session->data['wishlist'])) { echo 'do something'; } } Но они у меня не сработали или я их ставлю не туда
вставьте его в catalog\controller\product\product.php например перед PHP: if ($product_info) { и увидите результат.
Отлично. Уже есть движение. Но есть не достаток: Когда например в сессии товара нет, залогинимся и добавим товар в закладки, то уже проверка не работает. Я так понял, что уже надо считывать из базы данных. Так как сессия отключается (в плане код). Какие могут быть дальше действия?
Добавил код в catalog/model/account/wishlist.php Код: public function getAllWishlist() { // by nix if ($data = $this->getWishlist()) { $out = array(); foreach ($data as $key => $value) { $out[] = $value['product_id']; } return $out; } else if (isset($this->session->data['wishlist'])) { return $this->session->data['wishlist']; } } Добавил код в catalog/controller/product/product.php Вот такой код: Код: $this->load->model('account/wishlist'); $zol_wish = $this->model_account_wishlist->getAllWishlist(); if (isset($product_id) && isset($zol_wish)) { if (in_array($product_id, $zol_wish)) { $data['AllWishlist'] = true; } } Выше этого кода: Код: if ($product_info) { $url = ''; if (isset($this->request->get['path'])) { В файл catalog/view/theme/default/template/product/product.tpl заменил кнопку сердечка на такой код: Код: <?php if ($logged) { ?> <script type="text/javascript"> function ChangeColor(Element) { Element.style.color = 'red'; } </script> <button <?php if(isset($AllWishlist)) { ?> style="color: red" <?php } ?> type="button" data-toggle="tooltip" class="btn btn-default" title="<?php echo $button_wishlist; ?>" onclick="wishlist.add('<?php echo $product_id; ?>'); ChangeColor(this);"><i class="fa fa-heart"></i></button> <?php } ?> Добавил код в catalog/controller/product/category.php Вот такой код: Код: $this->load->model('account/wishlist'); $data['AllWishlist'] = $this->model_account_wishlist->getAllWishlist(); Выше этого кода: Код: $data['breadcrumbs'] = array(); В файл catalog/view/theme/default/template/product/category.tpl заменил кнопку сердечка на такой код: Код: <?php if ($logged) { ?> <script type="text/javascript"> function ChangeColor(Element) { Element.style.color = 'red'; } </script> <button <?php if(isset($AllWishlist)) { ?> <?php if(in_array($product['product_id'], $AllWishlist)) { ?> style="color: red" <?php } ?> <?php } ?> type="button" data-toggle="tooltip" title="<?php echo $button_wishlist; ?>" onclick="wishlist.add('<?php echo $product['product_id']; ?>'); ChangeColor(this);"><i class="fa fa-heart"></i></button> <?php } ?> Теперь если мы залогинимся, то у товара появиться сердечко. Если нажмём, то оно загорится красным и товар добавиться в закладки. Если удалил из закладок, то сердечко перестанет быть красным. Пример http://best-socks.ru/
Большое Вам человеческое СПАСИБО! Помогло. В контроллер только добавил ещё строчку $data['logged'] = $this->customer->isLogged();
А как бы это всё организовать ещё и для "сопутствующих товаров", что то не получается по той же схеме?
Говорю сразу, я не программист. Всё, что написано получилось, работает. Цель - чтобы на странице товара в разделе "сопутствующие товары" было так же. Т.е. чтобы сердечки у товаров, которые у меня в закладках, были красными. Про это тут нет. Делаю по примеру категории, т.е. в контроллер это Код: $this->load->model('account/wishlist'); $data['AllWishlist'] = $this->model_account_wishlist->getAllWishlist(); в tpl это Код: <?php if ($logged) { ?> <script type="text/javascript"> function ChangeColor(Element) { Element.style.color = 'red'; } </script> <button <?php if(isset($AllWishlist)) { ?> <?php if(in_array($product['product_id'], $AllWishlist)) { ?> style="color: red" <?php } ?> <?php } ?> type="button" data-toggle="tooltip" title="<?php echo $button_wishlist; ?>" onclick="wishlist.add('<?php echo $product['product_id']; ?>'); ChangeColor(this);"><i class="fa fa-heart"></i></button> <?php } ?> В итоге вылазиет ошибка.
Какая ошибка? Честно, мне лень все повторять что написано. (( В общем попробуем по ошибкам найти проблему.