tags:

views:

531

answers:

2

I've got a scaffold built for CakePHP, but need to have a way for users to type in part of a surname into a text box, click a button and for the list of people to be filtered to a wildcard search.

I'm struggling for example code. Does anyone have some?

A: 

You need to look at the findby methods that CakePHP provides.

in addition to your standard findAll() you have a number of "magic" findby methods which allow you to specify a column in the table to search by:

$this->User->findBySurname($surname);

You also have findBySql(statement) which allows to you use a custom SQL statement. You could use this to execute a LIKE statement as follows:

$users = $this->User->findBySql("SELECT * FROM USERS u WHERE u.SURNAME LIKE '%" . $surname . "%' ORDERBY SURNAME");

That will return you a list of matching users which you can then display to the user. It's not the most efficient query, but it works.

Jon
-1 for sql injection waiting to happen. Will reverse vote if you fix it.
Dana the Sane
I think you've missed the point, I've said you "could" use a statement like the one above - not that this is the given solution. The code above is a point in the right direction using findBySql...
Jon
The point is broader than that, someone coming from a search engine is fairly likely to copy the code right into their application.
Dana the Sane
I think that's entirely an issue with the developer rather than the illustrated set of points I've outlined here... ho hum...
Jon
A: 

views/users/index.ctp

<fieldset>
    <legend>Filter users</legend>
    <?php
        echo $form->create('User', array('action' => 'index'));
        echo $form->input('surname', array('div' => false));
        echo $form->submit('Filter', array('div' => false));
        echo $form->end();
    ?>
</fieldset>

controllers/users_controller.php

public function index($surname = null) {
    // post-redirect-get 
    if ($this->data['User']['surname']) {
       $this->redirect(array('id' => $this->data['User']['surname']));
    }
    // conditions
    $conditions = null;
    if ($surname) {
        $conditions = array('surname LIKE' => '%' . $surname . '%');
    }
    // find
    $users = $this->Users->find('all', array('conditions' => $conditions));
    // set
    $this->set(compact('users'));
}
deizel