我在 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
如何使用存储在实体中的变量来构建表单字段?