开发者

Concatenate multiple fields to display in autocomplete using AJAX in cakephp

currently my autocomplete works in displaying the first name of the user, but I want to concatenate the first name, last name and etc. How do I achieve this in the following code?

<script type="text/javascript">
    $(function() {
        $(".suggest").autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: '<?php echo $this->Html->url(array('controller' => 'searches', 'action' => 'suggestUser')); ?>',
                    dataType: "json",
                    data: {
                        //request.term is the value of the current textbox.
                        term: request.term
                    },
                    success: function( data ) {
                        response( $.map( data, function( item ) {
                            return {
                                label: item.User.firstName,
                                value: item.User.firstName

                            }
                        }));
                    }
        开发者_StackOverflow        });
            },
            minLength : 1
        });
    });

In my controller, the following codes below is my logic to search for that field.

function suggestUser() {

        if (isset($_GET["term"])) {
            $term = $_GET["term"];

            $result = $this->User->find('all', array(
                'conditions' => array(
                    'User.firstName LIKE' => $term . '%'
                ),
                'fields' => array(
                    'firstName'
                )
                    ));
            if ($term) {
                $this->set('results', $result);
                $this->view = 'Json';
                $this->set('json', 'results');
            }
        }
    }


http://book.cakephp.org/view/1588/virtualFields


It is really simple I realised. I managed to resolve it.

  label: item.User.firstName + " " + item.User.lastName,
  value: item.User.firstName + " " + item.User.lastName

You also need to append the lastName field in.

'fields' => array(
                    'firstName',
                    'lastName',
                )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜