How get value selected using Zend_Form_Element_Select

我的未来我决定 提交于 2019-12-14 01:57:41

问题


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


回答1:


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')];



回答2:


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'); 
...


来源:https://stackoverflow.com/questions/5976867/how-get-value-selected-using-zend-form-element-select

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!