0
votes

I am new to Yii. I am using this code



    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
    <?= $form->field($model, 'image')->fileInput(['type' => 'file']) ?>

    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

When i try to print post data in my controller then image field is going blank;
If i print through

 $_FILES 
then file data is showing.
Please let me know how to get image in post method.
2

2 Answers

2
votes

Step 1 : In your model file define one variable.

public $uploadedImage;

Step 2 : In your controller,

$model->uploadedImage = UploadedFile::getInstance($model, 'image');
$model->image = $model->uploadedImage->name;

After save() method write this to store image

$model->uploadedImage->saveAs('YOUR_WEBDIR_IMAGES_FOLDER/' . $model->uploadedImage->baseName . '.' . $model->uploadedImage->extension);

[If the above solution doesn't work then try this. :

Define another variable.

public $tempVarforImage;

In your controller

$model->tempVarforImage = $model->uploadedImage->name;
$model->image = $model->tempVarforImage;

(Because once I faced the issue in confliction of 'image' field from database and yii2 based 'image' variable)]

0
votes
  1. Create UploadForm model

    namespace app\models;
    use yii\base\Model;
    use yii\web\UploadedFile;
    class UploadForm extends Model{
        public $image;// Image name 
        public function rules()
        {
            return [
                [['image'], 'file'/* , 'skipOnEmpty' => false *//* , 'extensions' => 'png, jpg' */],
            ];
        }    
        public function upload($fileName)
        {
            if ($this->validate()) {
                $this->image->saveAs($fileName);
                return true;
            } else {
                return false;
            }
        }
    }
    
  2. Controller code Add at top of your file

    use app\models\UploadForm;
    use yii\web\UploadedFile;
    

    Add this in your function

    $model = User();
    if ($model->load(Yii::$app->request->post())) {
        $model1 = new UploadForm();
    
    
    $model1->image = UploadedFile::getInstance($model, 'image');
    
    $fileName  = $model1->image->baseName.'_'.time();
    $extension = $model1->image->extension;
    
    $fileName   =   $fileName.'.'.$extension;
    $filePath   =   WEBSITE_SLIDER_ROOT_PATH.$fileName;     
    if ($model1->upload($filePath)) {
        //Save in database
    }   
    
    }