Question

I have created a custom Varien object collection for my admin module (because the data is not from a db) and have got it successfully to show in an admin grid. I built the collection by using the following code:

$collection = new Varien_Data_Collection();

Inside loop:

$object = new Varien_Object();
$object->setFileName($filename);
$collection->addItem($object);

It's all working perfectly except when I try to filter using the grid filtering system, it returns this error:

Fatal error: Call to undefined method Varien_Data_Collection::addFieldToFilter() in /data/www/vhosts/adammoss.co.uk/httpdocs/magento/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php on line 472

I know that addFieldToFilter() is only used on EAV objects, which my collection obviously has none of. My question is whether anybody knows of any way around this?

Can I append that method to my object in some way or would I have to create a model for this to work?

******UPDATE 08/02/2012 ******

OK, so I've slightly changed the way I do this. I'm still using my custom class which is an exact duplicate of Filesystem.php

My grid collection now looks like this:

protected function _prepareCollection()
{
    $collection = new MyNamespace_MyModule_Model_Csv_Collection();
    $collection->addTargetDir('my/target/path');
    $this->setCollection($collection);

    return parent::_prepareCollection();
}

It loads in all my Files into the grid as expected, and it now Paginates! However for some reason it still won't filter or sort, even though I'm literally just using the exact same class as Filesystem.php.

I'll check Mage_Backup class as you suggested.

Was it helpful?

Solution

The problem not in EAV based entities. Method addFieldToFilter() is available only in Varien_Data_Db_Collection, that EAV and standard ORM models extend. If you'd like to have your admin grid module working with your collection in the same way as it works with DB collection, you need to implement two methods:

  • addFieldToFilter($filterName, $conditionArray)
  • setSort($fieldName, $direction)

Example of such custom collection implementation you can find in Varien_Data_Collection_Filesystem class that utilizes FS based collections. This kind of collection, for instance, used in Mage_Backup module to show grid with backup files.

Sincerely, Ivan

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top