php - symfony2 : error when rendering template - Object could not be converted to string

标签 php symfony

我有这个简单的 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 to search. But this will cause issues when rendering as there is a block to render the type search 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/

相关文章:

mysql - Symfony2 DBAL 更新方法返回 0

javascript - Symfony、grunt、requires.js 和 Assetic

php - 在 web 服务器内置的 php 中运行 symfony 2 项目

php - 我可以将 $_GET 参数传递给本地运行的脚本吗?

ipad - Symfony session 变量在 ipad 中丢失

php - 执行连接数据库和执行数据库查询时出错

javascript - 在每张图片周围添加一个 div,颜色为黑色。 PHP 或 HTML

php - Laravel 响应发送 android APK 文件

php - 如何在 Symfony2 中重新启动 session

symfony - 使用 Phpunit : InvalidArgumentException: Unreachable field 进行功能测试