Sorting 渲染列上的Magento网格排序
我已经在Magento中创建了一个网格,其中有一列不是来自数据库,而是使用渲染器从其他列计算了它的值。 假设网格中的自定义列为total=columnA from DB-columnB from DB,则必须根据自定义列对网格进行排序。 我在我的网格中重写了setCollectionToOrder函数,对从prepareCollection函数接收到的集合进行排序,并将排序后的集合放入新的集合对象中,但我的网格没有显示任何行,尽管我可以回显排序后的集合,它工作正常,但网格中没有行Sorting 渲染列上的Magento网格排序,sorting,magento,grid,Sorting,Magento,Grid,我已经在Magento中创建了一个网格,其中有一列不是来自数据库,而是使用渲染器从其他列计算了它的值。 假设网格中的自定义列为total=columnA from DB-columnB from DB,则必须根据自定义列对网格进行排序。 我在我的网格中重写了setCollectionToOrder函数,对从prepareCollection函数接收到的集合进行排序,并将排序后的集合放入新的集合对象中,但我的网格没有显示任何行,尽管我可以回显排序后的集合,它工作正常,但网格中没有行 prot
protected function _setCollectionOrder($column)
{
$collection = $this->getCollection();
if ($collection) {
switch ($column->getId()) {
case 'total':
$arr = array();
foreach($collection as $item) {
$colA= $item->getcolumnA();
$colB= $item->getcolumnB()
$total= $colA- $colB
$item->setTotal($total);
$arr[$i] = $item; $i++ ;
}
if($column->getDir()=='asc') {
$sorted = usort($arr, array('Grid_Class', '_cmpAscTotal'));
} else {
$sorted = usort($arr, array('Grid_Class', '_cmpDescTotal'));
}
$collection = $this->_tempCollection(); // A blank collection
for($i=0;$i<count($arr);$i++) {
$arr[$i]->setTotal(1);
$collection->addItem($arr[$i]);
}
$this->setCollection($collection);
break;
default:
parent::_setCollectionOrder($column);
break;
}
}
return $this;
}
是否有更好的方法在自定义列上实现排序集合,如果不是我在修改集合时所做的错误,即网格变为空实际上,您应该扩展集合类并在集合
\u afterLoad
方法中添加自定义排序。如果由于某种原因不可能,您应该在网格\u afterLoadCollection
方法中执行此操作。在任何情况下,您都不能/不应该/没有在collection\u setCollectionOrder
方法中执行此操作。因为如果你查看Mage\u Adminhtml\u Block\u Widget\u Grid::\u prepareCollection()
code-你会看到\u setCollectionOrder
在集合加载之前被调用
更新:
protected function _afterLoadCollection()
{
foreach ($this->getCollection() as $item) {
$item->setTotal($item->getcolumnA() - $item->getcolumnB());
}
usort($this->getCollection()->getIterator(), array('Grid_Class', '_cmpAscTotal'));
return $this;
}
谢谢Zyava
我必须像这样做-
$arr = $this->getCollection()->getItems();
if($dir=='asc') {
$sorted = usort($arr, array('Grid_Class', '_cmpAscSuggestion'));
} else {
$sorted = usort($arr, array('Grid_Class', '_cmpDescSuggestion'));
}
$this->getCollection()->setItems($arrt); // created a set item function in collection class for this module.
它对集合中的项目进行排序。@Zyava我曾尝试在_afterLoadCollection中打印我的自定义集合对象(我在setCollectionOrder函数中设置),我能够以排序的方式正确检索它,但网格中仍然没有行。我想问题是,如果我修改从db获得的相同集合对象,grid可以理解它,但若我创建一个空白的集合对象FRMDB并逐个添加项,grid就无法理解这一点。任何帮助都将不胜感激!!嗯,尝试不使用临时集合进行排序。我使用Usort进行排序,如果我输入集合,它不会调用回调函数。这就是为什么我必须在一个对象数组中获取所有集合项,使用Usort进行排序,然后在一个新集合对象中逐个添加所有新项。您能告诉我一些直接对集合进行排序的方法吗?仍然不明白为什么您不希望创建o=您自己的集合类并在那里进行所有数据处理。我用一段代码更新了我的答案,试试类似的东西。我怎样才能得到渲染列的总数?嗨,你把这些代码放在哪里?
$dir
来自哪里?
$arr = $this->getCollection()->getItems();
if($dir=='asc') {
$sorted = usort($arr, array('Grid_Class', '_cmpAscSuggestion'));
} else {
$sorted = usort($arr, array('Grid_Class', '_cmpDescSuggestion'));
}
$this->getCollection()->setItems($arrt); // created a set item function in collection class for this module.