I have problem with upload file. I use kartik-v/yii2-widget-fileinput extension. Here my code:
form model rule
/**
* @inheritdoc
*/
public function rules()
{
return [
[['image'], 'required', 'on' => static::SCENARIO_CREATE],
[['image'], 'file', 'extensions' => 'png, jpg, jpeg', 'maxSize' => 1024 * 1024],
];
}
form view
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
'options' => ['enctype' => 'multipart/form-data']
]); ?>
<?= $form->field($model, 'image')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
'pluginOptions' => [
'showPreview' => false,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false,
'showCancel' => false
],
]); ?>
controller action
public function actionCreate()
{
$model = new ItemForm();
$model->scenario = ItemForm::SCENARIO_CREATE;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
$randomString = Yii::$app->getSecurity()->generateRandomString(10);
$name = Inflector::slug($model->title) . '_' . $randomString . '.' . $image->extension;
$url = Image::URL . $name;
$model->image = $name;
if ($model->save()) {
$image->saveAs($url);
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Always when I submit form, I got error "image field is required". I have read many tutorials but still I have the same problem when I using ajax validation. Can anyone look at it and tell me what I'm doing wrong?