Saturday, May 4, 2013

Bootstrap Typeahead CakePHP 2.0

Integrate Twitter Bootstrap Typeahead with your CakePHP 2.0 application.
You need:
- Cakephp 2.x
- Jquery
- Twitter bootstrap

First the form:
<input data-provide="typeahead" id="user-typeahead" type="text" />

Setting your url base
Put it into default.ctp before </head>
<script type="text/javascript">
  //get url base app
  var site_url='<?php echo $this->base; ?>';

</script>

The Jquery:
Put it into bottom in view

<script>  
$( document ).ready( function(){        
            $('#user-typeahead').typeahead({
                source: function (query, process) {
                    return $.ajax({
                        url: site_url+'/users/typeahead_search',
                        type: 'get',
                        data: {q: query},
                        dataType: 'json',
                        success: function (json) {
                            return process(json);
                        }
                    });
                }
            });  

 });                      
 </script>


UsersController
    public function typeahead_search() {
        $this->autoRender = false;
        $this->RequestHandler->respondAs('json');

        // get the search term from URL
        $term = $this->request->query['q'];
        $users = $this->User->find('all', array(
            'conditions' => array(
                'User.username LIKE' => '%' . $term . '%'
            )
                ));

        // Format the result for input
        $result = array();
        foreach ($users as $key => $user) {
            array_push($result, $user['User']['username']);
        }
        $users = $result;

        echo json_encode($users);
    }


This action will receive the request, search the database for relevant result and return it on JSON format.

No comments:

Post a Comment