首页 > 解决方案 > Symfony 表单未显示在模板中

问题描述

在 Symfony 3.4 项目中,我刚刚创建了一个新的表单类型ProductSearchType。表单字段未显示在树枝模板中。只有<form>标签,但它们之间没有任何东西。

表格类型:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class, [
            'required' => false,
            'label' => 'Name',
        ])
        ->add('sizes', EntityType::class, [
            'required' => false,
            'label' => 'Bauform',
            'class' => ProductSize::class,
        ])
        ->add('description', TextType::class, [
            'required' => false,
            'label' => 'Beschreibung',
        ])
        ->add('price', EntityType::class, [
            'required' => false,
            'label' => 'Preiskategorie',
            'class' => ProductPrice::class,
        ])
        ->add('booster', EntityType::class, [
            'required' => false,
            'label' => 'Hörverlust',
            'class' => ProductBooster::class,
        ])
        ->add('brand', EntityType::class, [
            'required' => false,
            'label' => 'Marke',
            'class' => ProductBrand::class,
        ]);
}

行动:

public function index(Request $request): Response
{
    $products = $this->getDoctrine()->getRepository(Produkt::class)
        ->findBy([
            'showOnEmptySearch' => true,
        ], [
            'sortOnEmptySearch' => 'asc',
        ]);

    $searchForm = $this->createForm(ProductSearchType::class);
    $searchForm->handleRequest($request);

    $params = [
        'products' => $products,
        'search_form' => $searchForm->createView(),
    ];
    return $this->render('Products/index.html.twig', $params);
}

树枝部分:

{% block template_filter %}
    <h1>
        Suche
    </h1>
    <div class="filter_box">
        {{ form(search_form) }}
    </div>
{% endblock %}

标签: symfonytwig

解决方案


我建议遵循文档。在你的例子中:

$searchForm = $this->createForm(ProductSearchType::class);应该:

$searchForm = $this->createForm(ProductSearchType::class)->getForm();.

也在树枝上;

{{ form_start(search_form) }}
{{ form_widget(search_form) }}
{{ form_end(search_form) }}

这是文档链接。欢迎来到 Stackoverflow。

如果您得到问题的答案,请不要忘记将此答案标记为已接受答案。


推荐阅读