Перейти до вмісту
Пошук в
  • Детальніше...
Шукати результати, які ...
Шукати результати в ...

Сортировка атрибутов в карточке товара


Gann

Recommended Posts

Здравствуйте! Есть ли модуль, который бы позволял сортировать вывод атрибутов в карточке товара?

 

Стандартная сортировка не подойдёт, т.к. в разных группах очередность одного и того же атрибута - разная.

 

Нужно что-то вроде того: при редактировании товара, заполнении атрибутов - чтобы можно было указать порядок сортировки атрибута и выводить в карточку согласно этой сортировке.

Надіслати
Поділитися на інших сайтах

Как я думаю это сделать:

в админку во вкладку атрибутов добавить столбец (для ввода на каждый атрибут) Сортировка, куда будет вводиться значение sort_order_in_product

 

допустим,

в товар с ID=23 я добавлю атрибут "Атрибут1" (id1) и укажу сортировку "1", также атрибут "Атрибут2" (id2) и укажу сортировку "3"

в товар с ID=25 я добавлю атрибут "Атрибут1" (id1) и укажу сортировку "4", также атрибут "Атрибут2" (id2) и укажу сортировку "44"

 

Если в базу данных для атрибутов добавить два дополнительных столбца - id продукта и sort_order_in_product.

Получается, что в БД OC_attribute будет:

attribute_id = 1 attribute_group_id=1(одна группа на все) sort_order=0 (у всех одинаковая) ext_id id_product=23 sort_order_in_product=3

attribute_id = 2 attribute_group_id=1(одна группа на все) sort_order=0 (у всех одинаковая) ext_id id_product=25 sort_order_in_product=44

 

Отлично, но если будет 5000 товаров?

Тогда будет много дублирования атрибутов, так ведь? один и тот же атрибут с разными id_product и sort_order_in_product

 

Как лучше всего сделать, подскажите пожалуйста. Готовое решения вряд ли найдётся

 

 

Надіслати
Поділитися на інших сайтах

Сделать через oc_product_attribute? добавить sort_order_in_product (сортировка атрибутов) сюда?

 

Получается, что нужно будет изменить функцию в product.php public function getProductAttributes($product_id) и всё?
 

Надіслати
Поділитися на інших сайтах

2 минуты назад, Gann сказал:

Получается, что нужно будет изменить функцию в product.php public function getProductAttributes($product_id) и всё?

запись + вывод в админке, вывод (обработка) на витрине

Надіслати
Поділитися на інших сайтах


Итак, сделал запрос в `oc_product_attribute` - добавил sort_order int (11)

______

 

решил делать модификатор:

 

<file path="admin/view/template/catalog/product_form.tpl">	
	<operation>
	<search trim="true"><![CDATA[<td class="text-left"><?php echo $entry_text; ?></td>]]></search>
	<add trim="true" position="after"><![CDATA[
<td class="text-left"><?php echo $entry_sort_order; ?></td>
	]]></add>
	</operation>
	
	<operation>
	<search trim="true"><![CDATA[<?php } ?></td>]]></search>
	<add trim="true" position="after"><![CDATA[
<td class="text-left">
          <div class="input-group">
              <input type="text" name="sort_order" value="<?php echo $sort_order; ?>" placeholder="<?php echo $entry_sort_order; ?>" id="input-sort-order" class="form-control" />
          </div>
</td>
	]]></add>
	</operation>
</file>

 

 

пока верно всё?

 

Змінено користувачем Gann
Надіслати
Поділитися на інших сайтах

Всё, началось самое сложное для меня - работа с БД.

 

<file path="/admin/model/catalog/product.php">	
	<operation>
	<search trim="true"><![CDATA[$this->db->query("INSERT INTO " . DB_PREFIX . "product_attribute SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$product_attribute['attribute_id'] . "', language_id = '" . (int)$language_id . "', text = '" .  $this->db->escape($product_attribute_description['text']) . "'");]]></search>
	<add trim="true" position="replace"><![CDATA[
$this->db->query("INSERT INTO " . DB_PREFIX . "product_attribute SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$product_attribute['attribute_id'] . "', language_id = '" . (int)$language_id . "', text = '" .  $this->db->escape($product_attribute_description['text']) . "', sort_order = '" . (int)$data['sort_order'] . "'");
	]]></add>
	</operation>
</file>

 

для сохранения sort_ordera - верно?

 

Но не сохраняется. В таблице sort_order = NULL

 

контроллер надо смотреть?

Надіслати
Поділитися на інших сайтах

1 час назад, Gann сказал:

контроллер надо смотреть?

да

смотреть добавлена ли отправка sort_order в массив для передачи в модель

 

и лучше при insert не менять существующий, а добавлять свой отдельно - во избежание проблем совместимости с другими дополнениями

  • +1 1
Надіслати
Поділитися на інших сайтах

18 минут назад, AlexDW сказал:

да

смотреть добавлена ли отправка sort_order в массив для передачи в модель

 

Вот сюда:

if ($attribute_info) {
				$data['product_attributes'][] = array(
					'attribute_id'                  => $product_attribute['attribute_id'],
					'name'                          => $attribute_info['name'],
					'product_attribute_description' => $product_attribute['product_attribute_description']
				);
			}

надо добавить строчку:

'sort_order' => $product_attribute['sort_order']

 

Так? или ещё что-то? Смотрю в модель на public function getProductAttributes -  $product_attribute_data[] = array( и не понимаю ничего чёт..
 

 

19 минут назад, AlexDW сказал:

и лучше при insert не менять существующий, а добавлять свой отдельно - во избежание проблем совместимости с другими дополнениями

 

я вот этот инсерт пытаюсь сменить:

 

		if (isset($data['product_attribute'])) {
			foreach ($data['product_attribute'] as $product_attribute) {
				if ($product_attribute['attribute_id']) {
					foreach ($product_attribute['product_attribute_description'] as $language_id => $product_attribute_description) {
						$this->db->query("INSERT INTO " . DB_PREFIX . "product_attribute SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$product_attribute['attribute_id'] . "', language_id = '" . (int)$language_id . "', text = '" .  $this->db->escape($product_attribute_description['text']) . "'");
					}
				}
			}
		}

проблем бы не хотелось, может подскажете, как правильно делать? добавить ниже свой со своими переменными? не понимаю

Надіслати
Поділитися на інших сайтах

как вариант сохранения, при условии что сортировка своя для каждого из языков
 

<file path="admin/model/catalog/product.php">
	<operation>
		<search trim="true"><![CDATA[if (isset($data['product_option'])) {]]></search>
		<add position="before"><![CDATA[
		if (!empty($data['product_attribute'])) {
			foreach ($data['product_attribute'] as $product_attribute) {
				if ($product_attribute['attribute_id']) {
					foreach ($product_attribute['product_attribute_description'] as $language_id => $product_attribute_description) {
						if (isset($product_attribute_description['sort_order'])) {
							$this->db->query("UPDATE " . DB_PREFIX . "product_attribute SET sort_order = '" . (int)$product_attribute_description['sort_order'] . "' WHERE attribute_id = '" . (int)$product_attribute['attribute_id'] . "' AND language_id = '" . (int)$language_id . "'");
						}
					}
				}
			}
		}
		]]></add>
	</operation>
</file>

 

  • +1 1
Надіслати
Поділитися на інших сайтах


В общем, вот что есть на сегодняшний день:

 

<file path="admin/view/template/catalog/product_form.tpl">	
	<operation>
	<search trim="true"><![CDATA[<td class="text-left"><?php echo $entry_text; ?></td>]]></search>
	<add trim="true" position="after"><![CDATA[
<td class="text-left"><?php echo $entry_sort_order; ?></td>
	]]></add>
	</operation>
	
	<operation>
	<search trim="true"><![CDATA[<?php } ?></td>]]></search>
	<add trim="true" position="after"><![CDATA[
<td class="text-left">
          <div class="input-group">
              <input type="text" name="sort_order" value="<?php echo $sort_order; ?>" placeholder="<?php echo $entry_sort_order; ?>" id="input-sort-order" class="form-control" />
          </div>
</td>
	]]></add>
	</operation>
	<operation>
	<search trim="true" index="0"><![CDATA[html += '  </td>';]]></search>
	<add trim="true" position="after"><![CDATA[
	html += '<td class="text-left">';
	html += '<div class="input-group"><input type="text" name="sort_order" value="<?php echo $sort_order; ?>" placeholder="<?php echo $entry_sort_order; ?>" id="input-sort-order" class="form-control" /></div>';
	html += '  </td>';
	]]></add>
	</operation>
</file>
<file path="admin/model/catalog/product.php">
	<operation>
		<search trim="true"><![CDATA[if (isset($data['product_option'])) {]]></search>
		<add position="before"><![CDATA[
		if (!empty($data['product_attribute'])) {
			foreach ($data['product_attribute'] as $product_attribute) {
				if ($product_attribute['attribute_id']) {
					foreach ($product_attribute['product_attribute_description'] as $language_id => $product_attribute_description) {
						if (isset($product_attribute_description['sort_order'])) {
							$this->db->query("UPDATE " . DB_PREFIX . "product_attribute SET sort_order = '" . (int)$product_attribute_description['sort_order'] . "' WHERE attribute_id = '" . (int)$product_attribute['attribute_id'] . "' AND language_id = '" . (int)$language_id . "'");
						}
					}
				}
			}
		}
		]]></add>
	</operation>
</file>
<file path="admin/controller/catalog/product.php">
	<operation>
		<search trim="true"><![CDATA['product_attribute_description' => $product_attribute['product_attribute_description']]]></search>
		<add position="after"><![CDATA[,
		'sort_order' => $product_attribute['sort_order']
		]]></add>
	</operation>
</file>

последняя операция вызывает ошибку Undefined index: sort_order

 

попробовал указать 'sort_order' => $product_attribute_description['sort_order'] показывает Undefined variable: product_attribute_description

 

т.е. не знает такую переменную...

Змінено користувачем Gann
Надіслати
Поділитися на інших сайтах

  • 10 months later...
В 08.06.2017 в 14:58, Gann сказал:

В общем, вот что есть на сегодняшний день:

 


<file path="admin/view/template/catalog/product_form.tpl">	
	<operation>
	<search trim="true"><![CDATA[<td class="text-left"><?php echo $entry_text; ?></td>]]></search>
	<add trim="true" position="after"><![CDATA[
<td class="text-left"><?php echo $entry_sort_order; ?></td>
	]]></add>
	</operation>
	
	<operation>
	<search trim="true"><![CDATA[<?php } ?></td>]]></search>
	<add trim="true" position="after"><![CDATA[
<td class="text-left">
          <div class="input-group">
              <input type="text" name="sort_order" value="<?php echo $sort_order; ?>" placeholder="<?php echo $entry_sort_order; ?>" id="input-sort-order" class="form-control" />
          </div>
</td>
	]]></add>
	</operation>
	<operation>
	<search trim="true" index="0"><![CDATA[html += '  </td>';]]></search>
	<add trim="true" position="after"><![CDATA[
	html += '<td class="text-left">';
	html += '<div class="input-group"><input type="text" name="sort_order" value="<?php echo $sort_order; ?>" placeholder="<?php echo $entry_sort_order; ?>" id="input-sort-order" class="form-control" /></div>';
	html += '  </td>';
	]]></add>
	</operation>
</file>
<file path="admin/model/catalog/product.php">
	<operation>
		<search trim="true"><![CDATA[if (isset($data['product_option'])) {]]></search>
		<add position="before"><![CDATA[
		if (!empty($data['product_attribute'])) {
			foreach ($data['product_attribute'] as $product_attribute) {
				if ($product_attribute['attribute_id']) {
					foreach ($product_attribute['product_attribute_description'] as $language_id => $product_attribute_description) {
						if (isset($product_attribute_description['sort_order'])) {
							$this->db->query("UPDATE " . DB_PREFIX . "product_attribute SET sort_order = '" . (int)$product_attribute_description['sort_order'] . "' WHERE attribute_id = '" . (int)$product_attribute['attribute_id'] . "' AND language_id = '" . (int)$language_id . "'");
						}
					}
				}
			}
		}
		]]></add>
	</operation>
</file>
<file path="admin/controller/catalog/product.php">
	<operation>
		<search trim="true"><![CDATA['product_attribute_description' => $product_attribute['product_attribute_description']]]></search>
		<add position="after"><![CDATA[,
		'sort_order' => $product_attribute['sort_order']
		]]></add>
	</operation>
</file>

последняя операция вызывает ошибку Undefined index: sort_order

 

попробовал указать 'sort_order' => $product_attribute_description['sort_order'] показывает Undefined variable: product_attribute_description

 

т.е. не знает такую переменную...

 

Решили проблему ? 
тоже заинтересовался методом сортировки

Надіслати
Поділитися на інших сайтах


Створіть аккаунт або увійдіть для коментування

Ви повинні бути користувачем, щоб залишити коментар

Створити обліковий запис

Зареєструйтеся для отримання облікового запису. Це просто!

Зареєструвати аккаунт

Вхід

Уже зареєстровані? Увійдіть тут.

Вхід зараз
  • Зараз на сторінці   0 користувачів

    • Ні користувачів, які переглядиють цю сторінку

×
×
  • Створити...

Important Information

На нашому сайті використовуються файли cookie і відбувається обробка деяких персональних даних користувачів, щоб поліпшити користувальницький інтерфейс. Щоб дізнатися для чого і які персональні дані ми обробляємо перейдіть за посиланням . Якщо Ви натиснете «Я даю згоду», це означає, що Ви розумієте і приймаєте всі умови, зазначені в цьому Повідомленні про конфіденційність.