Home > database >  REST controller based on yii\rest\ActiveController does not accept any input data when trying to m
REST controller based on yii\rest\ActiveController does not accept any input data when trying to m

Time:06-06

tl;dr My Yii 2 app responds correctly to REST requests for fetching data (i.e. GET, but fails completely when I am trying to create some record (i.e. use POST HTTP verb or similar). What can be wrong?


I have enter image description here

What am I missing?

CodePudding user response:

The issue in this case is not in parsing JSON body but rather in loading data into model.

The yii\rest\CreateAction uses Model::load() method to load data into attributes. But load() method only loads data into attributes that are considered "safe".

As "safe" are considered attributes that are returned in attributes list for current scenario by Model::scenarios() method. As stated in documentation for scenarios() method:

The default implementation of this method will return all scenarios found in the rules() declaration.

So, if there are no validation rules in model, no attribute will be considered safe. Therefore, no attribute will be loaded.

There are two options how to make model load your data. You can override scenarios() method to return list of your attributes for scenario default.

public function scenarios(): array
{
    return [
        \yii\base\Model::SCENARIO_DEFAULT => ['your', 'attributes', ...],
        //or you can also use attributes() method here
        //\yii\base\Model::SCENARIO_DEFAULT => $this->attributes(),
    ];
}

Or, you can set proper validation rules in rules() method. Because you are dealing with user inputs, setting proper validation rules is probably better idea.

  • Related