Crusader
Crusader

Reputation: 1200

How to return JsonModel by default in ZF2?

Default ViewModel is not mandatory, I can return from controller just the array of data:

public function someAction()
{
  //...
  return array('result'=>$data);
}

But I can`t use this approach with Json. What should I do in dispatch event to wrap the results in JsonModel (for the appropriate accept header)?

Upvotes: 1

Views: 3415

Answers (4)

Nemutaisama
Nemutaisama

Reputation: 611

Just create Base Controller for all your API controllers, and replace model in MvcEvent.

class JsonRestController extends AbstractRestfulController
{

    public function onDispatch(MvcEvent $e)
    {
        $e->setViewModel(new JsonModel());
        return parent::onDispatch($e);
    }
}

Upvotes: 3

Neftalí Yagua
Neftalí Yagua

Reputation: 639

Is really simple

Add as follows:

IndexController.php

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel; // Add this line

class IndexController extends AbstractActionController {

    public function indexAction() {
        // some index action
        return new ViewModel();
    }

    public function apiAction() {

        $person = array(
            'first_name' => 'John',
            'last_name' => 'Downe',
        );
        // Special attention to the next line
        return new JsonModel(array(
            'data' => $person,
        ));
    }

}

api.phtml

<?php echo $this->json($this->data); ?>

Result:

{"first_name":"John","last_name":"Downe"}

Upvotes: 0

Ender Akg&#252;l
Ender Akg&#252;l

Reputation: 62

to get json data from controller you can echo json encoded data and exit. I use that for jquery ajax. i hope this is what you are looking for.

public function testAction()
{
    $active = "some data";
    echo json_encode(array('result' => $active));
    exit();
}

then at jquery you can get this data like that

$.ajax({
              type: 'GET',
              url: '/index/time',
              dataType: 'json',
              error: function() {
                 $('#info').html('<p>Error on time calculation</p>');
              },
              success: function(data) {
                  data.result
              }
 });

Upvotes: 1

itrascastro
itrascastro

Reputation: 785

You have to add a ViewJsonStrategy strategy to the view manager under your module.config.php:

'view_manager' => array(
    'template_map'              => array(
    ),
    'template_path_stack'       => array(
        __DIR__ . '/../view',
    ),
    'strategies'                => array(
        'ViewJsonStrategy',
    ),
), 

Then you can return a JsonModel in your action:

public function myAction()
{
    $data = [1, 2, 3, 4];

    return new JsonModel([
        'data' => $data
    ]);
}

Upvotes: 3

Related Questions