Naphstor
Naphstor

Reputation: 2496

creating multiple elements with same set of options in zend framework.

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.

Upvotes: 1

Views: 1183

Answers (3)

Pieter
Pieter

Reputation: 1774

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'
        ),
    ));
}

Upvotes: 2

vandalizmo
vandalizmo

Reputation: 377

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...

Upvotes: 2

Adrian World
Adrian World

Reputation: 3128

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

$B2 = clone $B1;
$B2->setLabel('B2Rating');

Upvotes: 2

Related Questions