2

我在 Symfony2 中有一个 FormType。它用于显示设置。设置作为实体存储在数据库中。使用 Doctrine2,我获取设置并创建一个表单,如下所示:

public function showSettingsAction()
{
    if(false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
        throw new AccessDeniedException();
    }
    $settings = new CommunitySettings();

    $repository = $this->getDoctrine()->getRepository('TestTestingBundle:CommunitySettings');
    $allSettings = $repository->findAll();

    $form = $this->createForm('collection', $allSettings, array(
        'type' => 'settings_form'
    ));
    $request = $this->container->get('request');
    if($request->getMethod() === 'POST') {
        $form->bindRequest($request);
        if($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $settings = $form->getData();
            foreach($settings as $setting) {
                $oldsetting = $em->getRepository('TestTestingBundle:CommunitySettings')
                    ->find($setting->getId());
                if(!$oldsetting) {
                    throw $this->createNotFoundException('No setting found for id '.$setting->getId());
                }

                $oldsetting->setSettingValue($setting->getSettingValue());
                $em->flush();
            }

            $this->get('session')->setFlash('message', 'Your changes were saved');

            return new RedirectResponse($this->generateUrl('_admin_settings'));
        }
    }


    return $this->render('TestTestingBundle:Admin:settings.html.twig',array(
        'form' => $form->createView(),
    ));
}

这是我将数组发送到的代码$allSettingssettings_form

$form = $this->createForm('collection', $allSettings, array(
    'type' => 'settings_form'
));

这是设置表单的样子:

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('settingValue', 'text');
}

我在实体中存储了一个标签、一个值和一个字段类型,我想用它们来构建表单。但是,当我使用它时,它只显示表单中的变量名称,如下所示:

0
Settingvalue //Is a checkbox, where it says Settingvalue, it should be the label stored in the entity
0

1
Settingvalue //Is a integer, where it says Settingvalue, it should be the label stored in the entity
3000

如何使用存储在实体中的变量来构建表单字段?

4

1 回答 1

3

您可以在设置表单类型中使用事件侦听器来解决此问题。

public function buildForm(FormBuilder $builder, array $options)
{
    $formFactory = $builder->getFormFactory();
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formFactory) {
        $form = $event->getForm();
        $data = $event->getData();

        $form->add($formFactory->createNamed('settingsValue', $data->getSettingsType(), array(
            'label' => $data->getSettingsLabel(),
        )));
    });
}
于 2012-07-31T17:08:33.693 回答