CActiveForm實(shí)際上是對(duì)Chtml類的封裝,它與Chmtl不同的地方是CActiveForm提供了驗(yàn)證機(jī)制,,有三種: 服務(wù)器端/客戶端/ajax驗(yàn)證 基本表單: <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'contact_form', 'enableAjaxValidation'=>true//是否是ajax驗(yàn)證 //'enableClientValidation'=>true,//是否客戶端驗(yàn)證 //'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 //單獨(dú)顯示錯(cuò)誤信息 echo $form->error($model,'name'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'email'); ?> <?php echo $form->textField($model,'email'); ?> <?php //單獨(dú)顯示錯(cuò)誤信息 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);//設(shè)定checkbox的默認(rèn)值,其實(shí)應(yīng)該在controller里面設(shè)定最好,radio,select的設(shè)定方法和這個(gè)一樣 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> //總體顯示錯(cuò)誤信息 <?php echo $form->errorSummary($model); ?> <?php $this->endWidget(); ?> 1、如果開啟ajax驗(yàn)證在controller端實(shí)現(xiàn)代碼: 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())//服務(wù)器端驗(yàn)證 { $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)); }
|