Zend Framework - 在选择框下拉列表中设置“选定"值

2021-12-29 00:00:00 html-select php zend-framework zend-form

我正在向 Zend_Form 实例添加一个 select 元素,如下所示:

I am adding a select element to a Zend_Form instance as follows:

  $user = $form->createElement('select','user')->setLabel('User: ')->setRequired(true);
  foreach($users as $u)
        {
            if($selected == $u->id)
            {
                $user->addMultiOption($u->id,$u->firstname.' '.$u->lastname);
                //*** some way of setting a selected option? selected="selected"

            }
            else
                $user->addMultiOption($u->id,$u->firstname.' '.$u->lastname);
        }

我一直在搜索文档,但找不到将选择元素的选项预先设置为已选择"的简单方法.

I have been searching the docs but cannot find a simple way of pre-setting an option of the select element to 'selected'.

推荐答案

我刚刚想出了如何去做.

I've just worked out how to do it.

必须使用元素的 setValue() 方法:

You have to use the setValue() method of the element:

$user = $form->createElement('select','user')->setLabel('User: ')->setRequired(true);
    foreach($users as $u)
        $user->addMultiOption($u->id,$u->firstname.' '.$u->lastname);

$user->setValue($selected); //$selected is the 'value' of the <option> that you want to apply selected="selected" to.

相关文章