K
K
karina_eax2017-01-30 22:15:16
Yii
karina_eax, 2017-01-30 22:15:16

Yii2 REST: How to correctly process a post request that passes a json collection?

I apologize in advance if the questions are too stupid, but everyone started somewhere.
I need to get data from a post request, which is passed as a json collection.
The collection looks like this:

[{ "title":"test1", "description":"test1", "date":"17.01.12 11:11:11" },  {"title":"test2", "description":"test2", "date":"17.01.12 22:22:22" }]

Next, this data must be written to the database. How to load data into the model? As I understand it, nothing will come of the usual load?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tkutru, 2017-01-31
@karina_eax

Get post data, decode it into an array, traverse the array and load the data into the model and save it. Let's say you pass data in the post parameter arr and your model is called Model

$data = json_decode(\Yii::$app->request->post('arr'), true);
foreach ($data as $chunk) {
    $model = new Model();
    $model->attributes = $chunk;
    $model->save();
}

In order for the model to be saved correctly in the database, its properties must satisfy its validation rules (see the rules method in the model class). If it is not saved in the database, you can check for errors, for example, instead of the usual saving, write
if (!$model->save()) {
    var_dump(['erorrs' => $model->errors]);
}

Errors are displayed in STDOUT just for the sake of clarity of the example, in general, of course, it is better not to display them immediately, but to log somewhere or format the response to the requester in a normal api.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question