Take the 2-minute tour ×

I'm working with CakePHP v2.3.x and on an edit page I need to dynamically update the page with search results...

I'm making an AJAX call from one of my Views/Tests/admin_edit.php view page to a specific action in my QuestionsController.php.

Here's the action (so far) that handles the request:

public function admin_search() {
        $searchdata = $this->request->data;
        $r = $this->Question->find('all', array('conditions' => array('Question.id' => $searchdata['id'])));
        echo json_encode($r);


It currently only returns questions whose IDs match the one entered by the user, but the finished version will search several different fields. I know how to do this by adding additional key/value pairs to the conditions array. However, I don't know how to make those fields optional. What if the user enters the question name, but NOT the id, or visa versa? Is there a configuration so that CakePHP will ignore any empty field conditions?

Similarly, is there a way to set the operator so that, for example, I could match substrings or integer ranges? Update: I found this in the docs.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

I would just remove any empty entries yourself first.

So let's say you have a $searchdata array with three optional fields, one of which is blank. First build your conditions array:

$searchdata = array("id" => 1, "name" => "", "type" => "foo");
$conditions = array('Question.id' => $searchdata['id'], 'Question.name' => $searchdata['name'], "Question.type" => $searchdata['type']);

(Or if you want to get fancy)

foreach($searchdata AS $key => $value) $conditions['Question.' . $key] = $value;

Now clean up $conditions, get rid of empty values:

$conditions = array_filter($conditions);



See http://3v4l.org/JN6PA

share|improve this answer
I dig it. That looks really clean. –  SDP Apr 11 '13 at 14:40
add comment

Your Answer


