gpt4 book ai didi

Symfony2,如何访问表单中的实体值?

转载 作者:行者123 更新时间:2023-12-04 05:40:12 25 4
gpt4 key购买 nike

我在 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

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

最佳答案

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

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(),
)));
});
}

关于Symfony2,如何访问表单中的实体值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11357748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com