Yii2 form with several fields, including file upload

Problem: Can't save both image and text into DB. I have a database table named 'image'. It has 'bird_id', 'name' and 'filename' columns. The name of the file being uploaded will be stored in 'name'. I am trying to collect all this data via ActiveForm. In a Model file (TestTable.php):

public function rules()
{
    return [
        [['name', 'about'], 'required'],
        [['name', 'about'], 'string', 'max' => 256],
    [['about'],'file','extensions'=>['jpg']]
    ];
}

In View file (input.php):

<?php $form = ActiveForm::begin(['id'=>'input-form','options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'name') ?>
    <?= $form->field($model, 'about')->fileInput() ?>

    <div class="form-group">
        <?= Html::submitButton('Добавить', ['class' => 'btn btn-primary']) ?>
    </div>
<?php ActiveForm::end(); ?>

In controller file (TestTableController.php):

public function actionInput()
{
$model = new TestTable();
if(Yii::$app->request->isPost){
    $model->load(Yii::$app->request->post());
    $model->about = UploadedFile::getInstance($model,'about');
    if($model->save()){
        $model->about->saveAs('images/1.jpg');
    }
    return $this->redirect(['bird/index']);
}       
return $this->render('input',['model'=>$model]);
}

I tried multiple simple fields in the form, and everything worked! Collecting just image also worked!

Upvotes: 2

Views: 1480

Answers (1)

J&#248;rgen
J&#248;rgen

Reputation: 3567

Try to save the UploadedFile instance as non object variable

$image = UploadedFile::getInstance($model, 'about');

Then you can save the filename in your model object (I use random string in my project, but you can change that as you wish)

$ext = end(explode('.', $image->name));
$model->about = Yii::$app->security->generateRandomString().".{$ext}";

Now you can save the model in the database:

if($model->save()) {
    $image->saveAs('path/to/img/folder/'.$model->about);

This is how i do it, and that works great. Hopefully this will help your project aswell.

Upvotes: 1

Related Questions