kartik-v / yii2-widgets

Collection of useful widgets for Yii Framework 2.0
http://demos.krajee.com/widgets
Other
558 stars 175 forks source link

FileInput UploadedFile::getInstances() always null #336

Closed raphaelM-sudo closed 7 years ago

raphaelM-sudo commented 7 years ago

Hi Kartik.

I am trying to implement an image upload functionality on form submit, using your FileInput widget, but UploadedFile::getInstances is always returning null inside the controller. I tried kartik\widgets\FileInput and kartik\file\FileInput, but it does not work both ways. The versions I am using are: yii2-widgets v3.4.0 and yii2-widget-fileinput v1.0.5. When I use the yii2 ActiveField fileInput it works.

I tried this basic example:

Model:

class CreateRecipeForm extends Model
{

    public $image;

    public function rules()
    {
            return
            [
                [['image'], 'safe'],
                [['image'], 'file', 'extensions'=>'jpg, gif, png, jpeg']
            ];
    }
}

View:

<?php $form = ActiveForm::begin([
        'id' => 'dynamic-form',
        'type'=>ActiveForm::TYPE_VERTICAL
]); ?>

<?= $form->field($model, 'image')->widget(FileInput::classname(), [
        'options' => ['accept' => 'image/*'],
]); ?>

<?php ActiveForm::end(); ?>

Controller:

public function actionCreate()
{

    $model = new CreateRecipeForm();

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

        $model->image = UploadedFile::getInstances($model, 'image');

        //image is always empty :(

        if ($model->create()) {
            return Yii::$app->getResponse()->redirect(Url::to('index'));
        }
    }

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

My actual model, view and controller is more complex, but it does not work with this simple one either. At first I tried multiple file upload and after I could not find the error, I was trying single file upload.

I hope you can help me, thanks in advance

kartik-v commented 7 years ago

Read this webtip for setting up and using FileInput widget.

Your form must have the enctype set for files to be read by your PHP server code:

$form = ActiveForm::begin([
    'options'=>['enctype'=>'multipart/form-data'] // important
]);

You may want to do some reading on generic HTML form settings for native file upload via PHP