File Upload Field Validation giving error during Update

Hi

I am using File Input option to upload a file in yii2 form using Active record. The file is Uploaded Successfully and I saved its corresponding path in DB.

When I open the form in update mode It is give Upload cannot be blank validation error.I checked the value of the attribute it has the reference path .

Has anyone faced this type of problem while updating a model with File Input without changing file Input attribute.

I am struggling with this problem from past 2 days please provide some suggestions to overcome this problem.

Thanks

1 Like

If i understand correctly you want to make the file required on create and not on update.

If this is correct you will need to use scenarios.




public function rules() {

    	return [

        	['filefield', 'required', 'message' => '{attribute} can\'t be blank', 'on'=>'create'],

        	['filefield', 'file', 'extensions' => ['pdf', 'doc', 'docx', 'txt'], 'maxSize' => 1024 * 1024 * 2, 'tooBig' => 'A resume can\'t be larger than 2 mb.', 'wrongExtension' => 'Only {extensions} types are allowed for {attribute}.'],

      	];

	}

notice on the required rule there is an on= create. "Create" is the scenario that the required should be applied to. The second rule would be applied for all scenarios and instances of the model since a specific scenario is not stated.

Note: you can name the scenarios whatever you like them to be named. You can also use as many as you like.

You need to specify your scenarios in your model (under the rules would be an ideal place). They need to have all of the attributes that need to be validated in them.


 public function scenarios() {

    	$scenarios = parent::scenarios();

    	$scenarios['create'] = ['filefield', 'someotherfield', 'anotherattribute'];

 		$scenarios['update'] = ['filefield', 'someotherfield'];

 		return $scenarios;

	}

To declare a scenario you have two ways; both would be when or right after you declare your model instance.

if it’s a new instance (i.e. create) you should call them like




$model = new SomeModel(['scenario' => 'create']);



The above wouldn’t work for an existing record so you can also declare a scenario like




$model = $this->findModel($id);

$model->scenario = 'update';


this also works for create 


$model = new SomeModel();

$model->scenario = 'create';



update:

Here is some more information about scenarios

Thanks Skworden

My problem is I want the File Input field to be required In all Scenario if it is empty .

If user don’t change the file in update mode it should use the old file .

I have defined the file Input field as required .

The problem is when I open it in Update mode and try to submit the form it raise the error file Input cannot be blank .

To do that you have to make it required only on create not update like i have above. So you will set a scenario like i said before. I will show you a controller action that can be refactored however, i didn’t want to show it refactored for learning purposes.

If you don’t know whats going on and you just end up copying and pasting code without knowing how it works.

So here you go




   public function actionUpdate($id) {

    	//find the model record to update

    	$model = $this->findModel($id);

    	//use a scenario to make fileFiled not requried

    	$model->scenario = 'updatefile';

    	//set the old file to a varable to use to check later

    	$oldfile = $model->filefield;

    	//check if user is trying to save and has set variables via post

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

          	//get the filefield field insatance; it could be empty so we will check for that next

   	       $newFile = UploadedFile::getInstance($model, 'filefield');

   	       //check if user has set a new filefield

        	if (isset($newFile)) {

            	//user set a new field assign it to a unique file name

            	$file = 'someUniquerFileName.' . $newFile->extension;

            	//set the attribute to the new uploaded file

            	$model->filefield = $file;

        	} else {

            	//the user didn't upload a new file so keep the old one

            	$model->filefield = $oldfile;

        	}

        	if ($model->save()) {

            	//if the model instance saved check if a new file was uploaded

            	if (isset($newFile)) {

                	//if a file was uploaded; remove the old file

                	unlink(Yii::$app->request->baseUrl . '/filepath/' . $oldfile);

                	//save new file to folder

                	$newFile->saveAs(Yii::$app->request->baseUrl . '/filepath/' . $file);

            	}

            	//send alert message telling user they have updated succefully.

            	\Yii::$app->getSession()->setFlash('success', 'You have successfully updated something!');

            	return $this->redirect(['toSomePage']);

        	} else {

            	//send alert message telling user there was an error.

            	\Yii::$app->getSession()->setFlash('danger', 'There was an error with your request. Please try adding updating  again. If this occures again please contact the site administrator!');

        	}

    	} else {

        	return $this->render('update', [

                    	'model' => $model,

        	]);

    	}

	}



Did you get this working?

Sorry for Late Reply I used the Model same Way you described but I am unable to understand why file upload is not working when I not validating it

add a rule like




 ['filefield', 'file', 'extensions' => ['pdf', 'doc', 'docx', 'txt'], 'maxSize' => 1024 * 1024 * 2, 'tooBig' => 'A resume can\'t be larger than 2 mb.', 'wrongExtension' => 'Only {extensions} types are allowed for {attribute}.'],



for update. I believe it needs to have some sort of rule. It doesn’t matter what rule; it just needs one for the update action. or the file won’t upload for whatever reason.

If that doesn’t work post your

whole model,upload and create controller actions

Thanks Skworden I was using Plugin to upload file ,I decided to remove plugin and use native yii 2 file upload and now scenarios are working

Thanks for help