我在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(),
));
}
这是我将$allSettings
数组发送到settings_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
如何使用实体中存储的变量来构建带有?
的表单字段答案 0 :(得分: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(),
)));
});
}