在Symfony 3中将参数从控制器传递到表单类型__construct

时间:2017-08-11 07:53:17

标签: php symfony symfony-2.1 symfony-3.3

在Symfony2中,我们使用了:

$form = $this->createForm(new MyFormType($mySession));

我们可以在__construct中传递$ session作为参数。

但是我无法在Symfony3中传递$ session参数

我尝试过这样的事情:

$form = $this->createForm(MyFormType::class, array(
        'mySession' => $mySession
    ));

有人可以指导我吗?如何解决这个问题。 提前谢谢!

2 个答案:

答案 0 :(得分:1)

createForm方法的第二个参数是您设置的$ datas。您可以使用FormType configureOptions中的data_class将数据链接到实体,如下所示:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => MyEntity::class,
    ));
}

此外,Symfony接受选项的第三个参数 以下是核心方法:

/**
     * Creates and returns a Form instance from the type of the form.
     *
     * @param string $type    The fully qualified class name of the form type
     * @param mixed  $data    The initial data for the form
     * @param array  $options Options for the form
     *
     * @return Form
     */
    protected function createForm($type, $data = null, array $options = array())
    {
        return $this->container->get('form.factory')->create($type, $data, $options);
    }

答案 1 :(得分:0)

我希望此链接可以帮助您:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $this->yourVarableName = $options['yourVarableName']; // here you will catch your pass data

    $builder
        ->add('name', TextType::class)
        ...
        ->add('your_field_type', ChoiceType::class, array(
            'label' => 'Label Field',
            'mapped' => false,
            'choices' => $this->traitChoices['figure_type']
        ))
        ...
    ;
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Foo\YouBundle\Entity\Goal',
        'yourVarableName' => null, // here your data
    ));
}

在创建控制器表单时:

$goal = new Goal(); //instance of Entity
$form = $this->createForm(GoalType::class, $goal, array(
        'action' => $this->generateUrl('profile_update'),
        'method' => 'PUT',
        'yourVarableName' => $yourVarableName,
    ));