Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate zend form select element?

Hello I have been searching for it from last couple of hours and have read every matching result google can give me but still can't get it to work.

I am creating a zend form select element through:

this->addElement('select','my_select', array( 
    'label' => 'Currency', 'value' => 'blue', 
    'multiOptions' => array( 'red' => 'Rouge', 'blue' => 'Bleu', 'white' => 'Blanc', ), ) );

now I want to populate it through

$form->populate

from the controller, I have tried giving double dimensional array like

$vals = array("my_select" => array("US Dollar", "Pound Sterling")) 

and then giving it in:

$form->populate($vals);

but this didnt worked and I am not sure if this will work, at the moment I am building my array like in array( 'red' => 'Rouge', 'blue' => 'Bleu', 'white' => 'Blanc') the same class as zend form and then passsing it to the addElement multiOptions dynamically, as this guy suggests here: http://zendguru.wordpress.com/2009/03/06/zend-framework-form-working-with-dropdownselect-list/ that works but I would like to have it through populate and also if someone can suggest me how to select default value as well, I will be very grateful!

Thanks,

like image 868
Hammad Tariq Avatar asked Aug 13 '10 16:08

Hammad Tariq


1 Answers

The populate method allows you to "populate" the form with default values IE:

$form->populate(array("my_select" => "red"); 

That would set the my_select to have "red" as being selected.

EDIT

As for the multi-dimensional array, I am not exactly sure what you are trying to do, do you want another select statement or to append those items? It seems like it should be another select element.

Looking more at it, what you want is to set that select up with values from the populate method, this is not an option. You can do something like this, however:

$currency = new Zend_Form_Element_Select('currency', array(
       "label" => "Currency",
       "required" => true,
    ));
$currency->addMultiOptions(array(
        "US Dollar" => 1,
        "Pound Sterling" => 2,
    ));

$form->addElements(array($currency));

$form->populate(array("currency" => "US Dollar"));

And that will add your currency select statement. And that should setup the drop down (the array of values could potentially come from the database etc) and then set US Dollar to be the default with the populate method.

like image 139
Jim Avatar answered Oct 05 '22 23:10

Jim