Autocomplete Endpoint & Serialization Group

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

To get our autocomplete fully working, we need an API endpoint that returns a list of user information - specifically user email addresses. We can do that! Create a new controller for this: AdminUtilityController. Make that extend the normal AbstractController and add a public function getUsersApi(). To make this a real page, add @Route("/admin/utility/users"). And, just to be extra fancy, let's also add methods="GET".

... lines 1 - 10
class AdminUtilityController extends AbstractController
{
/**
* @Route("/admin/utility/users", methods="GET")
*/
public function getUsersApi(UserRepository $userRepository)
{
... lines 18 - 22
}
}

The job of this endpoint is pretty simple: return an array of User objects as JSON: I'm not even going to worry about filtering them by a search term yet.

Add the UserRepository $userRepository argument and fetch every user with $users = $userRepository->findAllEmailAlphabetical(). Finish this with return $this->json() and, it doesn't really matter, but let's set the user objects into a users key.

... lines 1 - 15
public function getUsersApi(UserRepository $userRepository)
{
$users = $userRepository->findAllEmailAlphabetical();
... lines 19 - 22
}

Cool! Copy that URL, open a new tab paste and.... boo! A circular reference has been detected. This is a common problem with the serializer and Doctrine objects. Check it out: open the User class. By default, the serializer will serialize every property... or more accurately, every property that has a getter method.

Serialization Groups to the Rescue

But that means that it's serializing the apiTokens property. And, well, when it tries to serialize that, it notices its user property and so, tries to serialize the User object. You can see the problem. Eventually, before our CPU causes our computer fan to quit & our motherboard to catch on fire, the serializer notices this loop and throws this exception.

What's the fix? Well, the thing is, we don't really want to serialize all of the fields anyway! We really only need the email, but we could also just serialize the same basic fields that we serialized earlier.

Remember: in AccountController, we created an API endpoint that returns one User object. When we did that, we told the serializer to only serialize the groups called main. Look back in the User class. Ah, yes: we used the @Groups() annotation to "categorize" the fields we wanted into a group called main.

In AdminUtilityController, we can serialize that same group. Pass 200 as the second argument - this is the status code - we don't need any custom headers, but we do want to pass a groups option set to main... I know a lot of square brackets to do this.

... lines 1 - 15
public function getUsersApi(UserRepository $userRepository)
{
... lines 18 - 19
return $this->json([
'users' => $users
], 200, [], ['groups' => ['main']]);
}

Now go back and refresh. Got it! We could add a new serialization group to return even less - like maybe just the email. It's up to you.

Adding Security

But no matter what we do, we probably need to make sure this endpoint is secure: we don't want anyone to be able to search our user database. But... hmm.. this is tricky. In ArticleAdminController, the new() endpoint requires ROLE_ADMIN_ARTICLE.

Copy that role, go back to AdminUtilityController and, above the method, add @IsGranted() and paste to use the same role.

... lines 1 - 12
/**
... line 14
* @IsGranted("ROLE_ADMIN_ARTICLE")
*/
public function getUsersApi(UserRepository $userRepository)
... lines 18 - 25

This is a little weird because, in ArticleAdminController, the edit endpoint is protected by a custom voter that allows access if you have that same ROLE_ADMIN_ARTICLE role or if you are the author of this article. In other words, it's possible that an author could be editing their article, but the AJAX call to our new endpoint would fail because they don't have that role!

I wanted to point this out, but we won't need to fix it because, later, we're going to disable this field on the edit form anyways. In other words: we will eventually force the author to be set at the moment an article is created.

Next: let's finish this! Let's hook up our JavaScript to talk to the new API endpoint and then make it able to filter the user list based on the user's input.

Leave a comment!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.1.3",
        "ext-iconv": "*",
        "knplabs/knp-markdown-bundle": "^1.7", // 1.7.0
        "knplabs/knp-paginator-bundle": "^2.7", // v2.8.0
        "knplabs/knp-time-bundle": "^1.8", // 1.8.0
        "nexylan/slack-bundle": "^2.0,<2.2.0", // v2.0.0
        "php-http/guzzle6-adapter": "^1.1", // v1.1.1
        "sensio/framework-extra-bundle": "^5.1", // v5.2.1
        "stof/doctrine-extensions-bundle": "^1.3", // v1.3.0
        "symfony/asset": "^4.0", // v4.1.6
        "symfony/console": "^4.0", // v4.1.6
        "symfony/flex": "^1.0", // v1.2.7
        "symfony/form": "^4.0", // v4.1.6
        "symfony/framework-bundle": "^4.0", // v4.1.6
        "symfony/orm-pack": "^1.0", // v1.0.6
        "symfony/security-bundle": "^4.0", // v4.1.6
        "symfony/serializer-pack": "^1.0", // v1.0.1
        "symfony/twig-bundle": "^4.0", // v4.1.6
        "symfony/validator": "^4.0", // v4.1.6
        "symfony/web-server-bundle": "^4.0", // v4.1.6
        "symfony/yaml": "^4.0", // v4.1.6
        "twig/extensions": "^1.5" // v1.5.2
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.0", // 3.0.2
        "easycorp/easy-log-handler": "^1.0.2", // v1.0.7
        "fzaninotto/faker": "^1.7", // v1.8.0
        "symfony/debug-bundle": "^3.3|^4.0", // v4.1.6
        "symfony/dotenv": "^4.0", // v4.1.6
        "symfony/maker-bundle": "^1.0", // v1.8.0
        "symfony/monolog-bundle": "^3.0", // v3.3.0
        "symfony/phpunit-bridge": "^3.3|^4.0", // v4.1.6
        "symfony/profiler-pack": "^1.0", // v1.0.3
        "symfony/var-dumper": "^3.3|^4.0" // v4.1.6
    }
}