2014-12-05 13 views
5

Ho una classe Form con un campo non mappato entità in esso:valori di default impostata per un "campo non mappato entità" in un form Symfony 2

->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, 
)) 

che creo come questo:

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

Come posso impostare il suo valore predefinito? provato questo, ma non lavorato:

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

Si prega di notare che si tratta di un campo non mappato.

risposta

3

Symfony2 Setting a default choice field selection

@Carrie Kendall risposta:

"Avrai bisogno di iniettare l'EntityManager nella tua classe FormType Ecco un esempio semplificato:."

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

In controllore:

// ...  

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

// ... 
+0

Ha funzionato. Grazie. –

Problemi correlati