Validation rules for field file type

Hi, i am new working with yii, so i am working with forms. So i have a fileInput type field that allows me to upload images and i´m traying to find a validation rule that alllows me to leave empty the field because i want it to be an optional field to the user.
Because when we leave empty the field in gives me an error and it don´t send and save the information in the database.

Here is my model
public function rules()
{
return [
[[‘tipo’, ‘departamento’, ‘descripcion’, ‘estatus’], ‘required’],
[[‘tipo’], ‘string’, ‘max’ => 80],
[[‘departamento’, ‘descripcion’, ‘estatus’], ‘string’, ‘max’ => 250],
[[‘Imagen’], ‘file’, ‘extensions’=> ‘jpg,png,gif,jpeg’],

    ];
}

controller
if ($model->load(Yii::$app->request->post())) {
$model -> Imagen = UploadedFile::getInstance($model, ‘Imagen’);

        $image_name = $model->tipo.rand(1, 4000).'.'.$model->Imagen->extension;
        $image_path = 'uploads/'.$image_name;
        $model->Imagen->SaveAs($image_path);
        $model->Imagen = $image_path;
        $model->save(false);

        
        return $this->redirect(['view', 'id' => $model->id]);
        
}else{
    
    

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

Hi @EdgarBaeza13, welcome to the forum.

You can check the UploadedFile instance before saving. like this

$model->Imagen = UploadedFile::getInstance($model, 'Imagen');
if ($model->Imagen) {
    $image_name = $model->tipo . rand(1, 4000) . '.' . $model->Imagen->extension;
    $image_path = 'uploads/' . $image_name;
    $model->Imagen->saveAs($image_path);
    $model->Imagen = $image_path;
}
$model->save(false);
return $this->redirect(['view', 'id' => $model->id]);
1 Like

Thank you it works so well, great contribution

1 Like