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 ""
For your issue 2, you are confusing the name of the form and the name of the form type. Form types must have unique names, and using an empty one will cause issues (and so is rejected). The form name can be empty: