Как добавить пользовательский параметр сортировки в Magento. Я хочу добавить Бестселлеры, Лучшие и эксклюзивные в дополнение к сортировке по цене. Пожалуйста, помогитеMagento Custom Sort Option
ответ
Для Бестселлеры
haneged в code/local/Mage/Catalog/Block/Product/List/Toolbar.php
метод setCollection к
public function setCollection($collection) {
parent::setCollection($collection);
if ($this->getCurrentOrder()) {
if($this->getCurrentOrder() == 'saleability') {
$this->getCollection()->getSelect()
->joinLeft('sales_flat_order_item AS sfoi', 'e.entity_id = sfoi.product_id', 'SUM(sfoi.qty_ordered) AS ordered_qty')
->group('e.entity_id')->order('ordered_qty' . $this->getCurrentDirectionReverse());
} else {
$this->getCollection()
->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
}
}
return $this;
}
После setCollection я добавил этот метод:
public function getCurrentDirectionReverse() {
if ($this->getCurrentDirection() == 'asc') {
return 'desc';
} elseif ($this->getCurrentDirection() == 'desc') {
return 'asc';
} else {
return $this->getCurrentDirection();
}
}
И, наконец, я изменил mehod setDefaultOrder на
public function setDefaultOrder($field) {
if (isset($this->_availableOrder[$field])) {
$this->_availableOrder = array(
'name' => $this->__('Name'),
'price' => $this->__('Price'),
'position' => $this->__('Position'),
'saleability' => $this->__('Saleability'),
);
$this->_orderField = $field;
}
return $this;
}
для Лучшего по рейтингу
http://www.fontis.com.au/blog/magento/sort-products-rating
попытки выше коды.
на дату добавление
я не ассоциироваться с каким-либо из указанной выше ссылки для любой работы или беспокойства это только для целей знания и решить вашу проблему.
надеюсь, что это обязательно поможет.
Спасибо за ваш ответ, Анудж, это был лучший рабочий модуль, который я мог найти до сих пор.
Просто добавьте дополнительный бит в код, чтобы не решить не пагинации, вызванной «группой»
Copy «» /lib/varien/data/collection/Db.php «местный/Varien/данные/коллекция/dB.php.
Изменения функция GETSIZE в
public function getSize()
{
if (is_null($this->_totalRecords)) {
$sql = $this->getSelectCountSql();
//$this->_totalRecords = $this->getConnection()->fetchOne($sql, $this->_bindParams); //============================>change behave of fetchOne to fetchAll
//got array of all COUNT(DISTINCT e.entity_id), then sum
$result = $this->getConnection()->fetchAll($sql, $this->_bindParams);
foreach ($result as $row) {//echo'<pre>'; print_r($row);
$this->_totalRecords += reset($row);
}
}
return intval($this->_totalRecords);
}
Надеется, что это может помочь любому.
обновление Секция фильтра должны быть обновлены, а также, в противном случае просто показывает 1 пункт на всем фильтре. и ценовой фильтр не будут точными.
Что вам нужно сделать, это изменить ядро / Mage/каталог/модель/слой/фильтр/attribute.php и price.php
attribute.php GetCount() на нижней
$countArr = array();
//print_r($connection->fetchall($select));
foreach ($connection->fetchall($select) as $single)
{
if (isset($countArr[$single['value']]))
{
$countArr[$single['value']] += $single['count'];
}
else
{
$countArr[$single['value']] = $single['count'];
}
}
//print_r($countArr);//exit;
return $countArr;
//return $connection->fetchPairs($select);
Price.php getMaxPrice
$maxPrice = 0;
foreach ($connection->fetchall($select) as $value)
{
if (reset($value) > $maxPrice)
{
$maxPrice = reset($value);
}
}
return $maxPrice;
Если вы с той же проблемой и ищет этот вопрос, вы будете знать, что я имел в виду. Удачи, потратил 8 часов на эту лучшую функцию продажи.
Update снова,
просто нашел еще один способ реализовать используя хроны собрать лучшие данные о продаже ежедневно, сохраненных в таблице, которая включает в себя PRODUCT_ID и вычисленные базовую продажу фигуры. , а затем просто влево, не применяя 'group by' , что означает, что функции ядра не нуждаются в изменении и ускорении всего процесса сортировки. Наконец-то! хе-хе.
Чтобы разобраться в проблеме постраничной для сортировки коллекции пользовательских переписать модель ресурса из его коллекции от
app\code\core\Mage\Catalog\Model\Resource\Product\Collection.phpи модифицировать ниже метод из ядра
protected function _getSelectCountSql($select = null, $resetLeftJoins = true) { $this->_renderFilters(); $countSelect = (is_null($select)) ? $this->_getClearSelect() : $this->_buildClearSelect($select);/*Added to reset count filters for Group*/ if(count($countSelect->getPart(Zend_Db_Select::GROUP)) > 0) { $countSelect->reset(Zend_Db_Select::GROUP); } /*Added to reset count filters for Group*/ $countSelect->columns('COUNT(DISTINCT e.entity_id)'); if ($resetLeftJoins) { $countSelect->resetJoinLeft(); } return $countSelect; }
Над разрешим счета вопрос для сбор пользовательских сортировок.
- 1. Magento Custom Option If Statement
- 2. Magento Custom Option Quantity Update
- 3. Magento custom option - clear field field issue
- 4. C++ custom sort sort function
- 5. Rails render custom option
- 6. Bxslider Custom Pager Option
- 7. Magento Custom Backend module Grid sort/filter problem
- 8. custom sort bash array
- 9. YUI DataTable custom sort
- 10. Kendo grid custom sort
- 11. WooCommerce Custom Sort Plugin
- 12. ArangoDB custom sort order
- 13. Custom sort python
- 14. C++ sort custom function
- 15. sort custom Array List
- 16. XPath Custom Sort Expression
- 17. Groovy custom sort
- 18. Custom sort with wildcard
- 19. Ransack custom default sort
- 20. Custom datatable sort
- 21. dgrid custom sort issue
- 22. NSDictionary sort algorithm custom
- 23. Python custom sort
- 24. XSLT Custom Sort
- 25. Custom sort in C++
- 26. Wordpress Sort Posts/Custom Post Type
- 27. Magento sort regions default_name
- 28. UIView transitionWithView custom animation option
- 29. Parse Custom Date and Sort
- 30. Custom Sort in Crystal Reports
Это отлично работает для меня. Благодаря!! Btw Вместо того, чтобы напрямую менять файлы Core в Mage, я бы рекомендовал переехать в собственный модуль. –
это не изменяется напрямую. Я использовал 'code/local/Mage/Catalog', это локальный код, а не основной файл. но вы также можете использовать его в своем настраиваемом модуле для перезаписи блока – liyakat