Using activeFileField in my form, it outputs a hidden field which I assume is to be used when updating and the image is not changed. The problem here is that the value is always empty.
Also, if I put the following in the rules of my model I get an error:
array('image', 'file', 'types'=>'jpg, gif, png'),
The error:
Fatal error: Call to a member function getError() on a non-object in C:\wamp\www\yii\framework\validators\CFileValidator.php on line 146
Ok, I looked and see that the hidden field is just a fudge for something else. Why not make it useful, since I had to create another hidden field for "previous_image" when in update mode?
This is how I do it, if anybody else finds it useful (saving the file name to the database in my controller update action):
if($model->image=CUploadedFile::getInstance($model,'image')) {
$model->image->saveAs('/mypath/images/' . CUploadedFile::getInstance($model,'image')->name);
} else {
$model->image = $_POST['MyClass']['previous_image']; // from the hidden field
}
Unfortunately it is still not fixed in latest version of framework.
But it can be changed in core function
framework/web/helpers/CHtml.php
original code
public static function activeFileField($model,$attribute,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
// add a hidden field so that if a model only has a file field, we can
// still use isset($_POST[$modelClass]) to detect if the input is submitted
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
return self::hiddenField($htmlOptions['name'],'',$hiddenOptions)
. self::activeInputField('file',$model,$attribute,$htmlOptions);
}
new code
public static function activeFileField($model,$attribute,$htmlOptions=array(),$hiddenvalue='')
{
self::resolveNameID($model,$attribute,$htmlOptions);
// add a hidden field so that if a model only has a file field, we can
// still use isset($_POST[$modelClass]) to detect if the input is submitted
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
return self::hiddenField($htmlOptions['name'],$hiddenvalue,$hiddenOptions)
. self::activeInputField('file',$model,$attribute,$htmlOptions);
}