Cakephp 1.2 Filter Component

Making forms and filtering data is a very common task in every day work for most webdevelopers. Usually I was making some combination of a model and controller methods to be able to achive this task. It’s a lot of code and a lot of work. I started looking for a component which will make some work for me. Most interesting I found was a code provided by Mr Nik Chankov at his blog and it was a foundation for my work.
You can find oryginal filter component under this address.

What are the differences between my component and this provided by Nik Chankov?
Where is one importent. I don’t like to keep filter data in the session. Instead of this, my component provide methods that allowes you to filter your data using form, but to rember filter data in url’s generated by paginator helper.

Let’s start.
First, download the code from here and save it in your component folder as filter.php.

Next, add it to you controller like this:

var $components = array(...,'Filter',...);

In a controller action where you use your paginate method put this:

$filter = $this->Filter->process($this);
$this->set('url',$this->Filter->url);
$this->set('courses', $this->paginate(null,$filter));

And thats everything you have to do in a controller! There’s also additional parameter for Filter->process(). As a second parameter you can add an array of allowed attributes. For example, if you put

$this->Filter->process($this, array('id','fname','lname'))

and somebody will try to change or add some stuff in an url, that  data wan’t be used in the process of filter generation. Only ‘id’, ‘fname’ and ‘lname’ will count.
Let’s go forward to the view. As you can see I have set an url variable.

$this->set('url',$this->Filter->url);

It’s used in the paginator helper to “remember” filters instead of using Session. Just add this variable to $option array as you can see below.


echo $paginate->sort('Id','id', array('url'=>array($url)));?>

echo $paginator->numbers(array('url'=>array($url)));

Now, all you have to do is building a form, for example sth like this:


<?php echo $form->create('Videos',array('url'=>array('action'=>'index'))) ?>
<?php echo $form->input('fname') ?>
<?php echo $form->input('lname') ?>
<?php echo $form->input('Distributor.name') ?>
<?php echo $form->end('Search'); ?>

Importent feature is that you can also search data used in other models to which our model belongs to (here for example Distributor).

Tags: ,