duan198727 2014-10-02 18:35
浏览 50

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

Classic problem:

verify that a user accepted the contract terms but the value of the acceptance is not stored (bound) in the database...

  1. Extend CFormModel rather than CActiveForm (because CActiveForm binds values to DB)
  2. Post a CFormModel to a controller action
  3. Validate a CFormModel

I'm asking this question to answer it because the existing questions end in see the documentation...

  • 写回答

1条回答 默认 最新

  • dongyi6845 2014-10-02 18:35
    关注

    extend CFormModle, define the rules and got to validate. With bound variables you validated as part of save. Now you validate() by itself but Validate requires a list of attributes which is not defined in CFormModel. So, what do you do? You do this:

    $contract->validate($contract->attributeNames())

    Here's the full example:

    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'
            );
        }
    }
    

    Then in the controller you do this:

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

    The results: enter image description hereenter image description here

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看