2013-09-05 2 views
44

Vorrei definire un attributo id sui miei moduli symfony2.Attributo id sul tag form symfony

ho provato con questo nel mio modello ramoscello:

{{ form_start(form, {'id': 'form_person_edit'}) }} 

Ma non sembra lavorare.

risposta

85

Hai provato attr?

{{ form_start(form, {'attr': {'id': 'form_person_edit'}}) }} 
+0

thx molto, funziona bene! – wonzbak

+0

Siete i benvenuti! Sentiti libero di contrassegnare la mia risposta come accettata;) – SirDerpington

20

Iniettare l'id nella matrice opzioni che è passato attraverso il costruttore modulo:

public function newAction(Request $request) 
{ 
    // create a task and give it some dummy data for this example 
    $task = new Task(); 
    $task->setTask('Write a blog post'); 
    $task->setDueDate(new \DateTime('tomorrow')); 

    $form = $this->createFormBuilder($task, ['attr' => ['id' => 'task-form']]) 
     ->add('task', 'text') 
     ->add('dueDate', 'date') 
     ->add('save', 'submit', ['label' => 'Create Post']) 
     ->getForm(); 

    return $this->render('AcmeTaskBundle:Default:new.html.twig', [ 
     'form' => $form->createView(), 
    ]); 
} 

O in un tipo di modulo:

class TaskType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('task') 
      ->add('dueDate', null, ['widget' => 'single_text']) 
      ->add('save', 'submit'); 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults([ 
      'data_class' => 'Acme\TaskBundle\Entity\Task', 
      'attr' => ['id' => 'task-form'] 
     ]); 
    } 

    public function getName() 
    { 
     return 'task'; 
    } 
} 
2

Inoltre, devo aggiungere a quanto sopra ha citato le risposte, che puoi farlo nel tuo controller in questo modo:

$this->createForm(FormTypeInterFace, data, options); 

Per un campione, l'ho fatto così:

$this->createForm(registrationType::class, null, array(
    'action' => $this->generateUrl('some_route'), 
    'attr' => array(
     'id' => 'some_id', 
     'class' => 'some_class' 
    ) 
));