Create unnamed forms. While dealing with GET requests, I expect my query string to be like:
/page?page=1&results_per_page=50
This means I need to define a form like this one:
<?php
namespace Acme\DemoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PaginationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('page', 'text', array(
'empty_data' => 1,
'required' => false,
'property_path' => 'currentPage',
))
->add('results_per_page', 'text', array(
'empty_data' => 50,
'required' => false,
'property_path' => 'resultsPerPage',
));
}
public function getName()
{
return '';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Form\Model\Pagination',
'required' => true,
));
}
}
The only allowed way to create an unamed form is by doing:
$form = $this->createForm(new PaginationType(), new Pagination());
Any attempt to define it as part of DIC such as:
services:
acme_demo.form.type.pagination:
class: 'Acme\DemoBundle\Form\Type\PaginationType'
tags:
- { name: 'form.type', alias: 'acme_demo_pagination' }
And when I try to consume it as a string by using its alias such as:
$form = $this->createForm('acme_demo_pagination', new Pagination());
Or even:
$form = $this->formFactory->createNamedBuilder('', 'acme_demo_pagination', new Pagination())->getForm();
You'll always get this error:
The type name specified for the service "acme_demo.form.type.pagination" does not match the actual name. Expected "acme_demo_pagination", given ""
@stof Sorry, but you may not have understood what I wrote there.
When
$form->isValid()is called, it called forgetErrors(), but it skips any constraints violation that were added to the child Form because the submitted data does not contain the key for that child submission. This turns the$form->isSubmitted()to return false and then error checking gets skipped, leading$form->isValid()to return true.I highlighted the exact place where this happens.