Пейджер не выполняет подкачку в пользовательской коллекции категорий (остальная часть панели инструментов в порядке)
Я показываю пользовательскую коллекцию продуктов в блоке, который расширяет блок категорий. Я использую Magento 1.9 и шаблон по умолчанию.
Моя проблема в том, что пейджер работает неправильно. Он отображает правильное количество продуктов в коллекции, но ограничение не работает, даже если я добавлю его в URL-адрес в качестве параметра. Другие элементы панели инструментов (сортировка и переключение сетки/списка) работают.
Примером этой проблемы является то, что если есть 18 товаров в коллекции, на пейджере будет написано "Товары с 1 по 18 из 18 всего / Показать 12 на странице".
Я думаю, что корень проблемы находится где-то в моем блоке сбора данных. Я попробовал метод $pager->setcollection ($collection), как описано в ответе на этот пост, и попробовал это без заметных изменений в результатах.
Как мне заставить пейджер работать? Нужно ли мне создавать новый блок, который расширяет пейджер по умолчанию и используется в данном случае (похоже на небрежная идея), или есть собственное решение?
Layout.xml :
<?xml version="1.0" ?>
<layout>
<customer_items_index translate="label">
<label>Customer My Account Items</label>
<reference name="content">
<block type="myitems/customer_items" name="customer_items" template="catalog/category/view.phtml">
<block type="myitems/customer_list" name="customer_items_list" template="catalog/product/list.phtml">
<block type="catalog/product_list_toolbar" name="customer_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="customer_list_toolbar_pager"/>
</block>
</block>
</block>
</reference>
<reference name="left">
<block type="catalog/navigation" name="catalog.leftnav" after="currency" template="catalog/navigation/left.phtml"/>
</reference>
</customer_items_index>
<customer_account translate="label">
<reference name="customer_account_navigation">
<action method="addLink"><name>items</name><path>customer/items/</path><label>My Items</label></action>
</reference>
</customer_account>
List.php (код блока сбора данных):
class Rdc_MyItems_Block_Customer_List extends Mage_Catalog_Block_Product_List
{
protected function _getProductCollection() {
$customerId = Mage::getSingleton('customer/session')->getCustomer()->getId();
$productIds = Mage::helper('myitems')->getAllCustomerItems($customerId);
$_productCollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', array(
'in' => $productIds,
))
->load();
return $_productCollection;
}
protected function _prepareLayout()
{
parent::_prepareLayout();
$collection = $this->_getProductCollection();
$pager = $this->getLayout()->createBlock('page/html_pager', 'sales.order.history.pager')->setCollection($collection);
$this->setChild('pager', $pager);
}
public function getPagerHtml()
{
return $this->getChildHtml('pager');
}
}
Редактировать:
Я также расширяю блок catalog/category
и думаю, что моя проблема может быть связана с этим. "Категория", которую я создаю, - это пустая категория, в которой заданы только имя и описание. Коллекция продуктов не создается до тех пор, пока не будет установлен блок product_list
. Это выглядит вероятно, я смогу избавиться от своего пользовательского класса категорий и упростить свою проблему:
Items.php :
class Rdc_MyItems_Block_Customer_Items extends Mage_Catalog_Block_Category_View
{
public function getProductListHtml()
{
return $this->getChildHtml('customer_items_list');
}
public function getCurrentCategory()
{
$category = Mage::getModel('catalog/category')
->setName("My Items")
->setDescription("You bought these things.");
return $category;
}
}
2 answers
Это поможет, я думаю, решить проблему с загрузкой коллекции
parent::_prepareLayout();
$collection = $this->_getProductCollection();
$pager = $this->getLayout()->createBlock('page/html_pager', 'sales.order.history.pager')->setCollection($collection);
$this->setChild('pager', $pager);
$this->getCollection()->load();
return $this;
Пейджер использует каталог/слой для извлечения элементов для отображения на данной странице каталога. Чтобы заставить пейджер работать, мне нужно было создать подкласс Mage_Catalog_Model_Layer
и обновить код как в List.php
, так и в xml-файле макета.
Недавно добавленный Layer.php:
<?php
class MyCompany_MyItems_Model_Layer extends Mage_Catalog_Model_Layer
{
public function getProductCollection()
{
$customerId = Mage::getSingleton('customer/session')->getCustomer()->getId();
$productIds = Mage::helper('myitems')->getAllCustomerItems($customerId);
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', array(
'in' => $productIds,
));
return $collection;
}
/**
* Retrieve current category model
* If no category found in registry, the root will be taken
*
* @return Mage_Catalog_Model_Category
*/
public function getCurrentCategory()
{
$category = $this->getData('current_category');
if (is_null($category)) {
$category = Mage::getModel('catalog/category');
}
return $category;
}
/**
* Change current category object
*
* @param mixed $category
* @return Mage_Catalog_Model_Layer
*/
public function setCurrentCategory($category)
{
return $this;
}
}
Обновлено List.php:
<?php
class Sc_MyItems_Block_Customer_List extends Mage_Catalog_Block_Product_List
{
public function getLayer()
{
$layer = Mage::registry('current_layer');
if ($layer) {
return $layer;
}
return Mage::getSingleton('myitems/layer');
}
protected function _getProductCollection()
{
if (is_null($this->_productCollection)) {
$layer = $this->getLayer();
$this->_productCollection = $layer->getProductCollection();
}
return $this->_productCollection;
}
}
Обновлено layout.xml:
<?xml version="1.0" ?>
<layout>
<customer_items_index translate="label">
<label>Customer My Account Items</label>
<reference name="content">
<block type="myitems/customer_items" name="customer_items" template="catalog/category/view.phtml">
<block type="myitems/customer_list" name="customer_items_list" template="catalog/product/list.phtml">
<block type="core/text_list" name="product_list.name.after" as="name.after" />
<block type="core/text_list" name="product_list.after" as="after" />
<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="product_list_toolbar_pager"/>
</block>
<action method="setToolbarBlockName">
<name>product_list_toolbar</name>
</action>
</block>
</block>
</reference>
<reference name="left">
<block type="catalog/layer_view" name="catalog.layer.filter.view" template="catalog/layer/view.phtml"/>
</reference>
</customer_items_index>
<customer_account translate="label">
<reference name="customer_account_navigation">
<action method="addLink"><name>items</name><path>customer/items/</path><label>My Items</label></action>
</reference>
</customer_account>
</layout>