restyii2yii-rest

Yii2 rest return a custom value


I've a question about the RESTfull service of yii2.

in the cal view ( GET resource/{id} ) I want to return custom value that take the number of the current page for example host/resource?page=x (if it's set) , and it sum by one (x+1) untill the number is equal to the value of X-Pagination-Total-Count header.

So the response will be like this:

[
      {
        "id": 1,
        "username": "test",
        "email": "tset@email.it",
        "status": 10,
        "created_at": "2015-03-15 10:40:34"
      }
      {
        "id": 2,
        "username": "test1",
        "email": "tset1@email.it",
        "status": 10,
        "created_at": "2014-05-12 12:50:26"
      }
      .
      .
      .
     "custom_val" = x+1
]

Is possibile doing this? How can i set the return of this value? Thanks in advance for all the help.

edit: adding controller code

class UserController extends \yii\rest\ActiveController 
{

    // Model 'User'
    public $modelClass = 'api\modules\v1\models\User';

    /**
     * Behaviors
     * 
     * @return mixed
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['contentNegotiator']['formats']['application/json'] = \yii\web\Response::FORMAT_JSON;
        $behaviors['authenticator'] = [
            'class' => \yii\filters\auth\HttpBasicAuth::className(),
        ];


        return $behaviors;
    }

    /**
     * Actions
     * 
     * @return mixed
     */
    public function actions() 
    {

        $actions = parent::actions();


        unset($actions['delete'], $actions['create'], $actions['update']);

        $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];

        return $actions;

    }

    /**
     * Data Provider
     * 
     * @return  yii\data\ActiveDataProvider 
     */
    public function prepareDataProvider()
    {
        $data = User::find(); 

        $provider = new \yii\data\ActiveDataProvider([
            'query' => $data
        ]);

        return $provider;
    }

}

Solution

  • Try this:

    public function afterAction($action, $result){
    
        $result = parent::afterAction($action, $result);
    
        if($action->id == 'index') //check controller action ID
            $result['custom_val'] = 111;
    
        return $result;
    }