Yii 1.1: Enforcing "You must agree" requirements in forms

17 followers

Checkboxes have two possible values, true and false, but some applications require that the user select one particular value before proceeding. Examples might be:

  • I agree to the terms and conditions
  • I agree not to ship these goods into a terrorist country
  • I agree that Yii is the best MVC framework ever
  • I am over 18 years of age

In this case, the checkbox (implemented in the usual way in a form) warrants a validator that enforces this condition, and it can be done with the built-in compare validator along with a custom message:

Here, the model's iagree attribute (which could be named anything as your database or form dictate) can be attached to a form, and validation will be applied to it:

class SomeModel extends CActiveRecord {
    ...
    public function rules()
    {
        array('iagree', 'compare', 'compareValue' => true, 
              'message' => 'You must agree to the terms and conditions' ),
        ...
    }
    ...
}

Be sure to change the message to more precisely reflect what the user is agreeing to, as well as to provide an error label in the form.

Total 3 comments

#14284 report it
CoderK at 2013/08/01 05:17pm
perfect

Thanks for this! Helped a lot

#13085 report it
mem at 2013/05/03 06:32am
Require will NOT work

In case anyone's wonder, as much as I did, using 'required' will NOT make this work:

array('iagree', 'required', 'message'=>'You must agree with terms')

So use compare as stated by the OP and you should be good to go. :)

#12758 report it
rajesh chaurasia at 2013/04/10 07:07am
TOS

hi friends for using terms of service you can write in your model first public $tos; //define variable

than in rules you can write array( 'tos', 'compare', 'on'=>'register', 'compareValue' => true, 'message' => 'You must agree to the terms and conditions' ),

and in attribute level you can set 'tos' => 'I have read and agree to the following Terms of Use',

and in your view you can write

<?php echo $form->checkBoxRow($user, 'tos'); ?>

it will help you.

Leave a comment

Please to leave your comment.