|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Controller; |
| 4 | + |
| 5 | +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; |
| 6 | +use Symfony\Component\HttpFoundation\JsonResponse; |
| 7 | +use Symfony\Component\HttpFoundation\Request; |
| 8 | +use Symfony\Component\HttpFoundation\Response; |
| 9 | +use Symfony\Component\Routing\Attribute\Route; |
| 10 | + |
| 11 | +#[Route('/test')] |
| 12 | +final class TestAutocompleteController extends AbstractController |
| 13 | +{ |
| 14 | + #[Route('/autocomplete-dynamic-form', name: 'test_autocomplete_dynamic_form')] |
| 15 | + public function dynamicForm(): Response |
| 16 | + { |
| 17 | + return $this->render('test/autocomplete_dynamic_form.html.twig'); |
| 18 | + } |
| 19 | + |
| 20 | + #[Route('/autocomplete/movie', name: 'test_autocomplete_movie')] |
| 21 | + public function movieAutocomplete(Request $request): JsonResponse |
| 22 | + { |
| 23 | + $query = $request->query->get('query', ''); |
| 24 | + |
| 25 | + $movies = [ |
| 26 | + ['value' => 'movie_1', 'text' => 'The Matrix (1999)', 'title' => 'movie Movie #1'], |
| 27 | + ['value' => 'movie_2', 'text' => 'Inception (2010)', 'title' => 'movie Movie #2'], |
| 28 | + ['value' => 'movie_3', 'text' => 'The Dark Knight (2008)', 'title' => 'movie Movie #3'], |
| 29 | + ['value' => 'movie_4', 'text' => 'Interstellar (2014)', 'title' => 'movie Movie #4'], |
| 30 | + ['value' => 'movie_5', 'text' => 'Pulp Fiction (1994)', 'title' => 'movie Movie #5'], |
| 31 | + ]; |
| 32 | + |
| 33 | + $results = array_filter($movies, function ($movie) use ($query) { |
| 34 | + return '' === $query || false !== stripos($movie['text'], $query); |
| 35 | + }); |
| 36 | + |
| 37 | + return $this->json([ |
| 38 | + 'results' => array_values($results), |
| 39 | + ]); |
| 40 | + } |
| 41 | + |
| 42 | + #[Route('/autocomplete/videogame', name: 'test_autocomplete_videogame')] |
| 43 | + public function videogameAutocomplete(Request $request): JsonResponse |
| 44 | + { |
| 45 | + $query = $request->query->get('query', ''); |
| 46 | + |
| 47 | + $games = [ |
| 48 | + ['value' => 'videogame_1', 'text' => 'Halo: Combat Evolved (2001)', 'title' => 'videogame Game #1'], |
| 49 | + ['value' => 'videogame_2', 'text' => 'The Legend of Zelda (1986)', 'title' => 'videogame Game #2'], |
| 50 | + ['value' => 'videogame_3', 'text' => 'Half-Life 2 (2004)', 'title' => 'videogame Game #3'], |
| 51 | + ['value' => 'videogame_4', 'text' => 'Portal (2007)', 'title' => 'videogame Game #4'], |
| 52 | + ['value' => 'videogame_5', 'text' => 'Mass Effect 2 (2010)', 'title' => 'videogame Game #5'], |
| 53 | + ]; |
| 54 | + |
| 55 | + $results = array_filter($games, function ($game) use ($query) { |
| 56 | + return '' === $query || false !== stripos($game['text'], $query); |
| 57 | + }); |
| 58 | + |
| 59 | + return $this->json([ |
| 60 | + 'results' => array_values($results), |
| 61 | + ]); |
| 62 | + } |
| 63 | +} |
0 commit comments