Yii框架之使用表单form学习笔记
本文章来给大家总结一下关于Yii框架之使用表单form学习笔记,希望各位同学进入参考,如果有足的地方大家可在下方留言哦。
使用表单
在 Yii 中处理表单时,通常需要以下步骤:
1. 创建用于表现所要收集数据字段的模型类。
2. 创建一个控制器动作,响应表单提交。
3. 在视图脚本中创建与控制器动作相关的表单。
一、创建模型
在编写表单所需的 HTML 代码之前,我们应该先确定来自最终用户输入的数据的类型,以及这些数据应符合什么样的规则。模型类可用于记录这些信息。正如模型章节所定义的,模型是保存用户输入和验证这些输入的中心位置。
取决于使用用户所输入数据的方式,我们可以创建两种类型的模型。如果用户输入被收集、使用然后丢弃,我们应该创建一个表单模型; 如果用户的输入被收集后要保存到数据库,我们应使用一个Active Record。两种类型的模型共享同样的基类 CModel ,它定义了表单所需的通用接口。
1、定义模型类
例如创建为一个表单模型:
class LoginForm extends CFormModel { public $username; public $password; public $rememberMe=false; }
LoginForm 中定义了三个属性: $username, $password 和 $rememberMe。他们用于保存用户输入的用户名和密码,还有用户是否想记住他的登录的选项。由于 $rememberMe 有一个默认的值 false,相应的选项在初始化显示在登录表单中时将是未勾选状态。
我们将这些成员变量称为特性(attributes)而不是属性(properties),以区别于普通的属性(properties)。特性(attribute)是一个主要用于存储来自用户输入或数据库数据的属性(propertiy)。
2、声明验证规则
一旦用户提交了他的输入,模型被填充,我们就需要在使用前确保用户的输入是有效的。这是通过将用户的输入和一系列规则执行验证实现的。我们在 rules() 方法中指定这些验证规则,此方法应返回一个规则配置数组。
<?php class LoginForm extends CFormModel { public $username; public $password; public $rememberMe = false; private $_identity; public function rules() { return array( array( 'username, password', 'required' ) , //username 和 password 为必填项 array( 'rememberMe', 'boolean' ) , //rememberMe 应该是一个布尔值 array( 'password', 'authenticate' ) , //password 应被验证(authenticated) ); } public function authenticate($attribute, $params) { $this->_identity = new UserIdentity($this->username, $this->password); if (!$this->_identity->authenticate()) $this->addError('password', '错误的用户名或密码。'); } } ?>
rules() 返回的每个规则必须是以下格式:
array('AttributeList', 'Validator', 'on'=>'ScenarioList', ...附加选项)
其中:
AttributeList(特性列表)是需要通过此规则验证的特性列表字符串,每个特性名字由逗号分隔;
Validator(验证器) 指定要执行验证的种类;
on 参数是可选的,它指定此规则应被应用到的场景列表;
附加选项 是一个名值对数组,用于初始化相应验证器的属性值。
form表单更新数据时候选值问题
category表和post表是多对多,有个中间表relationships,分别记着category_id和post_id
Post.php model中 有关系
'cids'=>array(self::HAS_MANY,'Relationships','post_id'),
Category.php model中有方法:
static public function getAllCategory(){
return CHtml::listData(self::model()->findAll(), 'id', 'name');
}
比如现在我要更新一条数据,这条数据的栏目有两个,假设该文章id是21,是属于两个栏目,那么在relationship表中的数据就应该是
id post_id category_id
1 21 1
2 21 2
其中id是流水,该文章的category是1和2. 该栏目的数据我通过建立Relationship.php的AR能够获取,
_from中表单我是这么写的:
<div class='row'> <?php echo $form->labelEx($model, 'cid'); ?> <?php echo $form->checkBoxList($model, 'cid', Category::getAllCategory() , array( 'style' => 'display:inline;', 'separator' => "<br />n", 'template' => '{input}{label}', 'labelOptions' => array( 'style' => 'display:inline' ) )); ?> <?php echo $form->error($model, 'cid'); ?> </div>
问题是我在_form 中不知道要肿么将数据填进去?就是我在更新数据的时候,栏目应该选中才对。
对于view层数据的解耦,抛开checkBoxList,用dropDownList来说举个例子:
1=>分类1,2=>分类2,表现层(view)中可能是''=>请选择,1=>分类1,2=>分类2。通过此,你想到了什么?
关于Behavior是这样的,Behavior只是一种解决方案,稍后再说。目前你要明白的是,你如果要为Model提供一个属性(像cid[]),需要考虑哪几点?(提示:要与CActiveRecord接地气)
永久链接:http://www.phprm.com/frame/53045.html
转载随意!带上文章地址吧。