How can I use a wildcard search to get a list from scaffolding in a CakePHP?

后端 未结 2 1293
被撕碎了的回忆
被撕碎了的回忆 2021-01-26 15:19

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 t

相关标签:
2条回答
  • 2021-01-26 15:34

    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.

    0 讨论(0)
  • 2021-01-26 15:48

    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'));
    }
    
    0 讨论(0)
提交回复
热议问题