Standard "update model" view with fileField

Hi

I got stuck at one problem. I have this standard "Update Model" view on which there is form _view.php which is used to create and save model data.

Now on this form when I create new model data, amongst many textFields I have one fileField which uploads file to database - yes I chose this approach instead of FS.

When using "Create Model" form, file is uploaded to database and the there is displayed view.php which uses zii.widgets.CDetailView and there is displayed link that I can click on and open this file from DB.

So far so good.

Anyway when I use “Edit Model” view to edit the data, for example if I just change any textField value but I don’t touch fileField I get message “fileField cannot be empty”.

What approach do I have to choose to get this working?

Any suggestions are welcome.

Assuming the file is a required field when you create an entry, you can use scenarios to provide different validation rules.


public function rules()

{

  return array(

    array('fileField', 'file', 'on' => 'insert'),

    array('fileField', 'file', 'allowEmpty' => true, 'on' => 'update')

}

‘insert’ and ‘update’ are standard scenarios that are automatically set by Yii. You can also use your own:


$model = new myModel('customScenario');

// or

$model->setScenario('customScenario');

I edited my model.php to this:




array('myFileField', 'file', 'allowEmpty'=>false, 'on' => 'insert'),

array('myFileField', 'file', 'allowEmpty'=>true, 'on' => 'update'),



and indeed now I can save updated model data without touching myFileField, but after data is saved file is erased from database since I haven’t chosen any in update form.

What I want to achieve is not to erase the file when I don’t choose any new file on update form and save it…

You can test if the file is empty and then use save with a list of attributes to be saved like:

$model->save(true,array(‘textField1’,‘textField2’));

Check the doc for save() - http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail

Ok thanks for example and link for doc. Yesterday late at night I had idea to do this:




$model->attribute_1 = $_POST['textField1'];

$model->attribute_2 = $_POST['textField2'];

...........

$model->last_attribute = $_POST['last_textField'];

$model->save();



And amongst all the attributes not to assign this fileField to model attribute.

But thanks again for this reference example, I think this is doing the same. But looks better.

Now to be a little tricky I wonder if I can remove from $_POST[‘Model_which_I_am_saving’] (which is an array) just this one fileField?

I am studying PHP array_slice() :rolleyes: