开发者

How get value selected using Zend_Form_Element_Select

I have the following code in a Zend form, creating a drop-down开发者_如何学编程 list fed from a database:

// ... previously create the array $list and fill it from database

$element = new Zend_Form_Element_Select('name');
$element->setLabel('List name')
    ->addMultiOptions($list);   
$this->addElement($element, 'list_name', array(
         'required' => true,
        ));

Question: how can I get the value after posting the form? With the above code, $post['name'] returns the index of the selected item. A detail: the html generated code shows that the content in the $list are assigned to each element as 'label=' and the 'value=' attribute is the index that I retrieve through $post. So I believe it's a matter of correctly defining the options of Zend_Form_Element_Select ...

Thanks


The $list array should be built as:

$list = array(
    'value1' => 'label1',
    'value2' => 'label2',
);

After you've called isValid(), you can retrieve the value using $form->getValue('list_name');

If, instead, you want to retrieve the label, you can do:

$listNameOptions = $form->getElement('list_name')->getMultiOptions();
$label = $listNameOptions[$form->getValue('list_name')];


At first,i have the same question as you,then i tried like this,it works:

create the select obj :

...//code above ellipsis
$userName = new Zend_Form_Element_Select("userName");  //create obj
$userName->setLabel('user');

$db = Zend_Registry::get("db");
$sql = $db->quoteInto('select * from user',null);
$users = $db->query($sql)->fetchAll();

$userArray = array();
foreach ($users as $user){
    /*use value as the key,while form submited,key was added into response obj*/
    $userArray[ $user['name']] = $user['name']; //create the $list
}

$userName->addMultiOptions($userArray);
...

get selected data :

... 

//check if method is post

if ($this->getRequest()->isPost()){  

    $formData = $this->getRequest()->getPost();

    if($loginForm->isValid($formData)){

        //get the selected data

        $userName = $this->getRequest()->getParam('userName'); 
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜