Search code examples
zend-frameworkzend-form-element

restrict the maximum number of selections in zend multiselect


hi i created a zend multiselect box with several options. here is the code.

$time = new Zend_Form_Element_Multiselect('time');
$time->setLabel('Select Your Notification Timings: ')
->setMultiOptions(
    array(
        '0' => "Select", 
        '00:00' => '00:00', '00:30' => '00:30', '01:00' => '01:00', '01:30' => '01:30', '02:00' => '02:00', '02:30' => '02:30',  
        '03:00' => '03:00', '03:30' => '03:30', '04:00' => '04:00', '04:30' => '04:30', '05:00' => '05:00', '05:30' => '05:30',   
        '06:00' => '06:00', '06:30' => '06:30', '07:00' => '07:00', '07:30' => '07:30', '08:00' => '08:00', '08:30' => '08:30',
        '09:00' => '09:00', '09:30' => '09:30', '10:00' => '10:00', '10:30' => '10:30', '11:00' => '11:00', '11:30' => '11:30', 
        '12:00' => '12:00', '12:30' => '12:30', '13:00' => '13:00', '13:30' => '13:30', '14:00' => '14:00', '14:30' => '14:30',
        '15:00' => '15:00', '15:30' => '15:30', '16:00' => '16:00', '16:30' => '16:30', '17:00' => '17:00', '17:30' => '17:30',
        '18:00' => '18:00', '18:30' => '18:30', '19:00' => '19:00', '19:30' => '19:30', '20:00' => '20:00', '20:30' => '20:30',
        '21:00' => '21:00', '21:30' => '21:30', '22:00' => '22:00', '22:30' => '22:30', '23:00' => '23:00', '23:30' => '23:30' 
    ))
->setRequired(TRUE)
->addValidator('NotEmpty', true, array('integer', 'zero'));
$maxSelections = array('min' => 3, 'max' => 4);
$selectValid = new Zend_Validate_Between($maxSelections);
$selectValid->setMessage("Number of selected values should be minimum of '%min%' or maximum of '%max%'");
$time->size = 12;     
$this->addElement($time);

Now i want to restrict the maximum number of selections to 4. The thing is i have to store the selected values in database. Currently if a user selects more than 4, let say 6, the database will only store the first 4 values. But i want to show that error message to the user that he selected more than 4 values. I tried Zend_Validate_Between($maxSelections) as shown above. But still i don't get any error message.

any help?


Solution

  • to get the error message use :

     $result = $selectValid->isValid($currently_selected_value);
        if($result){
             $selectValid->getMessages();
        }
    

    $result will contain false if $currently_selected_value (the value select in your multiselect box) is not in the specified range , in that case to get the error message.

    .