I
I
Igor Vasiliev2019-05-12 00:05:53
Yii
Igor Vasiliev, 2019-05-12 00:05:53

Yii2, how to make a record in JSON format in the database?

Hello.
--
I used this plugin - demos.krajee.com/widget-details/fileinput
Here is the write action in the controller:

...
    public function actionCreate()
    {
        $model = new Catalog();
        $model->link = 'obj'.Scripts::getNameFile(); 
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->fullimg = UploadedFile::getInstances($model, 'fullimg');
            $model->upload();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', ['model' => $model,]);
        }
    }
...

Here is a function in the model that successfully uploads images to the right place:
...
    public function upload()
    {
        $dir = 'file/' .$this->id. '/';
        UploadFile::createFolder($dir);
        if ($this->save()) { // validate
            $index = 1;
            foreach ($this->fullimg as $file) {
                $file->saveAs($dir . self::nameFile().preg_replace('/\s+/', '', $file->baseName) .$index++. '.' . $file->extension);
            }
            return true;
        } else {
            return false;
        }
    }
...

When writing, it gives an error that the `fullimg` field does not have a default value, I added, it did not help.
The rule is the following:
...
[['fullimg'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 1000],
...

even if I turn off validation, it doesn't help, it says that it can't check the data. For this reason, I tried `$this->save()` instead of `$this->validate()` - I didn't see any difference, or I just didn't notice it while fiddling around.
The field accepts an array, not a string:
<?=$form->field($model, 'fullimg[]')->widget(FileInput::classname(), [
...
]);?>

Naturally, `Array` is written to the database because somewhere you need to get data and format it in json format.
For those who are interested, it's done like this:
public function actionView($id)
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; // формируем заголовок JSON
    $user = \app\models\User::find($id);  // инициализируем данные
    return $user; // выводим в JSON формате
}

Already tested, proven, working.
There is an idea to write through a special function:
...
public function beforeSave($insert) {
        ... // здесь сделать запись в БД 
        return parent::beforeSave($insert);
}
...

Actually the question is how to write data by default if `fullimg` is empty?
- Rule with `default` did not help.
How to intercept the data and write it as a json file to the database?
Maybe someone did, faced with this? Tell me, I don't see any solutions yet. What did I miss?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question