Symfony2 设置默认选择字段选择 [英] Symfony2 Setting a default choice field selection

查看:21
本文介绍了Symfony2 设置默认选择字段选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以下列方式创建表单:

I am creating a form in the following manner:

$form = $this->createFormBuilder($breed)
             ->add('species', 'entity', array(
                  'class' => 'BFPEduBundle:Item',
                  'property' => 'name',
                  'query_builder' => function(ItemRepository $er){
                      return $er->createQueryBuilder('i')
                                ->where("i.type = 'species'")
                                ->orderBy('i.name', 'ASC');
                  }))
             ->add('breed', 'text', array('required'=>true))
             ->add('size', 'textarea', array('required' => false))
             ->getForm()

如何为物种列表框设置默认值?

How can I set a default value for the species listbox?

感谢您的回复,我很抱歉,我想我应该重新表述我的问题.一旦我有了从模型中检索到的值,我该如何将该值设置为 SELECTED="yes" 以用于物种选择列表中的相应值?

Thank you for your response, I apologise, I think I should rephrase my question. Once I have a value that I retrieve from the model, how do I set that value as SELECTED="yes" for the corresponding value in the species choice list?

因此,TWIG 视图中的选择选项输出将如下所示:

So, that select option output from the TWIG view would appear like so:

<option value="174" selected="yes">Dog</option>

推荐答案

如果您使用 Cristian's 的解决方案,您将需要将 EntityManager 注入到您的 FormType 类中.这是一个简化的例子:

If you use Cristian's solution, you'll need to inject the EntityManager into your FormType class. Here is a simplified example:

class EntityType extends AbstractType{
    public function __construct($em) {
        $this->em = $em;
    }

    public function buildForm(FormBuilderInterface $builder, array $options){
         $builder
             ->add('MyEntity', 'entity', array(
                     'class' => 'AcmeDemoBundle:Entity',
                     'property' => 'name',
                     'query_builder' => function(EntityRepository $er) {
                         return $er->createQueryBuilder('e')
                             ->orderBy('e.name', 'ASC');
                     },
                     'data' => $this->em->getReference("AcmeDemoBundle:Entity", 3)
        ));
    }
}

还有你的控制器:

 // ...    

 $form = $this->createForm(new EntityType($this->getDoctrine()->getManager()), $entity);

// ...

来自 Doctrine Docs:

EntityManager#getReference($entityName, $identifier) 方法允许您获取对标识符已知的实体的引用,而无需从数据库加载该实体.这很有用,例如,当您想要建立与您拥有标识符的实体的关联时,作为性能增强.

The method EntityManager#getReference($entityName, $identifier) lets you obtain a reference to an entity for which the identifier is known, without loading that entity from the database. This is useful, for example, as a performance enhancement, when you want to establish an association to an entity for which you have the identifier.

这篇关于Symfony2 设置默认选择字段选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆