Reputation: 2590
I currently am trying the following code:
$sql = $db->query("select id,username,fullname from userss ORDER BY fullname ASC");
while($row = $sql->fetch()) {
$username[] = $row['username'];
}
$form = new Zend_Form();
$form->setAction('/index/change')
->setMethod('post');
$element = new Zend_Form_Element_Select('foo', array(
'multiOptions' => array(
$username,
)));
$form->addElement($element);
echo $form;
The desired result is the <select>
form showing the elements <option value='username'>Full Name</option>
where username is username
from SQL and Full Name is fullname
from sql.
Right now, it shows <option value='0'>Full Name</option>
I'm not quite sure how to specify the first part of the array, so that it will essentially be username => Full Name
Any suggestions? Thanks!
Upvotes: 0
Views: 384
Reputation: 8186
To make populating select element easier ZF provides fetchPairs
$sql = "select username,fullname from userss ORDER BY fullname ASC";
$db = Zend_Db_Table::getDefaultAdapter();
$select = new Zend_Form_Element_Select('foo');
$select->setMultiOptions($db->fetchPairs($sql));
This way saves you from iterating data (for, while loops) yourself.
Upvotes: 2
Reputation: 69957
To set the value of an option in a Zend_Form_Element_Select
, the array key defines the value, and the array value defines the text in the select that the user sees.
Try this:
$element = new Zend_Form_Element_Select('foo', array(
'multiOptions' => array(
$username => $fullname,
$username2 => $fullname2,
)));
You were seeing 0 since the array didn't have string keys, it defaulted to use the numerically indexed array keys as values.
Given your code, you would do this:
$username = array();
while($row = $sql->fetch()) {
$username[$row['username']] = $row['fullname'];
}
Upvotes: 3