我有一个symfony 3表格。我试图用handleRequest填充它:
$user = new User();
$userForm = $this->createForm(UserType::class, $user);
print_r($request->request->all());
$userForm->handleRequest($request);
print_r($userForm->getData());
我得到的输出是:
Array
(
[firstName] => test
[last_name] => test
[email] => test@test.test
[password] => erkeferke
[gender] => F
[supervisor] => 1
)
AppBundle\Entity\User Object
(
[id:AppBundle\Entity\User:private] =>
[firstName] =>
[lastName:AppBundle\Entity\User:private] =>
[email:AppBundle\Entity\User:private] =>
[password:AppBundle\Entity\User:private] =>
[photo:AppBundle\Entity\User:private] =>
[gender:AppBundle\Entity\User:private] =>
[supervisor:AppBundle\Entity\User:private] =>
[duties:AppBundle\Entity\User:private] =>
[lastLogin:AppBundle\Entity\User:private] =>
[createdAt:AppBundle\Entity\User:private] =>
[updatedAt:AppBundle\Entity\User:private] =>
[deletedAt:AppBundle\Entity\User:private] =>
)
知道它为什么没有填充?
答案 0 :(得分:1)
要从表单请求自动填充实体,您必须将实体绑定到FormType类。您可能会错过UserType
课程中的此绑定。在表单UserType
中,您应在其中添加方法configureOptions
,并在entity class name
键中指定data_class
。要了解更多信息,请参阅Symfony Forms并向下滚动到Setting the data_class
主题。另请参阅下面的示例,其中列出了用法。
<?php namespace AppBundle\Form;
...
class SiteType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// define form fields
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Site', // Entity to resolve to
));
}
}
现在,当您使用表单时,您的实体将从请求中解析,如下所示$site = $form->getData()
将返回Site
实体。这是第一次做对这非常棘手。你必须经常练习它,直到你掌握它为止。如果您有混淆,请告诉我们。
/**
*
* @param Request $request
*
* @return \Symfony\Component\HttpFoundation\Response
*
* @Route("/sites/create", name="_create_site")
*/
public function createSite(Request $request)
{
$site = new Site;
$form = $this->createForm(SiteType::class, $site);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$site = $form->getData(); // It will return Site Entity
...
$this->addFlash('success', 'Record added successfully.');
}
return $this->render('sites/create.html.twig', [
'site_form' => $form->createView(),
]);
}