Just wondering how it works and how to handle the information.
Let's say I have a form like this:
$multi = new Zend_Form_Element_Multiselect('users');
$multi->setMultiOptions(array(
//'option value' => 'option label'
'21' => 'John Doe',
'22' => 'Joe Schmoe',
'23' => 'Foobar Bazbat'
));
$form->addElement($multi);
If a user selects one, or multiple values from a multi-select box...
Using a multi select element like this one:
$multi = new Zend_Form_Element_Multiselect('users');
$multi->setMultiOptions(array(
//'option value' => 'option label'
'21' => 'John Doe',
'22' => 'Joe Schmoe',
'23' => 'Foobar Bazbat'
));
$form->addElement($multi);
You can get the values of the element like this:
public function indexAction()
{
$form = new MyForm();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
$values = $form->getValues();
$users = $values['users']; //'users' is the element name
var_dump $users;
}
}
$this->view->form = $form;
}
$users
will contain an array of the values that have been selected:
array(
0 => '21',
1 => '23'
)
$form->getElement('name')->getValue()
will return the value of $_POST['name']. You can make
$_POST['name']
be an array by defining the name of the element with brackets at the end. So in this case, 'name[]'. In the Zend Framework, use an element that extends
Zend_Form_Element_Multi
Please see: http://www.framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.multiselect
For example:
$multi = $form->createElement('multiselect', 'name[]');
$multi->setMultiOptions($options);
$form->addElement($multi);
if ($form->isValid($_POST)) {
$userSelectedOptions = $form->getElement('name')->getValue();
}
See the answer from brad. The especial part is the name of the element
$multi = $form->createElement('multiselect', 'name[]');
if you call the element with squares it will be handled as an array by the browser (not a zf behavior). Otherwise you'll get only the first selected element
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With