Opencart: Добавляем колонку SKU (поиск, фильтр, автодополнение, сортировка) в список товаров в backend
Бывает полезно иметь колонку с артикулом товара (SKU) в админке магазина. Хорошее решение от Руслана Бреста.

Для OpenCart 1.5.1.3 добавляем в админ-часть в список товаров колонку SKU (по-русски -- артикул или складской номер). В отличие от разработчиков поиск станет возможен по любому вхождению искомых символов - они могут встречаться в любом месте строчки SKU, а не только с её начала. Без этого ограничения удобнее намного:
commit 144af0b3466be74fb55f913686f96290b2c231a5
Author: Ruslan Brest <rb@labtodo.com>
Date: Mon Oct 10 13:49:45 2011 +0300
[+] admin: products SKU column (search, filter, autocomplete, sort)
diff --git a/upload/admin/controller/catalog/product.php b/upload/admin/controller/catalog/product.php
index 655b09d..72382b6 100644
--- a/upload/admin/controller/catalog/product.php
+++ b/upload/admin/controller/catalog/product.php
@@ -234,10 +234,16 @@ class ControllerCatalogProduct extends Controller {
if (isset($this->request->get['filter_model'])) {
$filter_model = $this->request->get['filter_model'];
} else {
$filter_model = null;
}
+
+ if (isset($this->request->get['filter_sku'])) {
+ $filter_sku = $this->request->get['filter_sku'];
+ } else {
+ $filter_sku = null;
+ }
if (isset($this->request->get['filter_price'])) {
$filter_price = $this->request->get['filter_price'];
} else {
$filter_price = null;
@@ -280,10 +286,13 @@ class ControllerCatalogProduct extends Controller {
}
if (isset($this->request->get['filter_model'])) {
$url .= '&filter_model=' . $this->request->get['filter_model'];
}
+ if (isset($this->request->get['filter_sku'])) {
+ $url .= '&filter_sku=' . $this->request->get['filter_sku'];
+ }
if (isset($this->request->get['filter_price'])) {
$url .= '&filter_price=' . $this->request->get['filter_price'];
}
@@ -328,10 +337,11 @@ class ControllerCatalogProduct extends Controller {
$this->data['products'] = array();
$data = array(
'filter_name' => $filter_name,
'filter_model' => $filter_model,
+ 'filter_sku' => $filter_sku,
'filter_price' => $filter_price,
'filter_quantity' => $filter_quantity,
'filter_status' => $filter_status,
'sort' => $sort,
'order' => $order,
@@ -373,10 +383,11 @@ class ControllerCatalogProduct extends Controller {
$this->data['products'][] = array(
'product_id' => $result['product_id'],
'name' => $result['name'],
'model' => $result['model'],
+ 'sku' => $result['sku'],
'price' => $result['price'],
'special' => $special,
'image' => $image,
'quantity' => $result['quantity'],
'status' => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
@@ -391,12 +402,13 @@ class ControllerCatalogProduct extends Controller {
$this->data['text_disabled'] = $this->language->get('text_disabled');
$this->data['text_no_results'] = $this->language->get('text_no_results');
$this->data['text_image_manager'] = $this->language->get('text_image_manager');
$this->data['column_image'] = $this->language->get('column_image');
- $this->data['column_name'] = $this->language->get('column_name');
+ $this->data['column_name'] = $this->language->get('column_name');
$this->data['column_model'] = $this->language->get('column_model');
+ $this->data['column_sku'] = $this->language->get('entry_sku');
$this->data['column_price'] = $this->language->get('column_price');
$this->data['column_quantity'] = $this->language->get('column_quantity');
$this->data['column_status'] = $this->language->get('column_status');
$this->data['column_action'] = $this->language->get('column_action');
@@ -428,10 +440,13 @@ class ControllerCatalogProduct extends Controller {
}
if (isset($this->request->get['filter_model'])) {
$url .= '&filter_model=' . $this->request->get['filter_model'];
}
+ if (isset($this->request->get['filter_sku'])) {
+ $url .= '&filter_sku=' . $this->request->get['filter_sku'];
+ }
if (isset($this->request->get['filter_price'])) {
$url .= '&filter_price=' . $this->request->get['filter_price'];
}
@@ -453,10 +468,11 @@ class ControllerCatalogProduct extends Controller {
$url .= '&page=' . $this->request->get['page'];
}
$this->data['sort_name'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&sort=pd.name' . $url, 'SSL');
$this->data['sort_model'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&sort=p.model' . $url, 'SSL');
+ $this->data['sort_sku'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&sort=p.sku' . $url, 'SSL');
$this->data['sort_price'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&sort=p.price' . $url, 'SSL');
$this->data['sort_quantity'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&sort=p.quantity' . $url, 'SSL');
$this->data['sort_status'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&sort=p.status' . $url, 'SSL');
$this->data['sort_order'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&sort=p.sort_order' . $url, 'SSL');
@@ -467,10 +483,13 @@ class ControllerCatalogProduct extends Controller {
}
if (isset($this->request->get['filter_model'])) {
$url .= '&filter_model=' . $this->request->get['filter_model'];
}
+ if (isset($this->request->get['filter_sku'])) {
+ $url .= '&filter_sku=' . $this->request->get['filter_sku'];
+ }
if (isset($this->request->get['filter_price'])) {
$url .= '&filter_price=' . $this->request->get['filter_price'];
}
@@ -499,10 +518,11 @@ class ControllerCatalogProduct extends Controller {
$this->data['pagination'] = $pagination->render();
$this->data['filter_name'] = $filter_name;
$this->data['filter_model'] = $filter_model;
+ $this->data['filter_sku'] = $filter_sku;
$this->data['filter_price'] = $filter_price;
$this->data['filter_quantity'] = $filter_quantity;
$this->data['filter_status'] = $filter_status;
$this->data['sort'] = $sort;
@@ -649,10 +669,13 @@ class ControllerCatalogProduct extends Controller {
}
if (isset($this->request->get['filter_model'])) {
$url .= '&filter_model=' . $this->request->get['filter_model'];
}
+ if (isset($this->request->get['filter_sku'])) {
+ $url .= '&filter_sku=' . $this->request->get['filter_sku'];
+ }
if (isset($this->request->get['filter_price'])) {
$url .= '&filter_price=' . $this->request->get['filter_price'];
}
@@ -1204,11 +1227,11 @@ class ControllerCatalogProduct extends Controller {
}
public function autocomplete() {
$json = array();
- if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model']) || isset($this->request->get['filter_category_id'])) {
+ if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model']) || isset($this->request->get['filter_sku']) || isset($this->request->get['filter_category_id'])) {
$this->load->model('catalog/product');
if (isset($this->request->get['filter_name'])) {
$filter_name = $this->request->get['filter_name'];
} else {
@@ -1218,11 +1241,17 @@ class ControllerCatalogProduct extends Controller {
if (isset($this->request->get['filter_model'])) {
$filter_model = $this->request->get['filter_model'];
} else {
$filter_model = '';
}
-
+
+ if (isset($this->request->get['filter_sku'])) {
+ $filter_sku = $this->request->get['filter_sku'];
+ } else {
+ $filter_sku = '';
+ }
+
if (isset($this->request->get['filter_category_id'])) {
$filter_category_id = $this->request->get['filter_category_id'];
} else {
$filter_category_id = '';
}
@@ -1240,10 +1269,11 @@ class ControllerCatalogProduct extends Controller {
}
$data = array(
'filter_name' => $filter_name,
'filter_model' => $filter_model,
+ 'filter_sku' => $filter_sku,
'filter_category_id' => $filter_category_id,
'filter_sub_category' => $filter_sub_category,
'start' => 0,
'limit' => $limit
);
@@ -1291,10 +1321,11 @@ class ControllerCatalogProduct extends Controller {
$json[] = array(
'product_id' => $result['product_id'],
'name' => html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8'),
'model' => $result['model'],
+ 'sku' => $result['sku'],
'option' => $option_data,
'price' => $result['price']
);
}
}
diff --git a/upload/admin/model/catalog/product.php b/upload/admin/model/catalog/product.php
index b75d072..fab30d9 100644
--- a/upload/admin/model/catalog/product.php
+++ b/upload/admin/model/catalog/product.php
@@ -350,10 +350,13 @@ class ModelCatalogProduct extends Model {
}
if (!empty($data['filter_model'])) {
$sql .= " AND LCASE(p.model) LIKE '" . $this->db->escape(utf8_strtolower($data['filter_model'])) . "%'";
}
+ if (!empty($data['filter_sku'])) {
+ $sql .= " AND LCASE(p.sku) LIKE '%" . $this->db->escape(utf8_strtolower($data['filter_sku'])) . "%'";
+ }
if (!empty($data['filter_price'])) {
$sql .= " AND p.price LIKE '" . $this->db->escape($data['filter_price']) . "%'";
}
@@ -388,10 +391,11 @@ class ModelCatalogProduct extends Model {
$sql .= " GROUP BY p.product_id";
$sort_data = array(
'pd.name',
'p.model',
+ 'p.sku',
'p.price',
'p.quantity',
'p.status',
'p.sort_order'
);
@@ -659,10 +663,14 @@ class ModelCatalogProduct extends Model {
if (!empty($data['filter_model'])) {
$sql .= " AND LCASE(p.model) LIKE '" . $this->db->escape(utf8_strtolower($data['filter_model'])) . "%'";
}
+ if (!empty($data['filter_sku'])) {
+ $sql .= " AND LCASE(p.sku) LIKE '%" . $this->db->escape(utf8_strtolower($data['filter_sku'])) . "%'";
+ }
+
if (!empty($data['filter_price'])) {
$sql .= " AND p.price LIKE '" . $this->db->escape($data['filter_price']) . "%'";
}
if (isset($data['filter_quantity']) && !is_null($data['filter_quantity'])) {
diff --git a/upload/admin/view/template/catalog/product_list.tpl b/upload/admin/view/template/catalog/product_list.tpl
index 25b90b3..c183b7d 100644
--- a/upload/admin/view/template/catalog/product_list.tpl
+++ b/upload/admin/view/template/catalog/product_list.tpl
@@ -31,10 +31,15 @@
<td class="left"><?php if ($sort == 'p.model') { ?>
<a href="<?php echo $sort_model; ?>" class="<?php echo strtolower($order); ?>"><?php echo $column_model; ?></a>
<?php } else { ?>
<a href="<?php echo $sort_model; ?>"><?php echo $column_model; ?></a>
<?php } ?></td>
+ <td class="left"><?php if ($sort == 'p.sku') { ?>
+ <a href="<?php echo $sort_sku; ?>" class="<?php echo strtolower($order); ?>"><?php echo $column_sku; ?></a>
+ <?php } else { ?>
+ <a href="<?php echo $sort_sku; ?>"><?php echo $column_sku; ?></a>
+ <?php } ?></td>
<td class="left"><?php if ($sort == 'p.price') { ?>
<a href="<?php echo $sort_price; ?>" class="<?php echo strtolower($order); ?>"><?php echo $column_price; ?></a>
<?php } else { ?>
<a href="<?php echo $sort_price; ?>"><?php echo $column_price; ?></a>
<?php } ?></td>
@@ -55,10 +60,11 @@
<tr class="filter">
<td></td>
<td></td>
<td><input type="text" name="filter_name" value="<?php echo $filter_name; ?>" /></td>
<td><input type="text" name="filter_model" value="<?php echo $filter_model; ?>" /></td>
+ <td><input type="text" name="filter_sku" value="<?php echo $filter_sku; ?>" /></td>
<td align="left"><input type="text" name="filter_price" value="<?php echo $filter_price; ?>" size="8"/></td>
<td align="right"><input type="text" name="filter_quantity" value="<?php echo $filter_quantity; ?>" style="text-align: right;" /></td>
<td><select name="filter_status">
<option value="*"></option>
<?php if ($filter_status) { ?>
@@ -83,10 +89,11 @@
<input type="checkbox" name="selected[]" value="<?php echo $product['product_id']; ?>" />
<?php } ?></td>
<td class="center"><img src="<?php echo $product['image']; ?>" alt="<?php echo $product['name']; ?>" style="padding: 1px; border: 1px solid #DDDDDD;" /></td>
<td class="left"><?php echo $product['name']; ?></td>
<td class="left"><?php echo $product['model']; ?></td>
+ <td class="left"><?php echo $product['sku']; ?></td>
<td class="left"><?php if ($product['special']) { ?>
<span style="text-decoration: line-through;"><?php echo $product['price']; ?></span>
<span style="color: #b00;"><?php echo $product['special']; ?></span>
<?php } else { ?>
<?php echo $product['price']; ?>
@@ -130,10 +137,16 @@ function filter() {
if (filter_model) {
url += '&filter_model=' + encodeURIComponent(filter_model);
}
+ var filter_sku = $('input[name=\'filter_sku\']').attr('value');
+
+ if (filter_sku) {
+ url += '&filter_sku=' + encodeURIComponent(filter_sku);
+ }
+
var filter_price = $('input[name=\'filter_price\']').attr('value');
if (filter_price) {
url += '&filter_price=' + encodeURIComponent(filter_price);
}
@@ -204,7 +217,30 @@ $('input[name=\'filter_model\']').autocomplete({
$('input[name=\'filter_model\']').val(ui.item.label);
return false;
}
});
+
+$('input[name=\'filter_sku\']').autocomplete({
+ delay: 0,
+ source: function(request, response) {
+ $.ajax({
+ url: 'index.php?route=catalog/product/autocomplete&token=<?php echo $token; ?>&filter_sku=' + encodeURIComponent(request.term),
+ dataType: 'json',
+ success: function(json) {
+ response($.map(json, function(item) {
+ return {
+ label: item.sku,
+ value: item.product_id
+ }
+ }));
+ }
+ });
+ },
+ select: function(event, ui) {
+ $('input[name=\'filter_sku\']').val(ui.item.label);
+
+ return false;
+ }
+});
//--></script>
<?php echo $footer; ?>
\ No newline at end of file
almix
Разработчик Loco, автор статей по веб-разработке на Yii, CodeIgniter, MODx и прочих инструментах. Создатель Team Sense.
Вы можете почитать все статьи от almix'а.
- 0 Opencart: Скидки для пользователей, надо указывать в колонке "количество" значение, отличное от нуля! (02.07.2014)
- 0 Как оперативно создать интернет-магазин на основе шаблона OpenCart? (05.06.2014)
- 0 Opencart: Установка мета тега Keywords для главной страницы через админку (05.12.2013)
- 0 Opencart: война модулей FilterPro mega, Intelligent Product Labels, AStickers - Ajax стикеры (24.10.2013)
- 0 Opencart: Модуль Filter Product OpenCart_v1.5.x: Как скрывать недоступные опции в фильтре (23.10.2013)
- 0 Ошибка xml файла Opencart для Яндекс Маркета: <b>Notice</b>: iconv(): Detected an illegal character in input string... (04.09.2013)
- 0 Opencart: Выводить изображения подкатегорий на странице категории. (11.07.2013)
- 0 Opencart: Вывод атрибутов вместо описания в категориях. (23.10.2013)
- 0 Opencart: Обновление движка с версии 1.4.9 до 1.5.1.3! (05.02.2015)
- 0 Opencart: Вставляем имя покупателя в модуле JV_QuickOrder - быстрый заказ товара (22.04.2013)
- 0 OpenCart: Fancybox (или colorbox)+"cloud-zoom" одновременно. Значок-ссылка поверх изображения товара на просмотр в полный вид (03.06.2013)
- 0 OpenCart: Делаем шаблон растягиваемым и добавляем отступы. (10.01.2014)
- Как включить SSL и сделать редирект на HTTPS. На примере Opencart 2 (03.12.2017)
- Opencart 2: Цена за квадратный метр, за штуку и др. (05.10.2017)
- Opencart 2: Cлайдер Owl Carousel в OcStore 2.1.0.2. Что делать, если слайдер не работает? (10.05.2017)
- Opencart 2: Добавляем новую позицию в макет для вывода модуля (27.04.2017)
- SEO оптимизация хлебных крошек breadcrumbs в Opencart 2 (27.04.2017)
- Opencart 2: Закладки без регистрации (Wishlist without registration) (26.04.2017)
- Opencart 2: сделать разные валюты в админке и на сайте (24.04.2017)
- Opencart 2: OCMOD замена нескольких строк (12.04.2017)
- Как установить расширение в Opencart 2 (27.04.2017)
- Загрузка файлов (картинок) по ajax через форму для Opencart (04.09.2016)
- Opencart: Как не показывать какой-либо товар в списке на странице производителей? (29.07.2015)
- Порядок баннеров в Opencart (15.05.2015)
- Устанавливаем ionCube Loader на MAMP за пару минут. (06.02.2015)
9 комментариев
РозРазъясните как ориентироваться в нем?Павел - комментарии по ходу кода - это разница между тем, что было и тем, что стало после изменений (difference), это автоматически вставляется (например на github так удобно для сравнения версий кода):
Спасибо автору!
За 20 минут сделал на 1.5.4.1
Строки там немного другие, но догадаться можно!