Magento – How to Validate Checkbox in Magento

adminformform-validationformsvarien

In Form I have added code for checkbox as follows.

$fieldset->addField('title', 'checkboxes', array(
    'label'     => Mage::helper('custommodule')->__('Title'),
    'class'   => 'validate-one-required-by-name',
    'name'      => 'title[]',
    'values' => array(
        array('value'=>'aaa','label'=>'Checkbox1'),
        array('value'=>'bbb','label'=>'Checkbox2'),
        array('value'=>'ccc','label'=>'Checkbox3'),
    ),
    'onclick' => "",
    'onchange' => "",
    'disabled' => false,
    'tabindex' => 1
));

I got 3 checkbox field. If I dont choose any option and if then i click Submit. My form submitted. I want to add validation to these checkbox that one of the checkbox must select before submit.
As per This link. I have tried to add class validate-one-required for validation but it doesnt apply to checkbox. I want magento system to validate. Please help me anybody know. Thanks in advance.

Best Answer

So it appears there is a problem with how Varien_Data_Form_Element_Checkboxes works with classes.

When you look into the method _optionToHtml, which is where the options are built, you will see that it loops through all the html attributes and then performs a call to getDataUsingMethod. This function will, for class, end up calling $this->getClass($args) which returns null :(

But if you add the method getClass into the Varien_Dat_Form_Element_Checkboxes class then it will work.

public function getClass($args=null)
{
    return parent::getClass();
}

You can see that the checkboxes class already has this sort of thing for getDisabled, getOnClick which gets the value stored against the requested checkbox name.