我有这个简单的 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(),
));
}
}
这是搜索实体:
class Search {
protected $query;
public function setQuery($query)
{
$this->query = $query;
}
public function getQuery()
{
return $this->query;
}
}
这是我的表格:
class SearchType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('query', 'text')
->add('search', 'submit');
}
public function getName()
{
return 'search';
}
}
不幸的是在尝试渲染表单时
{% extends '::base.html.twig' %}
{% block body %}
{{ form(form) }}
{% endblock %}
我遇到了这个错误:
在呈现模板期间抛出异常(“可捕获的 fatal error :类 My\ApplicationBundle\Entity\Search 的对象无法转换为字符串
顺便说一句,只渲染 HTML 效果很好。
有什么想法吗?谢谢你的帮助
已解决:我找到了一种解决方法来更改呈现表单的方式:
{{ form_start(form, {'attr': {'class': 'form-search'}}) }}
{{ form_widget(form.query, {'attr': {'class': 'form-control search-query'}}) }}
{{ form_end(form) }}
最佳答案
我想我已经找到了您问题的答案 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)
所以问题可能出在名称 search
本身。然后尝试指定不同的名称。
关于php - symfony2 : error when rendering template - Object could not be converted to string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28740505/