Yii2 envelope single data in JSON response

1.2k views Asked by At

I went through offical guide and found a way to envelop JSON data like this.

use yii\rest\ActiveController;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];
}

This works perfect when I have a collection and then I have a response like this.

{
     products:....
}

But what I want to do is that i have a envelope for single data. For example if I do products/10 GET request to get.

{
    product:
}

Hope somebody figured it out.

2

There are 2 answers

0
Salem Ouerdani On

Single Data Envelope is not supported by \yii\rest\Serializer. At least until Yii 2.0.6 only collections get enveloped in order to add _links and _meta data objects to the response.

To envelope single data resource objects you'll need to override ActiveController's default view action within your Controller :

public function actions() 
{
    $actions = parent::actions();
    unset($actions['view']);
    return $actions;
}

public function actionView($id)
{
    $model = Product::findOne($id);
    return ['product' => $model];
}
0
diogo.abdalla On

Old, but I just bumped into here with the same problem.

And found a better (I think) solution: create your own serializer class extending \yii\rest\Serializer:

class Serializer extends \yii\rest\Serializer
{
  public $itemEnvelope;

  public function serializeModel($model)
  {
      $data = parent::serializeModel($model);
      if($this->itemEnvelope)return [$this->itemEnvelope=>$data];
      return $data;
  }
}

And then use it like this:

    public $serializer = [
    'class'              => '[your-namespace]\Serializer',
    'collectionEnvelope' => 'list',
    'itemEnvelope'       => 'item'
];