I am a newbee; started learning Yii recently.
I am trying to upload an image file selected by the user to the server. I want the user to choose a file and a filename to save the uploaded file with. I have specified the ‘required’ rule in model’s rule() but the form get submitted even when I leave the upload file and/or the filename empty. Here are my files:
Model: UploadForm.php
<?php
class UploadForm extends CFormModel
{
public $image;
public $uploadfilename;
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg,jpeg,gif,png', 'maxSize'=>30720),
array('image', 'required'),
array('uploadfilename','required'),
);
}
}
?>
Controller: UploadController.php
<?php
class UploadController extends Controller {
public $defaultAction="upload" ;
public function filters() {
return array(
'accessControl', // perform access control for CRUD operations
);
}
public function accessRules() {
/* Access Rules
* Based on user authentication: isGuest() !isGurst, isAdminUser() and isSuperUser()
**/
// ....
}
public function actionUpload() {
$model=new UploadForm;
if(isset($_POST['UploadForm'])) {
$model->attributes=$_POST['UploadForm'];
$uploadedImage = CUploadedFile::getInstance($model, 'image');
// Save Image file in a server folder
$uploadedImage->saveAs( $model->uploadfilename);
}
$this->render('upload',array('model'=>$model));
}
View file: Upload.php
<div class="form">
<?php echo CHtml::form('','post',array('enctype'=>'multipart/form-data')); ?>
<BR>
<BR>
<?php echo CHtml::activeLabel($model,'Product Image'); ?>
<?php echo CHtml::activeFileField($model, 'image'); ?>
<BR>
<div class="row">
<?php echo CHtml::activeLabel($model,'upload filename'); ?>
<?php echo CHtml::activeTextField($model,'uploadfilename'); ?>
</div>
<BR>
<?php echo CHtml::submitButton('Upload File Now'); ?>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
I would appreciate if someone could explain me why the model is not being validated() before being submitted. If I add $model->validated() in uploadAction, it returns me correct result. Do I need to call $model->validate() or the framework should automatically call it?