In the old days, I remember being extra lazy when it comes to requests for filter/search functions. I would be lazier if the conditions includes lots of fields.
Stumbling upon postConditions, this flipped what I felt about creating a filter function.
So here’s what we are going to try, we’ll create a filter function for messages as example. Let’s assume you have the table, model, controller and some CRUD done and working for messages.
Let us begin by creating the view first since we’re getting the filter conditions from the form. It’s this file: ‘app/views/messages/filter_messages.ctp’.
<h2>Filter Messages</h2> <?php echo $form->create('Message', array('action' => 'filter_messages')); echo $form->input('message'); echo $form->input('from'); echo $form->end('Submit Filter'); ?> <hr /> <h2>Filter Results: </h2> <?php //display apa kita jumpa kat sini foreach($messages as $message): echo $message['Message']['message'] ; echo "<hr />"; endforeach; ?>
Then add the filter function to the app/controllers/messages_controller.php.
function filter_messages() { //simple initialization for the variable that'll carry the result $messages = array(); //checks if we sent something to filter via the form (remember sent items go to $this->data) if($this->data) { /* * here comes postConditions * first parameter is the posted value, * * the second parameter (array('message' => 'LIKE')) * tells postCondition for the fields we're looking at and what type of * condition we want to use for that field item. So in this case, we want to use 'LIKE' for field 'message' * therefore the sql generated will look similar to "SELECT * FROM messages as Message WHERE Message.message LIKE '%whatever%' " * * the third parameter, will tell what is the boolean condition among each * condition we set for the find (you know like if we want 'message' is like 'b' AND the message came from 'dude') * * last and quite least (heh), if we set true, only the fields we set in the second parameter will be considered. * if false, any field in $this->data will be used. nifty huh. */ $conditions = $this->postConditions( $this->data, array('message' => 'LIKE'), 'OR', false ); //the usual find() function. $messages = $this->Message->find('all', array('conditions'=> $conditions)); } //sends result to the view. $this->set('messages', $messages); } ?>
That’s it!
An additional note: Controller::postConditions() doesn’t mean you have to use the data posted but you can also ready your own array in the usual $myarray['Model']['field1'] format and use that as parameter.
<?php $tobefiltered = array('Message' => ( array( 'message'=>'this is my message', 'created' => '2009-09-09 21:09:09', 'from' => '013xxxxxxxxxx' ) ); $condition_generated = $this->postConditions($tobefiltered); ?>


time kasih tuan umah.
lagi senang…sunggug DRY