【问题标题】:Passing data to buildForm() in Symfony 3.3在 Symfony 3.3 中将数据传递给 buildForm()
【发布时间】:2017-10-22 04:44:08
【问题描述】:

我正在尝试将当前经过身份验证的用户传递给 buildForm 几个小时,我搜索了谷歌...没有任何效果 我得到的错误是

表单的视图数据应该是 AppBundle\Entity\AdsList 类的一个实例,但它是一个 (n) 数组。您可以通过将“data_class”选项设置为 null 或添加将 a(n) 数组转换为 AppBundle\Entity\AdsList 实例的视图转换器来避免此错误。

->getForm();

我必须想好要做什么......视图转换器......(https://symfony.com/doc/current/form/data_transformers.html

但我只有一个整数...

如果你有一个很好的例子,我还想从内容中生成独特的 slug(最终版本不会有标题字段):)

提前感谢:)

AgencyController.php

/**
 * @Route("/agency/post", name="agency_post")
 */
public function agencyNewAd(Request $request)
{
   //  $agency = $this->get('security.token_storage')->getToken()->getUser(); ( this didn't worked .. )
    $form = $this->createForm(AgencyNewAdType::class, array(
        'postedBy' => $this->getUser(),
    ));
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $ad = $form->getData();

        // save the task to the database
        $em = $this->getDoctrine()->getManager();
        $em->persist($ad);
        $em->flush();
        // return new Response('Saved new Post with id ' . $ad->getId());
        return $this->redirectToRoute('agency_admin');
    }
    return $this->render('agency/new_ad.html.twig', [
        'adForm' => $form->createView()
    ]);
}

AgencyNewAdType.php

class AgencyNewAdType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    // https://stackoverflow.com/questions/36905490/how-to-pass-parameter-to-formtype-constructor-from-controller
    $builder
        ->add('title', TextType::class)
        ->add('content', TextareaType::class)
        ->add('category', EntityType::class, array(
            // query choices from Category.Name
            'class' => 'AppBundle:CategoryAd',
            'choice_label' => 'name',
        ))
        ->add('postedAt', DateType::class)
        ->add('postedBy',HiddenType::class, array(
            'data' => $options['postedBy']
        ))
        ->add('save', SubmitType::class, array('label' => 'Create Post'))
        ->getForm();

}
public function configureOptions(OptionsResolver $resolver)
   {
    $resolver->setDefaults(array(
        'postedBy' => null,
        'data_class' => 'AppBundle\Entity\AdsList',
    ));
   }
}

【问题讨论】:

    标签: php symfony arguments


    【解决方案1】:

    我需要将参数传递给表单,使其看起来像

    public function agencyNewAd(Request $request): Response
    {
        $pass = new AdsList();
        $pass->setPostedBy($this->getUser());
        $form = $this->createForm(AgencyNewAdType::class, $pass);
        $form->handleRequest($request);
    
        if ($form->isSubmitted() && $form->isValid()) {
            // $form->getData() holds the submitted values iN MeM
            $ad = $form->getData();
    
            // save the ad to the database
            $em = $this->getDoctrine()->getManager();
            $em->persist($ad);
            $em->flush();
            // return new Response('Saved new Post with id ' . $ad->getId());
            return $this->redirectToRoute('agency_admin');
        }
        return $this->render('agency/new_ad.html.twig', [
            'adForm' => $form->createView()
        ]);
    }
    

    并且在表单中我需要删除postedBy ...

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // https://stackoverflow.com/questions/36905490/how-to-pass-parameter-to-formtype-constructor-from-controller
        $builder
            ->add('title', TextType::class)
            ->add('content', TextareaType::class)
            ->add('category', EntityType::class, array(
                // query choices from Category.Name
                'class' => 'AppBundle:CategoryAd',
                'choice_label' => 'name',
            ))
            ->add('postedAt', DateType::class)
            ->add('save', SubmitType::class, array('label' => 'Create Post'))
            ->getForm();
    
    }
    

    【讨论】:

      【解决方案2】:

      在控制器中创建时你错过了一个参数,第二个参数应该是你连接到表单的对象,第三个是选项数组,所以它看起来像:

      public function agencyNewAd(Request $request)
      {
          $ad = new AdsList();
          $form = $this->createForm(AgencyNewAdType::class, $ad, array(
              'postedBy' => $this->getUser(),
          ));
          $form->handleRequest($request);
      
          if ($form->isSubmitted() && $form->isValid()) {
              $em = $this->getDoctrine()->getManager();
              $em->persist($ad);
              $em->flush();
      
              return $this->redirectToRoute('agency_admin');
          }
          return $this->render('agency/new_ad.html.twig', [
              'adForm' => $form->createView()
          ]);
      }
      

      另一种方法是将您的选项传递给表单的构造,如下所示:

      public function agencyNewAd(Request $request)
      {
          $ad = new AdsList();
          $form = $this->createForm(new AgencyNewAdType($this->getUser()), $ad);
      

      然后在 AgencyNewAdType 的构造函数中,您将接受您的参数,在本例中为当前登录用户。

      【讨论】:

      • 对于第一个选项,我收到 10 页错误 -> An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class AppBundle\Entity\Agency could not be converted to string").
      • 第二个 -> ` 类型错误:传递给 Symfony\Bundle\FrameworkBundle\Controller\Controller::createForm() 的参数 3 必须是数组类型,给定对象,在 /home 中调用/dev/www/d/src/AppBundle/Controller/AgencyController.php 第 46 行` 第 46 行` $form = $this->createForm(AgencyNewAdType::class,($this->getUser()), $ad) ;`
      • @AlexanderBr。第一个错误看起来与表单无关,因为我没有看到您在任何地方提到代理实体,但我猜您需要该实体中的 toString 方法
      • 你能帮帮我吗?
      • @AlexanderBr。检查我的答案你必须做$this->createForm(new AgencyNewAdType($this->getUser()), $ad);所以你的表单构造函数接受用户实体而不是第二个参数
      猜你喜欢
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多