dev7
dev7

Reputation: 183

laravel populating typeahead

I am trying to populate typeahead with a list of data.

model:

 public function getClientNameAttribute() {
     return '{"clientID":"'.$this->id.'", "clientName": "'.$this->name.'"}';
 }

on running the following:

{!! $clients->lists('ClientName') !!}

I get this as my output :

["{\"clientID\":\"1\", \"clientName\": \"client 1\"}","{\"clientID\":\"2\", \"clientName\": \"client 2\"}"

It should be like this :

 [{"clientID": "1", "clientName": "client 1"}, {"clientID": "2", "clientName": "client 2"},

So I need to get rid of the slashes, and the double quotes around each record.

<script>
            $('#client').typeahead({
    source: function (query, process) {
        client = [];
        clientid = {};
        var data = {!!$clients->lists('ClientName')!!};
        $.each(data, function (i, state) {
            clientid[state.clientName] = state;
            client.push(state.clientName);
        });
        process(client);
    },
    matcher: function (item) {
        if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
            return true;
        }
    },
    sorter: function (items) {
        return items.sort();
    },
    highlighter: function (item) {
        var regex = new RegExp('(' + this.query + ')', 'gi');
        return item.replace(regex, "<strong>$1</strong>");
    },
    updater: function (item) {
        $('#clientID').val(clientid[item].clientID);
        return item;
    }
});
        </script>

Upvotes: 0

Views: 41

Answers (1)

Hieu Le
Hieu Le

Reputation: 8415

The ClientName attribute is double encoded. To get the JSON output correctly, you should modify your accessor to return the array object instead of an JSON-encoded string:

public function getClientNameAttribute() {
     return [
          "clientID" => $this->id, 
          "clientName" => $this->name,
     ];
}

Upvotes: 1

Related Questions