V
V
vitaly_742021-05-08 18:09:38
Yii
vitaly_74, 2021-05-08 18:09:38

Is it possible in Yii2 to specify a JSON parser for a specific action/actions?

public function behaviors()
    {
        return [
            'verbs' => [
                'class' => \yii\filters\VerbFilter::className(),
                'actions' => [
                    'index'  => ['GET'],
                    'truck'   => ['POST', "DELETE"],
                    'polygon'   => ['POST', "DELETE"],
                    'marker'   => ['POST', "DELETE"],
                    'line-string'   => ['POST', "DELETE"],
                ],
            ],
        ];
    }

I would like to put the parser 'application/json' => 'yii\web\JsonParser' on all actions except for index.
Now in a specific action I do this:
Yii::$app->request->parsers = [
            'application/json' => 'yii\web\JsonParser'
        ];
        Yii::$app->response->format = Response::FORMAT_JSON;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Desh, 2021-05-20
@vitaly_74

public function behaviors()
 {
     return [
        [
             'class' => 'yii\filters\ContentNegotiator',
             'only' => ['view', 'index'],  // in a controller
             // if in a module, use the following IDs for user actions
             // 'only' => ['user/view', 'user/index']
             'formats' => [
                 'application/json' => Response::FORMAT_JSON,
             ],
             'languages' => [
                 'en',
                 'de',
             ],
         ],
     ];
 }

Class yii\filters\ContentNegotiator

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question