CheckBoxList rule

hi , i use follow code to create a checkboxlist

<?php echo CHtml::CheckBoxList(‘position[]’,null,array(0=>‘position1’,1=>‘position2’,2=>‘position3’));


now i want to let at least one box select, how should i write the rule?

There is no specific rule to see if any check boxes are selected. That’s the beauty to check boxes, they can be selected or not and not just limited to just 1 item.

So what you’ll have to do is, 2 choices:

If you plan to use this type of feature often, make an extension by creating a component that will contain your own custom validation rules. If you just plan to use it this once, create the function within the model of the AR / Form you’re using the check boxes with (the easier solution). Then use the beforeValidate() function to call your custom rule that checks to see if any check boxes are selected or not, and if they aren’t, return the function false so that way it doesn’t process the validation.

Example (using for a model):


public function beforeValidate()


     // call the function here

     $result = checkCheckBoxList();


     // evaluate result


            return true;


            return false;


public function checkCheckBoxList()


     // iterate through the variable array holding your checkboxlist

     foreach($variable1 as $variable2)


            // check the properties or values of the $variable2

            // if at-least 1 is "checked" return true, else if it iterates through and finds nothing, return false.



The other way is through a component, but the code would look more hefty and you wouldn’t have it on beforeValidate you’d actually have the component do all the work, extending the CValidator class and then using it like a normal rule, where the iteration logic is inside the component.

Hope that helps :)

good,i done it~ :lol: