【问题标题】:How to use a custom FormType in Symfony 3如何在 Symfony 3 中使用自定义 FormType
【发布时间】:2016-02-28 02:10:57
【问题描述】:

我正在训练,但我在 symfony 3 下

我有问题我得到这个错误

“字符串”类型的预期参数, 给出“Test\FrontBundle\Form\Type\SheetType”

SheetType.php 上的代码是

<?php

namespace Test\FrontBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\FormBuilderInterface;


class SheetType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name',null,array('label'=>'Titre de l\'album'))
            ->add('type')
            ->add('artist')
            ->add('duration')
            ->add('released', DateType::class)
            ;
    }
}

在我的 SheetController.php 上,我从我的控制器中做到这一点 我一直不知道如何解决这个问题,否则我会出错

 public function createAction(Request $request)
    {
        $form = $this->createForm(new SheetType());

        $form->handleRequest($request);

        if($request->isMethod('post') && $form->isValid()){
            $em = $this->getDoctrine()->getManager();
            $em->persist($form->getData());
            $em->flush();
           return $this->redirect($this->generateUrl('test_front_sheet_list'));
        } 
        return $this->render('TestFrontBundle:Sheet:create.html.twig', array('form' => $form->createView()));
    }

【问题讨论】:

    标签: symfony-forms symfony


    【解决方案1】:

    由于 symfony 2.8 在创建表单或表单构建器时您必须传递一个完整的类名实例作为参数,它不再采用 FormTypeInterface 的实例。

    https://github.com/symfony/symfony/blob/2.8/UPGRADE-2.8.md

    所以你应该改用$form = $this-&gt;createForm(SheetType::class);

    【讨论】:

    • 我们现在如何在 formType 中传递自定义属性?我曾经这样做过:new MyFormType($customAttr) 但现在我们必须传递表单类型的完全限定类名,我不能再这样做了..
    猜你喜欢
    • 2013-05-02
    • 2014-04-17
    • 2016-05-14
    • 1970-01-01
    • 2016-10-17
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    相关资源
    最近更新 更多