CActiveForm实际上是对Chtml类的封装,它与Chmtl不同的地方是CActiveForm提供了验证机制,
有三种:服务器端/客户端/ajax验证
表单:
<?php $form=$this->beginWidget('CActiveForm',
array(
'id'=>'contact_form',
'enableAjaxValidation'=>true//是否是ajax验证 //'enableClientValidation'=>true,//是否客户端验证 //'action'=>'site/contact', //'method'=>'get', )
); ?> <p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?> <?php echo $form->textField($model,'name');?> <?php //单独显示错误信息 echo $form->error($model,'name');
?> </div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?> <?php echo $form->textField($model,'email'); ?> <?php //单独显示错误信息 echo $form->error($model,'email');
?> </div>
<div class="row">
<?php echo $form->labelEx($model,'subject'); ?> <?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?> </div>
<div class="row">
<?php echo $form->labelEx($model,'body'); ?> <?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?> </div>
<?php $model -> name = 0;
echo $form->radioButtonList($model,'name',
array('1'=>'Male','0'=>'Female'),
array('separator'=>' ','labelOptions'=>array('class'=>''))
)
?> <div class="row">
<?php echo $form->labelEx($model,'label:'); ?> <?php $model ->name = array(1,2,3,4);//设定checkbox的默认值,其实应该在controller里面设定最好,radio,select的设定方法和这个一样 echo $form->checkBoxList($model,'name',
array('1'=>'Football','2'=>'Music','3'=>'Game','4'=>'basketball'),
array('separator'=>' ','labelOptions'=>array('class'=>'mylabel'))
)
?> </div>
<?php if(extension_loaded('gd')): ?> <div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?> <div>
<?php $this->widget('CCaptcha'); ?> <?php echo $form->textField($model,'verifyCode'); ?> </div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
</div>
<?php endif; ?> <div class="row submit">
<?php echo CHtml::submitButton('Submit');
?> </div>
//总体显示错误信息 <?php echo $form->errorSummary($model); ?> <?php $this->endWidget(); ?>
验证:
public function actionContact()
{
$model=new ContactForm;
//ajax validation if(isset($_POST['ajax']) && $_POST['ajax']==='contact_form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())//服务器端验证 {
$headers="From: {$model->email}\r\nReply-To: {$model->email}";
mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
谢谢关注!