Answer the question
In order to leave comments, you need to log in
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,]);
}
}
...
...
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;
}
}
...
...
[['fullimg'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 1000],
...
<?=$form->field($model, 'fullimg[]')->widget(FileInput::classname(), [
...
]);?>
public function actionView($id)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; // формируем заголовок JSON
$user = \app\models\User::find($id); // инициализируем данные
return $user; // выводим в JSON формате
}
...
public function beforeSave($insert) {
... // здесь сделать запись в БД
return parent::beforeSave($insert);
}
...
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question