经典问题:
验证用户是否接受了合同条款,但接受的值未存储(绑定)在数据库中...
我问这个问题是为了回答这个问题,因为现有的问题最后会看到文档......
答案 0 :(得分:0)
扩展CFormModle,定义规则并进行验证。使用绑定变量,您将其验证为保存的一部分。现在您自己验证()但Validate需要一个未在CFormModel中定义的属性列表。所以你会怎么做?你这样做:
<强> $合约─&GT;验证($合约─&GT; attributeNames()) 强>
以下是完整示例:
class Contract extends CFormModel
{
...
public $agree = false;
...
public function rules()
{
return array(
array('agree', 'required', 'requiredValue' => 1, 'message' => 'You must accept term to use our service'),
);
}
public function attributeLabels()
{
return array(
'agree'=>' I accept the contract terms'
);
}
}
然后在控制器中执行此操作:
public function actionAgree(){
$contract = new Contract;
if(isset($_POST['Contract'])){
//$contract->attributes=$_POST['Contract']; //contract attributes not defined in CFormModel
...
$contract->agree = $_POST['Contract']['agree'];
...
}
if(!$contract->validate($contract->attributeNames())){
//re-render the form here and it will show up with validation errors marked!
}
结果: