I have a simple model based on CFormModel, as shown here.
<?php
class _UploadForm extends CFormModel
{
public $productname;
public $imagefilename;
public function rules()
{
return array(
array('productname', 'required'),
// array('imagefilename', 'required'),
);
}
}
?>
The view file displays a form with these two fields. In the model, the productname is required, and I want to keep imagefilename optional. Here is my view file:
<div class="form">
<BR>
<BR>
<?php if(Yii::app()->user->hasFlash('FileUploadSuccess')){ ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('FileUploadSuccess'); ?>
</div>
<?php } ?>
<?php if(Yii::app()->user->hasFlash('FileUploadError')){ ?>
<div class="flash-error">
<?php echo Yii::app()->user->getFlash('FileUploadError'); ?>
</div>
<?php } ?>
<?php echo CHtml::form('','post'); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'productname'); ?>
<?php echo CHtml::activeTextField($model,'productname',array('size'=>40,'maxlength'=>40)); ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'imagefilename'); ?>
<?php echo CHtml::activeTextField($model,'imagefilename',array('size'=>40,'maxlength'=>40)); ?>
</div>
<?php echo CHtml::submitButton('Submit'); ?>
<?php echo CHtml::endForm(); ?>
</div>
In the controller, I want to check if the user entered data in the imagefilename field. If yes, I want to use $model->imagefilename, otherwise I would use $model->productname (to be used as filename to save an uploaded file.) Here is my controller:
<?php
class _UploadController extends Controller {
public $defaultAction="upload" ;
public function actionUpload() {
$model=new _UploadForm;
if(isset($_POST['_UploadForm'])) {
$model->attributes=$_POST['_UploadForm'];
if($model->validate()) {
if(isset($model->imagefilename) && ($model->imagefilename) ){
$filenameforsavingfile = $model->imagefilename;
} else {
$filenameforsavingfile = $model->productname;
}
Yii::app()->user->setFlash('FileUploadSuccess',
$model->productname. ' file has been uploaded successfully to '
. $filenameforsavingfile );
} else {
// model could not be validated
$modelErrors = $model->getErrors();
foreach ($modelErrors as $arrayvalue) {
$errorlist .= implode(",", $arrayvalue);
}
Yii::app()->user->setFlash('FileUploadError',
'Validation Errors: '. $errorlist );
}
}
$this->render('_upload',array('model'=>$model));
}
}
?>
To my surprise, the controller always finds $model->imagefilename empty, therefore, $filenameforsavingfile always gets $model->productname, even when I enter data in the imagefilename field. However, if I make, imagefilename ‘required’ in the model, $filenameforsavingfile starts picking data from the imagefilename entered on the form. Am I not using Yii in the correct way? How can I make magefilename field optional and still get the data entered when entered by the user?
Thanks in advance.