-2

I need to send data array from Controller, but i don't know what is the good way. I think the controller should send the array in json. This is my js code:

 $.typeahead({
        input: '[data-autocomplete="team"]',
        minLength: 1,
        order: "asc",
        offset: true,
        hint: true,
        source: {
             items: {
                 data: [here, i need to get array data from controller]
                 ajax: {
                     type: "POST",
                     url: "/teams",
                     data: {
                         myKey: $('[data-autocomplete="team"]').val()
                     }
                 }
             }
         },
    });

and this is my controller

    /**
     * @Route(name="teams", path="/teams")
     */
    public function sendTeams()
    {
        $em = $this->getDoctrine()->getManager();
        $teams = $em->getRepository(Teams::class)->findAll();
        $data = [];
        foreach($teams as $team){
           $data[] = $team->getName();
        }

        return new JsonResponse($data, 200, [], true);
    }
user3461461
  • 306
  • 2
  • 3
  • 16

1 Answers1

1

Using a JsonReponse is a proper solution.

But there is multiple way your code could be improved.

If your project is configured with the default autowiring options, you could auto wire your repository (which by the way would have been better if called TeamRepository associated to a Team entity instead of Teams):

/**
 * @Route(name="teams", path="/teams")
 */
public function sendTeams(TeamsRepository $teamsRepository)
{
    $teams = $teamsRepository->findAll();
    $data = [];
    foreach($teams as $team){
       $data[] = $team->getName();
    }

    return new JsonResponse($data, 200, [], true);
}

You should also not set the bool $json parameter of JsonResponse since $data is not a json but an array that you want to be converted into a json. Using a JsonResponse will return a proper JsonResponse with json headers, the bool $json parameter just help converting a php variable into a json (if possible).

/**
 * @Route(name="teams", path="/teams")
 */
public function sendTeams(TeamsRepository $teamsRepository)
{
    $teams = $teamsRepository->findAll();
    $data = [];
    foreach($teams as $team){
       $data[] = $team->getName();
    }

    return new JsonResponse($data);
}

You could also simplify your foreach (The arrow key function is php 7.4+, use a regular callable otherwise):

/**
 * @Route(name="teams", path="/teams")
 */
public function sendTeams(TeamsRepository $teamsRepository)
{
    $teams = $teamsRepository->findAll();
    $data = array_map(fn($e) => $e->getName(), $teams);

    return new JsonResponse($data);
}

It depends of you, but you could also use FOSJsRoutingBundle to not write manually the path to your teams route. You can check how to use it if you want.

Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
  • thanks for the improvements, I am going to apply them, however, something is wrong between the controller and the javascript, as it is not working correctly... if I hardcode the array in the javascript it works fine, but through the controller, it is not working. – user3461461 Nov 03 '21 at 11:45
  • There should be an issue with how you receive your data in your javascript. You could try to check your url to see if you get the proper json (**url.com/teams**). – Dylan KAS Nov 03 '21 at 11:57
  • https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md The documentation seems to say that you need to use `asyncResults ` with ajax Request – Dylan KAS Nov 03 '21 at 12:01
  • you were right, thank you very much for the help – user3461461 Nov 03 '21 at 12:04