Enforcing "You must agree" requirements in forms

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

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.

25 0
17 followers
Viewed: 33 765 times
Version: Unknown (update)
Category: How-tos
Written by: Steve Friedl
Last updated by: Steve Friedl
Created on: Jan 20, 2011
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles