2

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

2 Answers 2

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')];
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.