Reputation: 47
I want to use a form_widget to render a field for a collectionType form. Here is my controller :
/**
* @Route("/ticket", name="ticket")
*/
public function ticket(Request $request)
{
$data = $request->getSession()->get('orders');
$number = $data->getNumberOfTickets();
for ($i=1; $i<=$number ;$i++){
$tickets[] = new Tickets();
}
$form = $this->createForm(CollectionType::class, $tickets, ['entry_type' => TicketsType::class] );
$form->handleRequest($request);
dump($request);
return $this->render('louvre/ticket.html.twig', [
'tickets' =>$tickets,
'form' => $form->createView()
]);
}
and when i try :
{{ form_widget(tickets.firstname)}}
or
{{ form_widget(form.firstname)}}
or
{{ form_widget(form.tickets.firstname)}}
I have an error :
Neither the property "firstname" nor one of the methods "firstname()", "getfirstname()"/"isfirstname()"/"hasfirstname()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".
Here is my form :
class TicketsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('category', CheckboxType::class, [
'attr' => [
'class' => 'form-control'
]
])
->add('firstname', TextType::class, [
'attr' => [
'class' => 'form-control'
]
])
->add('lastname', TextType::class, [
'attr' => [
'class' => 'form-control'
]
])
->add('country', TextType::class, [
'attr' => [
'class' => 'form-control'
]
])
->add('dateOfBirth', DateType::class, [
'attr' => [
'class' => 'form-control'
],
'widget' => 'single_text',
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Tickets::class,
]);
}
}
Upvotes: 0
Views: 3053
Reputation: 649
You might want to add the code of the entity to your question: Tickets.php
In Tickets.php you probably define the class Tickets and in that class you probably don't have any of the methods listed in the error message. Adding this method with the exact name should help:
public function getfirstname() {
return $this->firstname;
}
About the twig code: you might want to add some more to the question. For example, do you have {{ form_start(form) }}
or something else in the beginning?
Then as it is a CollectionType, you probably want to render some input field for each of the members in the collection. Maybe something like this:
{% for ticket in form.tickets %}
<div class="ticket">{{ form_widget(ticket.firstname) }}</div>
{% endfor %}
Upvotes: 0
Reputation: 47
To render a field I just need to use the prototype in twig:
{{ form_widget(form.vars.prototype.firstname) }}
and add this in my form method, in my controller:
'allow_add' => true
Upvotes: 1