1

经典问题:

验证用户是否接受了合同条款,但接受的价值未存储(绑定)在数据库中......

  1. 扩展 CFormModel 而不是 CActiveForm(因为 CActiveForm 将值绑定到 DB)
  2. 将 CFormModel 发布到控制器操作
  3. 验证 CFormModel

我要求这个问题来回答它,因为现有问题以查看文档结尾......

4

1 回答 1

0

扩展 CFormModle,定义规则并进行验证。使用您在保存过程中验证的绑定变量。现在您 validate() 自己但 Validate 需要一个未在 CFormModel 中定义的属性列表。所以你会怎么做?你来做这件事:

$contract->validate($contract->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!
    }   

结果: 在此处输入图像描述 在此处输入图像描述

于 2014-10-02T18:35:50.783 回答