I will organize loading of pictures.

Model:

class Image extends \yii\db\ActiveRecord { public $files; public function rules() { return [ [[ 'id_actoutrs', 'id_category', 'id_pages', 'id_serial', 'id_user', 'for_home'], 'integer'], [['files'], 'file', 'extensions' => 'png, jpg'], [['title_alt', 'path', 'name'], 'string', 'max' => 255], ]; } 

Representation:

 <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> <?= $form->field($model, 'title_alt')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'files[]')->fileInput(['multiple' => true]) ?> <?= $form->field($model, 'for_home')->radioList([ '0' => Yii::t('app','NO'), '1' => Yii::t('app','YES') ]); ?> 

Controller:

 public function actionCreate() { $model = new Image(); $class=Yii::$app->request->get("class"); $feilds =Yii::$app->request->get("feilds"); $value=Yii::$app->request->get("value"); if ($model->load(Yii::$app->request->post())) { $model->files = UploadedFile::getInstances($model, 'files'); foreach ($model->files as $file) { $files_to = TransliteratorHelper::process($file->name, '', 'en'); $years=date('Y'); $mounts=date('m'); $path =0; switch ($class) { case 'category': $path = 'category'; break; } if (file_exists(Yii::getAlias('@frontend/web/').$path.'/'.$years.'/'.$mounts.'/')) { } else { mkdir(Yii::getAlias('@frontend/web/').$path.'/'.$years.'/'.$mounts.'/', 0775, true); } $file->saveAs(Yii::getAlias('@frontend/web/').$path.'/'.$years.'/'.$mounts.'/'.$files_to); $model->path=$path.'/'.$years.'/'.$mounts.'/'; $model->name = $files_to; $model->save(); } 

Debug shows this error:

20: 26: 09.879 info yii \ db \ ActiveRecord :: insert Model not inserted due to validation error. C: \ OpenServer \ domains \ film.lc \ backend \ controllers \ ImageController.php (98)

print_r( $model->getErrors()) gives the following error:

Array ([files] => Array ([0] => Download file.)) 1

What is the problem?

  • You carry out validation in the controller. It should be in the models: toster.ru/q/248500 - Urmuz Tagizade
  • @Urmuz Tagizade Is this a recommendation or a mandatory notation? It's just that there are no explanations for why validation fails. - Sergalas

2 answers 2

If the file is not loaded and, in principle, an optional download is implied, then try adding such an attribute:

 [['files'], 'file', 'extensions' => 'png, jpg','skipOnEmpty' => true ] 
  • download required - Sergalas
  • and secondly, the validation does not pass anyway - Sergalas
  • The documentation meant a separate model for downloading files, it inherits from Model, maybe this is the case. - StalkAlex
  • I already organized in the same model and nothing - Sergalas
  • Your advice was the most correct and choose. - Sergalas

Perhaps you should specify the 'extensions' parameter as an array:

 [['files'], 'file', 'extensions' => ['png', 'jpg']]