when a form has file input, it requires a file to be uploaded

Hello…

I have a form that places a file input that is optional. The problem is that after I press submit button, file input field is validated to be required, when it is not.

This is the rules for the model:




	public function rules()

	{

		return array(

			array('titulo','length','max'=>100),

			array('mnu_id, titulo, texto', 'required'),

			array('mnu_id, publicado, orden', 'numerical', 'integerOnly'=>true),

			array('foto','length','max'=>100),

			array('foto', 'file', 'types'=>'jpg, gif, png'),

		);

	}



"foto" is the file field that is optional.

I created a public variable called $foto in the model. When I choose a file, all works perfect, but when I don’t select a file, forms validation raises an error.

The form is created with:




<?php echo EHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>



And here is how I create the file field:




<div class="simple">

<?php echo EHtml::activeLabelEx($model,'foto'); ?>

<?php echo EHtml::activeFileField($model, 'foto', array('class'=>'boton', 'size'=>50)); ?>

</div>



Any help will be greatly appreciated

Thanks

Jaime

Hi Jaime,

to tell the file validator the field is optional, theres a special property called "allowEmpty" accepting a boolean value.

So just replace your file validation rule with this one:


array('foto', 'file', 'types'=>'jpg, gif, png', 'allowEmpty'=>true),

and you should be set. :)

Hope that helps,

Steffen

Tnank you! it worked :rolleyes: