Zend FrameWork 2 Get ServiceLocator In Form and populate a drop down list

前端 未结 6 1340
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 14:40

I need to get the adapter from the form, but still could not.

In my controller I can recover the adapter using the following:



        
6条回答
  •  礼貌的吻别
    2021-02-02 15:27

    We handle this in the model, by adding a method that accepts a form

    public function buildFormSelectOptions($form, $context = null)
    {
        /** 
         * Do this this for each form element that needs options added
         */
        $model = $this->getServiceManager()->get('modelProject');
    
        if (empty($context)){
            $optionRecords = $model->findAll();
        } else {
            /**
             * other logic for $optionRecords
             */
        }
    
        $options = array('value'=>'', 'label'=>'Choose a Project');
        foreach ($optionRecords as $option) {
            $options[] = array('value'=>$option->getId(), 'label'=>$option->getName());
        }
    
        $form->get('project')->setAttribute('options', $options);
    }
    

    As the form is passed by reference, we can do something like this in the controller where the form is built:

        $builder = new AnnotationBuilder();
        $form = $builder->createForm($myEntity);
        $myModel->buildFormSelectOptions($form, $myEntity);
    
        $form->add(array(
            'name' => 'submitbutton',
            'attributes' => array(
                'type'  => 'submit',
                'value' => 'Submit',
                'id' => 'submitbutton',
            ),
        ));
    
        $form->add(array(
            'name' => 'cancel',
            'attributes' => array(
                'type'  => 'submit',
                'value' => 'Cancel',
                'id' => 'cancel',
            ),
        ));
    

    Note: The example assumes the base form is build via annotations, but it doesn't matter how you create the initial form.

提交回复
热议问题