UploadedFile is null, but the name of image is given

Hi,

I have another problem. When I am as a User I want to upload image, the image will not be saved, because this line in the model is give me null:




UploadedFile::getInstance($this, 'image')



But the name of image is available…

This is the form input on the view:




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



My controller:




   /**

     * Modfiy user's data.

     *

     * @return mixed

     */

    public function actionUpdate()

    {

        $model = new AccountForm();

        // this var_dump returns with null.

        var_dump(\yii\web\UploadedFile::getInstance($model, 'image'));

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            Yii::info(sprintf('Account modified by user: %s.', Yii::$app->user->identity->username));

        }

        return $this->render('update', ['model' => $model]);

    }



and least my model’s part:




   public $image


   /**

     * @inheritdoc

     */

    public function rules() {

        return [

            [['image'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg']

        ];

    }


   /**

     * Save user own's profile

     *

     * @return boolean true if the save was successful

     */

    public function save() {

        // This var_dump give me the name of the image, so this is work

        var_dump($this->image);

        if (!$this->validate()) {

            return null;

        }

        // This gives me null value...

        var_dump(UploadedFile::getInstance($this, 'image'));

        $this->accountImageComponent->saveImage(UploadedFile::getInstance($this, 'image'));

        return $this->saveUserData();

    }



Somebody see my mistake?

You must check in the Yii debug bar, under Response, what parameters you have after you submit the form, in the section $_FILES

also you can check in your view if option form is set like:


$form = ActiveForm::begin([

        'options' => ['enctype' => 'multipart/form-data'],

    ]);

at the end I don’t use


UploadedFile::getInstance($this, 'image')

in the model but in the controllers like so:


        $upform = new AccountForm();

        $upform->image = UploadedFile::getInstance($upform, 'image');




            if (isset($upform->image)) {

                if ($upform->validate()) {


                    $newname = Yii::$app->security->generateRandomString(20);


                    $upform->image->saveAs(\Yii::$app->params['path.profile'] . $newname . '.' . $upform->image->extension);


                }

            }