1

Hi i have to create some multiselect element in zend with same options. i.e.

$B1 = new Zend_Form_Element_Multiselect('Rating');
$B1->setLabel('B1Rating')
          ->setMultiOptions(
              array(
                  'NULL' => "Select", 
                  '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5'))
          ->setRequired(TRUE)
          ->addValidator('NotEmpty', true);
    $B1->setValue(array('NULL'));
    $B1->size = 5;    
    $this->addElement($B1);

Now i have to create 5 elements of same type but different labels. So i don't want to copy the whole code 5 times. So is there any way i can do so without copy-pasting the code for 5 times.

3 Answers 3

2

About three different ways spring to mind. Here's the simplest one

$B2 = clone $B1;
$B2->setLabel('B2Rating');
Sign up to request clarification or add additional context in comments.

2 Comments

see docu and look at the comments.
Hey thanks. Actually while looking at the shallow or deep cloning perspective i also found that we could use something like $form = new Zend_Form_Element_Multiselect(); ...... $new_form = $form->deepclone();
2

Another approach:

$options = array(
    'required'     => true,
    'validators'   => array('NotEmpty'),
    'value'        => null,
    'size'         => 5,
    'multiOptions' => array(
              'NULL' => "Select", 
              '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5'),
);

$B1 = new Zend_Form_Element_Multiselect('Rating', $options);
$B1->setLabel('B1Rating')
$this->addElement($B1);

$B2 = new Zend_Form_Element_Multiselect('Rating2', $options);
$B2->setLabel('B2Rating')
$this->addElement($B1);

And so on...

Comments

2

Because there's never a limit on the amount of ways you can accomplish a certain goal, here's another solution:

$ratingLabels = array('Rating 1', 'Rating 2', 'Rating 3');

foreach($ratingLabels as $index => $ratingLabel) {
    $this->addElement('multiselect', 'rating' . (++$index), array(
        'required' => true,
        'label' => $ratingLabel,
        'value' => 'NULL',
        'size' => 5,
        'multiOptions' => array(
            'NULL' => 'Select',
            '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5'
        ),
    ));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.