简体   繁体   English

使用它的 id 设置一个 Symfony2 实体表单字段

[英]Setting a Symfony2 Entity form field using it's id

I have a Symfony2 unmapped form which has a field of type 'Entity'.我有一个 Symfony2 未映射表单,它有一个“实体”类型的字段。 Here is the form type definition:这是表单类型定义:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('RegistrationForgotEmailTemplate', 'entity', array(
            'class' => 'EmailBundle:EmailTemplate',
            'placeholder' => '-- Default ---',
        ));
}

Here is where I build the form instance:这是我构建表单实例的地方:

$data = array('RegistrationForgotEmailTemplate' => 4);
$form = $this->createForm($formType, $data, array(
            'action' => $url,
            'method' => 'POST'
            ));

My problem is the form is not setting the RegistrationForgotEmailTemplate field to the correct entity (id 4).我的问题是表单没有将 RegistrationForgotEmailTemplate 字段设置为正确的实体(id 4)。 I assume this is because I am providing the id of the entity rather than an instance of it.我认为这是因为我提供的是实体的 id 而不是它的实例。 Is there a way of providing the just the id of the entity to set this field or is the only way to pass an instance of the entity I want to set the field to?有没有办法提供实体的 id 来设置这个字段,或者是传递我想设置字段的实体实例的唯一方法?

You could either use a transformer or you could use the "choice" field rather than "entity" and inject an object to provide the choices list (likely a repository).您可以使用转换器,也可以使用“选择”字段而不是“实体”并注入一个对象来提供选择列表(可能是存储库)。

Personally I think you'll find the transformer method easier.我个人认为你会发现变压器方法更容易。 The resulting code will be nicer too生成的代码也会更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM