Format of Json-Return from Controller

I want to fill a “datalist” input in my form and have this method in the controller:

    public function fetchDirections($term=null) {
        $this->autoRender=false;
        //$this->request->allowMethod('ajax');
        $this->request->allowMethod('get');
        $term = $this->request->getQuery('term');
        $directions = $this->fetchTable('Directions');
        $query=$directions->find()
            //->select(['Directions.id','Directions.name'])
            ->select(['Directions.name'])
            ->where(['Directions.name like'=>'%'.$term.'%','Directions.directiontype_id = '=>1, 'Directions.directionstate_id ='=>3])
            ->order(['Directions.name'=>'ASC'])
            ->limit(10);

        return $this
            ->response
            ->withType('application/json')
            ->withStringBody(json_encode($query,JSON_UNESCAPED_UNICODE));
        exit();
    }

The method returns value in this format:

XHRGET
http://192.168.178.39/recipes/Ajax/fetchDirections/d
[HTTP/1.1 200 OK 172ms]

	
0	Object { name: "Direction" }
name	"Direction"
1	Object { name: "Direction 1" }
name	"Direction 1"
2	Object { name: "Direction 2" }
name	"Direction 2"

I would like to have the return in this format:


XHRGET
https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/html-elements.json
[HTTP/1.1 200 OK 0ms]

	
0	"html"
1	"head"
2	"title"
3	"base"

How can I change the format of the return?

You might try Collection methods Collections - 5.x

$query = $directions->find()
            ->select(['Directions.name'])
            ->where([
                       'Directions.name LIKE' => '%'.$term.'%',
                       'Directions.directiontype_id' => 1, 
                       'Directions.directionstate_id' => 3
             ])
            ->orderBy(['Directions.name' => 'ASC'])
            ->limit(10)
            ->all()
            ->extract('name');

Thank you very much. This works for me.

1 Like