Yii验证未绑定的变量(未存储)

时间:2014-10-02 18:35:51

标签: php data-binding yii gii

经典问题:

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

  1. 扩展CFormModel而不是CActiveForm(因为CActiveForm绑定 值到DB)
  2. 将CFormModel发布到控制器操作
  3. 验证CFormModel
  4. 我问这个问题是为了回答这个问题,因为现有的问题最后会看到文档......

1 个答案:

答案 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!
    }   

结果: enter image description here enter image description here