D
D
Daniil Sidorov2020-09-20 12:52:55
Yii
Daniil Sidorov, 2020-09-20 12:52:55

How to work with json fields in yii2?

I recently found out that Yii2 has support for Json fields, so I decided to rewrite the old code, but ran into difficulties.

When receiving information, there are no problems, you do not need to decode the field yourself, the value comes already in the form of an array. But there is a problem when trying to change the values.

The value is not displayed correctly in the form. "Array" is displayed

<?= $form->field($model, 'meta')->textInput(['maxlength' => true]) ?>

Well, everything seems to be clear here. Just before submitting the model to the form, you need to do json_encode and pass the string:
$model->meta = json_encode($model->meta);

But how now to save the value when submitting the form? I open the form, edit the Json value of the field, which is written as a string, and save it. In the post, a model arrives with a modified Json string, everything is ok.
Here's what comes in the post

Array
(
    [_csrf] => VmUwDTNtfnkj2HqHmZJyxfaKMTC_IFElEnXlXuJloTcOKmVXUQQxNk2HLb7TxCChhflVZdUUBVJjRI4auDPqDg==
    [Sale] => Array
        (
            ...
            [meta] => {<b>"sub_CHANGED":3</b>,"icon":"fal fa-gift","text":"-70%","price":1650,"oldPrice":5500}
            ...
        )

)


But when the model is loaded, $model->load(Yii::$app->request->post()there is no change in the data.
loaded model

app\models\Sale Object
(
    [_attributes:yii\db\BaseActiveRecord:private] => Array
        (
            ...
            [meta] => {<b>"sub":3</b>,"icon":"fal fa-gift","text":"-70%","price":1650,"oldPrice":5500}
            ...
        )


There is a suspicion that something is wrong with the validation, but I don’t know what. What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-09-20
@DaniLaFokc

After reading from the database, we decode
Before saving to the database, we encode
Work with the form: https://github.com/Myks92/vmc-event/tree/master/sr...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question