1 创建 Form 表单
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form', //标志id
'enableAjaxValidation'=>true, //是否开启ajax验证
'enableClientValidation'=>true, //是否开启客户端验证
'focus'=>array($model,'firstName'), //焦点聚焦位置
)); ?>
<?php echo $form->errorSummary($model); ?> //错误汇总
<div class="row">
<?php echo $form->labelEx($model,'firstName'); ?> //标签
<?php echo $form->textField($model,'firstName'); ?> //文本域
<?php echo $form->error($model,'firstName'); ?> //错误提示
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastName'); ?>
<?php echo $form->textField($model,'lastName'); ?>
<?php echo $form->error($model,'lastName'); ?>
</div>
<?php $this->endWidget(); ?>
2 处理表单
public function actionCreate()
{
$model=new User;
$this->performAjaxValidation($model); //如果开启了ajaxValidation
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
if($model->save())
$this->redirect('index');
}
$this->render('create',array('model'=>$model));
}
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
3 常见的表单域
a 文本输入框
public string textField(CModel $model, string $attribute, array $htmlOptions=array ( ))
b checkbox
|
public string
checkBox(
CModel $model, string $attribute, array $htmlOptions=array ( ))
|
public string checkBoxList(CModel $model, string $attribute, array $data//标签, array $htmlOptions=array ( ))
c 下拉菜单
public string dropDownList(CModel $model, string $attribute, array $data, array $htmlOptions=array ( ))
d 隐藏域
public string hiddenField(CModel $model, string $attribute, array $htmlOptions=array ( ))
e label 标签
public string labelEx(CModel $model, string $attribute, array $htmlOptions=array ( )) //自动的提取model中各个字段的label
f 单选框
public string radioButton(CModel $model, string $attribute, array $htmlOptions=array ( ))
一组单选框
public string radioButtonList(CModel $model, string $attribute, array $data, array $htmlOptions=array ( ))
g textarea
public string textArea(CModel $model, string $attribute, array $htmlOptions=array ( ))
Yii框架表单创建与处理
本文介绍如何使用Yii框架创建表单并处理用户输入。包括表单元素如文本框、复选框等的实现方法,以及表单验证和提交处理的流程。还介绍了如何通过ajax进行实时验证。

5251

被折叠的 条评论
为什么被折叠?



