Yii Framework Forum: CheckBoxList rule - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

CheckBoxList rule Rate Topic: ***** 1 Votes

#1 User is offline   evoup 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 23
  • Joined: 14-July 10

Posted 14 July 2010 - 12:53 PM

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?
0

#2 User is offline   whoopass 

  • Advanced Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 119
  • Joined: 27-May 09
  • Location:Ajax, Ontario, Canada

Posted 14 July 2010 - 03:04 PM

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):

<?php

public function beforeValidate()
{
     // call the function here
     $result = checkCheckBoxList();
     
     // evaluate result
     if($result)
            return true;
     else
            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 :)
1

#3 User is offline   evoup 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 23
  • Joined: 14-July 10

Posted 14 July 2010 - 09:35 PM

good´╝îi done it~ :lol:
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users