Reputation: 1991
I have this simply controller:
class SearchController extends Controller{
public function indexAction(Request $request)
{
$search = new Search();
$form = $this->createForm(new SearchType(), $search);
$form->handleRequest($request);
if ($form->isValid()) {
return $this->redirect($this->generateUrl('search'));
}
return $this->render('MyApplicationBundle:Search:index.html.twig', array(
'form' => $form->createView(),
));
}
}
this is the search entity:
class Search {
protected $query;
public function setQuery($query)
{
$this->query = $query;
}
public function getQuery()
{
return $this->query;
}
}
and this is my form:
class SearchType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('query', 'text')
->add('search', 'submit');
}
public function getName()
{
return 'search';
}
}
unfortunately when trying to render the form
{% extends '::base.html.twig' %}
{% block body %}
{{ form(form) }}
{% endblock %}
I got this error:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class My\ApplicationBundle\Entity\Search could not be converted to string in
BTW, the rendering of just HTML works fine.
any idea? thanks for your help
SOLVED: I found a workaround changing how to render the form:
{{ form_start(form, {'attr': {'class': 'form-search'}}) }}
{{ form_widget(form.query, {'attr': {'class': 'form-control search-query'}}) }}
{{ form_end(form) }}
Upvotes: 3
Views: 2405
Reputation: 8467
I think I've found an answer to your question here.
the method inherited from
AbstractType
will create the name according to the class name which will lead tosearch
. But this will cause issues when rendering as there is a block to render the typesearch
but for the core type. You should set the name explicitly by using a name not used already (a good way is to prefix it by the alias of the bundle)
So the issue could be in the name search
itself. Try specifying different name then.
Upvotes: 1
Reputation: 39390
Every form needs to know the name of the class that holds the underlying data, as described here
You should add the following method to the SearchType
class:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyApplicationBundle\Entity\Search',
));
}
and remember to add the following use
method:
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
Hope this help
Upvotes: 0