Zend-动态表单下拉菜单

时间:2018-07-28 11:18:51

标签: zend-framework doctrine dropdown zend-form

我从zend框架开始,但在实现动态下拉列表时遇到了麻烦。

我需要创建一个简单的下拉列表,以选择从数据库中选择的事件。

这是我的模块类:

public function getFormElementConfig()
{
    return array(
        "factories" => [
            'participant_form' => function (ServiceManager $serviceManager) {

                /** @var EntityManager $entityManager */
                $entityManager = $serviceManager->get("doctrine.entitymanager.orm_default");

                $events = $entityManager->getRepository('Application\Entity\Event')->findAll();
                $eventForSelect = array();
                foreach ($events as $event) {
                  $eventForSelect[$event->getId()] = $event->getName();
                }

                /** @var \Zend\Form\Form $form */
                $form = new ParticipantForm();
                $form->setHydrator(new DoctrineHydrator($entityManager));
                $form->setObject(new Participant());

                $form->setOption('event_for_select', $eventForSelect);

                return $form;

            },
        ]
    );
}

但我不知道如何在我的表单中获取选项“ event_for_select”:

class ParticipantForm extends Form
{
  public function __construct($name = null)
  {

    parent::__construct('user');

    $this->setAttribute('class', 'form-horizontal');

    $this->add([
        'name' => 'id',
        'type' => 'Hidden',
    ]);

    $this->add([
        'name'    => 'firstname',
        'type'    => 'Text',
        'options' => [
            'label' => 'Prénom',
        ],
    ]);

    $this->add([
        'name'    => 'event',
        'type'    => 'Select',
        'options' => [
                 'label' => 'Event',
                 'value_options' => // ?? $event_for_select

         ],
    ]);

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

在表单类中添加字段:

class ParticipantForm extends Form
{
    protected $eventForSelect;

    public function setEventForSelect($eventForSelect)
    {
        $this->eventForSelect = $eventForSelect;

        // update field value options
        $this->get('event')
             ->setValueOptions($this->eventForSelect);

        return $this;
    }

    // rest of form class code
}

然后在工厂中使用setEventForSelect()方法:

/** @var \Zend\Form\Form $form */
$form = new ParticipantForm();
$form->setHydrator(new DoctrineHydrator($entityManager));
$form->setObject(new Participant());

$form->setEventForSelect($eventForSelect);

return $form;

然后采用以下格式:

$this->add([
    'name'    => 'event',
    'type'    => 'Select',
    'options' => [
        'label' => 'Event',
        'value_options' => $this->eventForSelect,
     ],
]);