I'm building a site-wide search form and I'm having trouble understanding the Symfony2 Forms structure, regarding children forms and error handling.
My code looks like this:
Form Type
class SearchType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('q', 'search', array(
'label' => '',
'attr' => array(),
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\SearchQuery',
'csrf_protection' => false,
));
}
public function getName()
{
return 'search_form';
}
}
Entity (referred as data_class
in the Form Type above)
class SearchQuery
{
/**
* @Assert\NotBlank()
* @Assert\Type(type="string", message="form.search.query.validation.type")
* @Assert\Length(
* min = 3,
* max = 50
* )
*/
protected $q;
public function __construct($q = '')
{
$this->setQ($q);
}
public function __toString() {
return $this->getQ();
}
public function getQ()
{
return $this->q;
}
public function setQ($query)
{
$this->q = $query;
}
}
Controller
$searchForm = $this->createForm(new SearchType());
$searchFormData = array('q' => $q);
$searchForm->submit($searchFormData);
if ($searchForm->isValid()) {
[...]
}
else {
// this returns an empty array regardless there are errors or not
$errors = $searchForm->getErrors();
// this returns errors when they are present
$errorMessages = $searchForm->getErrorsAsString();
}
You might notice on the second line in the controller code, that I'm submitting an array, not a SearchQuery
object. I've tried that and it doesn't come out well, although I expected this to be the right approach.
Digging in the Symfony documentation and questions here on StackOverflow helped me understand that getErrors()
(see it here) never checks children forms and getErrorsAsString()
(see it here) does. So I guessed that that's the reason behind the described behaviour and so it was, my form had a child form.
My question is why is there a child form present and how to get rid of it? What am I doing wrong?
Thanks!