【问题标题】:Passing an object from controller to form type将对象从控制器传递到表单类型
【发布时间】:2017-01-09 04:50:07
【问题描述】:

我想将一个对象从控制器传递到我的表单构建器,以便稍后将其用于我的 ChoiceType 字段。我该如何做到这一点?

这是我的控制器:

    $choices          = [];
    $table2Repository = $this->getDoctrine()->getRepository('SwipeBundle:Company');
    $table2Objects    = $table2Repository->findAll();

    foreach ($table2Objects as $table2Obj) {
        $choices[$table2Obj->getId()] = $table2Obj->getId() . ' - ' . $table2Obj->getName();
    }

    $form = $this->createForm(SubAgentType::class, $choices, array(
        'action'=>$this->generateUrl('backend_sub_agent_create'),
        'method'=>'POST'
    ));

这是我的 SubAgentType.php

class SubAgentType extends AbstractType {

    protected $choices;

    public function __construct (Choices $choices)
    {
        $this->choices = $choices;
    }    

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('company_id', ChoiceType::class, array(
            'mapped'  => false,
            'choices' => $choices,
        ));

问题是我收到以下错误。

可捕获的致命错误:参数 1 传递给 MyBundle\Form\SubAgentType::__construct() 必须是 MyBundle\Form\Choices,

【问题讨论】:

    标签: php symfony


    【解决方案1】:

    回答您的问题:

    在您的 services.yml 文件中:

    myform.type:
        class: AppBundle\Form\MyFormType
        arguments:
            - '@doctrine.orm.entity_manager'
        tags:
          - { name: form.type }
    

    在您的 MyFormType 中:

    /**
     * @var EntityManagerInterface
     */
    protected $em;
    
    /**
     * LicenseeType constructor.
     *
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }
    
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $choices          = [];
        $table2Repository = $this-em->getRepository('SwipeBundle:Company');
        $table2Objects    = $table2Repository->findAll();
    
        foreach ($table2Objects as $table2Obj) {
            $choices[$table2Obj->getId()] = $table2Obj->getId() . ' - ' . $table2Obj->getName();
        }
    
        ...
    

    但是,很明显,如果您正确定义实体关系,则不需要这样做。

    【讨论】:

    • There is no extension able to load the configuration for "myform.type"
    【解决方案2】:

    尝试在 SubAgentType 中解析你的构造函数,$choices 不需要是 Choices 的子类型:

    public function __construct ($choices)
    {
        $this->choices = $choices;
    }
    

    如果你在控制器中注入一个数组,那么构造函数必须接受一个数组。

    【讨论】:

    • 但是你应该有另一种行为,现在是什么?
    猜你喜欢
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多