我想用 symfony 创建一个搜索表单 我首先创建一个表单(Form/SearchType.php) 然后在控制器中渲染它(SearchController.php) 然后将渲染发送给查看器以显示表单 (部分/Header.html.twig) 但我收到此错误:变量“form”不存在。 预先感谢
Header.html.twig:
<header class="hero-header">
<h1 class="hero-title">
Désigner.<br>Coder.<br>Assembler.
</h1>
<p class="hero-subtitle">
DevPlanTech : Où Passion et Technologie Se Rencontrent - Explorez les Dernières Tendances, Trouvez les Meilleurs Bons Plans, et Maîtrisez l'Art du Dev et du Design
</p>
<div class="search-box">
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</div>
</header>
表单/SearchType.php:
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SearchType as FormSearchType;
use Symfony\Component\Form\FormBuilderInterface;
class SearchType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('q', FormSearchType::class, [
'label' => false,
'attr' => [
'placeholder' => 'Recherchez un article',
'aria-label' => 'Recherchez un article'
]
]);
}
}
SearchController.php:
<?php
namespace App\Controller;
use App\Form\SearchType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use App\Repository\ArticlesRepository;
class SearchController extends AbstractController
{
#[Route('/search', name: 'search')]
public function search(Request $request, ArticlesRepository $articlesRepository): Response
{
$form = $this->createForm(SearchType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$searchText = $form->get('q')->getData();
$articles = $articlesRepository->findByKeywordInTitle($searchText);
return $this->render('partials/search_results.html.twig', [
'searchText' => $searchText,
'articles' => $articles,
]);
}
return $this->render('partials/Header.html.twig', [
'form' => $form->createView(),
]);
}
}
{{ form_widget(form.q) }}
尽管在这个简单的情况下,您可以将所有三个 Twig 线替换为
{{ form(form) }}