设置"非映射实体字段的默认值"在Symfony 2表格上

时间:2014-12-05 12:49:23

标签: php symfony

我有一个Form类,其中包含一个非映射的实体字段:

->add('client', 'entity', array(
    'class' => 'MyBundle:Client',
    'property' => 'name',
    'empty_value' => 'Select...',
    'query_builder' => function(EntityRepository $er) {
        return $er->createQueryBuilder('c')
            ->orderBy('c.name', 'ASC');
    },
    'mapped' => false,
))
我创建的

$form = $this->createForm(new MyType(),
    $entity,
    array('action' => $this->generateUrl('my_action'))
);

如何设置默认值?尝试了这个,但没有奏效:

'data' => 23423, // id in table 
'data' => 'Client name'
$form->setDefault('client', 'Client name'); // in controller

请注意,这是一个非映射字段。

1 个答案:

答案 0 :(得分:4)

Symfony2 Setting a default choice field selection

@Carrie Kendall回答:

"您需要将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)
        ));
    }
}

在控制器中:

 // ...    

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

// ...