Symfony2设置默认的选择字段。

时间:2021-12-17 07:34:48

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?

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


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?

谢谢你的回复,我道歉,我想我应该重新表达我的问题。一旦我获得了从模型中检索的值,我如何将该值设置为在物种选择列表中对应的值的选择="yes" ?

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

因此,从TWIG视图中选择的选项输出将会是这样:

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

12 个解决方案

#1


57  

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

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

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)
        ));
    }
}

And your controller:

和你的控制器:

 // ...    

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

// ...

From Doctrine Docs:

从教义文档:

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.

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

#2


109  

You can define the default value from the 'data' attribute. This is part of the Abstract "field" type (http://symfony.com/doc/2.0/reference/forms/types/field.html)

您可以从“data”属性定义默认值。这是抽象“字段”类型的一部分(http://symfony.com/doc/2.0/reference/forms/types/field.html)。

$form = $this->createFormBuilder()
            ->add('status', 'choice', array(
                'choices' => array(
                    0 => 'Published',
                    1 => 'Draft'
                ),
                'data' => 1
            ))
            ->getForm();

In this example, 'Draft' would be set as the default selected value.

在本例中,“Draft”将被设置为默认的选定值。

#3


23  

the solution: for type entity use option "data" but value is a object. ie:

解决方案:对于类型实体使用选项“数据”,但值是一个对象。即:

$em = $this->getDoctrine()->getEntityManager();

->add('sucursal', 'entity', array
(

    'class' => 'TestGeneralBundle:Sucursal',
    'property'=>'descripcion',
    'label' => 'Sucursal',
    'required' => false,
    'data'=>$em->getReference("TestGeneralBundle:Sucursal",3)           

))

#4


5  

I think you should simply use $breed->setSpecies($species), for instance in my form I have:

我认为您应该简单地使用$breed->setSpecies($species),例如在我的表单中:

$m = new Member();
$m->setBirthDate(new \DateTime);
$form = $this->createForm(new MemberType, $m);

and that sets my default selection to the current date. Should work the same way for external entities...

这将我的默认选择设置为当前日期。对于外部实体,应该采用同样的方法……

#5


3  

If you want to pass in an array of Doctrine entities, try something like this (Symfony 3.0+):

如果您想要传入一个Doctrine实体数组,可以尝试如下方法(Symfony 3.0+):

protected $entities;
protected $selectedEntities;

public function __construct($entities = null, $selectedEntities = null)
{
    $this->entities = $entities;
    $this->selectedEntities = $selectedEntities;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('entities', 'entity', [
        'class' => 'MyBundle:MyEntity',
        'choices' => $this->entities,
        'property' => 'id',
        'multiple' => true,
        'expanded' => true,
        'data' => $this->selectedEntities,
    ]);
}

#6


2  

I'm not sure what you are doing wrong here, when I build a form using form classes Symfony takes care of selecting the correct option in the list. Here's an example of one of my forms that works.

我不确定您在这里做错了什么,当我使用form类创建一个表单时,Symfony负责选择列表中的正确选项。这是我的一个作品的例子。

In the controller for the edit action:

在控制器中编辑操作:

$entity = $em->getRepository('FooBarBundle:CampaignEntity')->find($id);

if (!$entity) {
throw $this->createNotFoundException('Unable to find CampaignEntity entity.');
}


$editForm = $this->createForm(new CampaignEntityType(), $entity);
$deleteForm = $this->createDeleteForm($id);

return $this->render('FooBarBundle:CampaignEntity:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));

The campaign entity type class (src: Foo\BarBundle\Form\CampaignEntityType.php):

活动实体类型类(src: Foo\BarBundle\Form\ campaign - type .php):

namespace Foo\BarBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;

class CampaignEntityType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
        ->add('store', 'entity', array('class'=>'FooBarBundle:Store', 'property'=>'name', 'em'=>'my_non_default_em','required'  => true, 'query_builder' => function(EntityRepository $er) {return $er->createQueryBuilder('s')->orderBy('s.name', 'ASC');}))
        ->add('reward');
    }
    public function getName()
    {
        return 'foo_barbundle_campaignentitytype';
    }
}

#7


2  

From the docs:

从文档:

public Form createNamed(string|FormTypeInterface $type, string $name, mixed $data = null, array $options = array())

mixed $data = null is the default options. So for example I have a field called status and I implemented it as so:

混合$data = null是默认选项。例如,我有一个名为status的字段,我将它实现如下:

$default = array('Status' => 'pending');

$filter_form = $this->get('form.factory')->createNamedBuilder('filter', 'form', $default)
        ->add('Status', 'choice', array(
            'choices' => array(
                '' => 'Please Select...',
                'rejected' => 'Rejected',
                'incomplete' => 'Incomplete',
                'pending' => 'Pending',
                'approved' => 'Approved',
                'validated' => 'Validated',
                'processed' => 'Processed'
            )
        ))->getForm();

#8


2  

Setting default choice for symfony2 radio button

设置symfony2单选按钮的默认选择。

            $builder->add('range_options', 'choice', array(
                'choices' => array('day'=>'Day', 'week'=>'Week', 'month'=>'Month'),
                'data'=>'day', //set default value 
                'required'=>true,
                'empty_data'=>null,
                'multiple'=>false,
                'expanded'=> true                   
        ))

#9


1  

The form should map the species->id value automatically to the selected entity select field. For example if your have a Breed entity that has a OnetoOne relationship with a Species entity in a join table called 'breed_species':

表单应该将该物种的id值自动映射到所选的实体选择字段。例如,如果您有一个品种实体,它与一个名为“育种物种”的联接表中的物种实体有一个一对一的关系:

class Breed{

    private $species;

    /**
    * @ORM\OneToOne(targetEntity="BreedSpecies", mappedBy="breed")
    */
    private $breedSpecies;

    public function getSpecies(){
       return $breedSpecies->getSpecies();
    }

    private function getBreedSpecies(){
       return $this->$breedSpecies;
    }
}

The field 'species' in the form class should pick up the species->id value from the 'species' attribute object in the Breed class passed to the form.

表单类中的字段“物种”应该从传递给表单的“物种”属性对象中获取该物种->id值。

Alternatively, you can explicitly set the value by explicitly passing the species entity into the form using SetData():

或者,您可以显式地设置值,通过使用SetData()将该物种实体显式地传递到表单中:

    $breedForm = $this->createForm( new BreedForm(), $breed );
    $species   = $breed->getBreedSpecies()->getSpecies();

    $breedForm->get('species')->setData( $species );

    return $this->render( 'AcmeBundle:Computer:edit.html.twig'
                        , array( 'breed'     => $breed
                               , 'breedForm' => $breedForm->createView()
            )
    );

#10


1  

I don't think you should use the data option, because this does more than just setting a default value. You're also overriding any data that's being passed to the form during creation. So basically, you're breaking support for that feature. - Which might not matter when you're letting the user create data, but does matter when you want to (someday) use the form for updating data.

我认为您不应该使用data选项,因为这不仅仅是设置一个默认值。您还将重写在创建过程中传递给表单的任何数据。基本上,你是在打破对这个功能的支持。-当您允许用户创建数据时,这可能并不重要,但是当您希望(某一天)使用表单来更新数据时,这很重要。

See http://symfony.com/doc/current/reference/forms/types/choice.html#data

看到http://symfony.com/doc/current/reference/forms/types/choice.html数据

I believe it would be better to pass any default data during form creation. In the controller.

我相信在表单创建过程中传递任何默认数据会更好。在控制器。

For example, you can pass in a class and define the default value in your class itself. (when using the default Symfony\Bundle\FrameworkBundle\Controller\Controller)

例如,您可以传入一个类并定义类本身的默认值。(使用默认的Symfony\Bundle\FrameworkBundle\Controller\控制器)

$form = $this->createForm(AnimalType::class, [
    'species' => 174 // this id might be substituted by an entity
]);

Or when using objects:

或当使用对象:

$dog = new Dog();
$dog->setSpecies(174); // this id might be substituted by an entity

$form = $this->createForm(AnimalType::class, $dog);

Even better when using a factory: (where dog probably extends from animal)

在使用工厂时更好(狗可能从动物身上延伸)

$form = $this->createForm(AnimalType::class, DogFactory::create());

This will enable you to separate form structure and content from each other and make your form reusable in more situations.

这将使您能够分离表单结构和内容,并使您的表单在更多情况下可重用。


Or, use the preferred_choices option, but this has the side effect of moving the default option to the top of your form.

或者,使用preferred_options选项,但这有将默认选项移动到表单顶部的副作用。

See: http://symfony.com/doc/current/reference/forms/types/choice.html#preferred-choices

见:http://symfony.com/doc/current/reference/forms/types/choice.html首选方式

$builder->add(
    'species', 
    'entity', 
    [
        'class' => 'BFPEduBundle:Item',
        'property' => 'name',
        'query_builder' => ...,
        'preferred_choices' => [174] // this id might be substituted by an entity
     ]
 );

#11


0  

You can either define the right default value into the model you want to edit with this form or you can specify an empty_data option so your code become:

您可以将正确的默认值定义为您想要用该表单编辑的模型,或者您可以指定empty_data选项,以便您的代码成为:

$form = $this
    ->createFormBuilder($breed)
    ->add(
        'species',
        'entity',
        array(
            'class'         => 'BFPEduBundle:Item',
            'property'      => 'name',
            'empty_data'    => 123,
            '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()
;

#12


0  

You can use "preferred_choices" and "push" the name you want to select to the top of the list. Then it will be selected by default.

您可以使用“preferred_choice”和“push”这个名称,您想要在列表的顶部选择。然后它将被默认选中。

'preferred_choices' => array(1), //1 is item number

entity Field Type

实体字段类型

#1


57  

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

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

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)
        ));
    }
}

And your controller:

和你的控制器:

 // ...    

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

// ...

From Doctrine Docs:

从教义文档:

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.

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

#2


109  

You can define the default value from the 'data' attribute. This is part of the Abstract "field" type (http://symfony.com/doc/2.0/reference/forms/types/field.html)

您可以从“data”属性定义默认值。这是抽象“字段”类型的一部分(http://symfony.com/doc/2.0/reference/forms/types/field.html)。

$form = $this->createFormBuilder()
            ->add('status', 'choice', array(
                'choices' => array(
                    0 => 'Published',
                    1 => 'Draft'
                ),
                'data' => 1
            ))
            ->getForm();

In this example, 'Draft' would be set as the default selected value.

在本例中,“Draft”将被设置为默认的选定值。

#3


23  

the solution: for type entity use option "data" but value is a object. ie:

解决方案:对于类型实体使用选项“数据”,但值是一个对象。即:

$em = $this->getDoctrine()->getEntityManager();

->add('sucursal', 'entity', array
(

    'class' => 'TestGeneralBundle:Sucursal',
    'property'=>'descripcion',
    'label' => 'Sucursal',
    'required' => false,
    'data'=>$em->getReference("TestGeneralBundle:Sucursal",3)           

))

#4


5  

I think you should simply use $breed->setSpecies($species), for instance in my form I have:

我认为您应该简单地使用$breed->setSpecies($species),例如在我的表单中:

$m = new Member();
$m->setBirthDate(new \DateTime);
$form = $this->createForm(new MemberType, $m);

and that sets my default selection to the current date. Should work the same way for external entities...

这将我的默认选择设置为当前日期。对于外部实体,应该采用同样的方法……

#5


3  

If you want to pass in an array of Doctrine entities, try something like this (Symfony 3.0+):

如果您想要传入一个Doctrine实体数组,可以尝试如下方法(Symfony 3.0+):

protected $entities;
protected $selectedEntities;

public function __construct($entities = null, $selectedEntities = null)
{
    $this->entities = $entities;
    $this->selectedEntities = $selectedEntities;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('entities', 'entity', [
        'class' => 'MyBundle:MyEntity',
        'choices' => $this->entities,
        'property' => 'id',
        'multiple' => true,
        'expanded' => true,
        'data' => $this->selectedEntities,
    ]);
}

#6


2  

I'm not sure what you are doing wrong here, when I build a form using form classes Symfony takes care of selecting the correct option in the list. Here's an example of one of my forms that works.

我不确定您在这里做错了什么,当我使用form类创建一个表单时,Symfony负责选择列表中的正确选项。这是我的一个作品的例子。

In the controller for the edit action:

在控制器中编辑操作:

$entity = $em->getRepository('FooBarBundle:CampaignEntity')->find($id);

if (!$entity) {
throw $this->createNotFoundException('Unable to find CampaignEntity entity.');
}


$editForm = $this->createForm(new CampaignEntityType(), $entity);
$deleteForm = $this->createDeleteForm($id);

return $this->render('FooBarBundle:CampaignEntity:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));

The campaign entity type class (src: Foo\BarBundle\Form\CampaignEntityType.php):

活动实体类型类(src: Foo\BarBundle\Form\ campaign - type .php):

namespace Foo\BarBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;

class CampaignEntityType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
        ->add('store', 'entity', array('class'=>'FooBarBundle:Store', 'property'=>'name', 'em'=>'my_non_default_em','required'  => true, 'query_builder' => function(EntityRepository $er) {return $er->createQueryBuilder('s')->orderBy('s.name', 'ASC');}))
        ->add('reward');
    }
    public function getName()
    {
        return 'foo_barbundle_campaignentitytype';
    }
}

#7


2  

From the docs:

从文档:

public Form createNamed(string|FormTypeInterface $type, string $name, mixed $data = null, array $options = array())

mixed $data = null is the default options. So for example I have a field called status and I implemented it as so:

混合$data = null是默认选项。例如,我有一个名为status的字段,我将它实现如下:

$default = array('Status' => 'pending');

$filter_form = $this->get('form.factory')->createNamedBuilder('filter', 'form', $default)
        ->add('Status', 'choice', array(
            'choices' => array(
                '' => 'Please Select...',
                'rejected' => 'Rejected',
                'incomplete' => 'Incomplete',
                'pending' => 'Pending',
                'approved' => 'Approved',
                'validated' => 'Validated',
                'processed' => 'Processed'
            )
        ))->getForm();

#8


2  

Setting default choice for symfony2 radio button

设置symfony2单选按钮的默认选择。

            $builder->add('range_options', 'choice', array(
                'choices' => array('day'=>'Day', 'week'=>'Week', 'month'=>'Month'),
                'data'=>'day', //set default value 
                'required'=>true,
                'empty_data'=>null,
                'multiple'=>false,
                'expanded'=> true                   
        ))

#9


1  

The form should map the species->id value automatically to the selected entity select field. For example if your have a Breed entity that has a OnetoOne relationship with a Species entity in a join table called 'breed_species':

表单应该将该物种的id值自动映射到所选的实体选择字段。例如,如果您有一个品种实体,它与一个名为“育种物种”的联接表中的物种实体有一个一对一的关系:

class Breed{

    private $species;

    /**
    * @ORM\OneToOne(targetEntity="BreedSpecies", mappedBy="breed")
    */
    private $breedSpecies;

    public function getSpecies(){
       return $breedSpecies->getSpecies();
    }

    private function getBreedSpecies(){
       return $this->$breedSpecies;
    }
}

The field 'species' in the form class should pick up the species->id value from the 'species' attribute object in the Breed class passed to the form.

表单类中的字段“物种”应该从传递给表单的“物种”属性对象中获取该物种->id值。

Alternatively, you can explicitly set the value by explicitly passing the species entity into the form using SetData():

或者,您可以显式地设置值,通过使用SetData()将该物种实体显式地传递到表单中:

    $breedForm = $this->createForm( new BreedForm(), $breed );
    $species   = $breed->getBreedSpecies()->getSpecies();

    $breedForm->get('species')->setData( $species );

    return $this->render( 'AcmeBundle:Computer:edit.html.twig'
                        , array( 'breed'     => $breed
                               , 'breedForm' => $breedForm->createView()
            )
    );

#10


1  

I don't think you should use the data option, because this does more than just setting a default value. You're also overriding any data that's being passed to the form during creation. So basically, you're breaking support for that feature. - Which might not matter when you're letting the user create data, but does matter when you want to (someday) use the form for updating data.

我认为您不应该使用data选项,因为这不仅仅是设置一个默认值。您还将重写在创建过程中传递给表单的任何数据。基本上,你是在打破对这个功能的支持。-当您允许用户创建数据时,这可能并不重要,但是当您希望(某一天)使用表单来更新数据时,这很重要。

See http://symfony.com/doc/current/reference/forms/types/choice.html#data

看到http://symfony.com/doc/current/reference/forms/types/choice.html数据

I believe it would be better to pass any default data during form creation. In the controller.

我相信在表单创建过程中传递任何默认数据会更好。在控制器。

For example, you can pass in a class and define the default value in your class itself. (when using the default Symfony\Bundle\FrameworkBundle\Controller\Controller)

例如,您可以传入一个类并定义类本身的默认值。(使用默认的Symfony\Bundle\FrameworkBundle\Controller\控制器)

$form = $this->createForm(AnimalType::class, [
    'species' => 174 // this id might be substituted by an entity
]);

Or when using objects:

或当使用对象:

$dog = new Dog();
$dog->setSpecies(174); // this id might be substituted by an entity

$form = $this->createForm(AnimalType::class, $dog);

Even better when using a factory: (where dog probably extends from animal)

在使用工厂时更好(狗可能从动物身上延伸)

$form = $this->createForm(AnimalType::class, DogFactory::create());

This will enable you to separate form structure and content from each other and make your form reusable in more situations.

这将使您能够分离表单结构和内容,并使您的表单在更多情况下可重用。


Or, use the preferred_choices option, but this has the side effect of moving the default option to the top of your form.

或者,使用preferred_options选项,但这有将默认选项移动到表单顶部的副作用。

See: http://symfony.com/doc/current/reference/forms/types/choice.html#preferred-choices

见:http://symfony.com/doc/current/reference/forms/types/choice.html首选方式

$builder->add(
    'species', 
    'entity', 
    [
        'class' => 'BFPEduBundle:Item',
        'property' => 'name',
        'query_builder' => ...,
        'preferred_choices' => [174] // this id might be substituted by an entity
     ]
 );

#11


0  

You can either define the right default value into the model you want to edit with this form or you can specify an empty_data option so your code become:

您可以将正确的默认值定义为您想要用该表单编辑的模型,或者您可以指定empty_data选项,以便您的代码成为:

$form = $this
    ->createFormBuilder($breed)
    ->add(
        'species',
        'entity',
        array(
            'class'         => 'BFPEduBundle:Item',
            'property'      => 'name',
            'empty_data'    => 123,
            '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()
;

#12


0  

You can use "preferred_choices" and "push" the name you want to select to the top of the list. Then it will be selected by default.

您可以使用“preferred_choice”和“push”这个名称,您想要在列表的顶部选择。然后它将被默认选中。

'preferred_choices' => array(1), //1 is item number

entity Field Type

实体字段类型