Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

In this example, we'll implement auto-suggestion feature while typing an user id in a textbox. It will query only id field and suggest us relevant IDs to choose from.

Assuming that you have at least basic knowledge about symfony so I'm going to cut this example short.


Javascript and HTML parts


Javascript


Search starts as soon as you start typing which can be controlled with minLength option.


<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<script>
$(function() {
$('#user_id').autocomplete({
source: function(request, response) {
$.getJSON(
$('#suggest_user_endpoint').val(),
{
term: $('#user_id').val().trim()
},
response
);
},
minLength: 1
});
});
</script>

HTML


<div class="ui-widget">
<input type="text" id="user_id" name="user_form" />
</div>

<input type="hidden" id="suggest_user_endpoint" value="{{ path('suggest_users') }}" />

Controller


/**
* @param Request $request
*
* @Route("/suggest-users", name="suggest_users")
* @Method("GET")
*
* @return JsonResponse
*/
public function suggestUsersAction(Request $request)
{
$term = $request->query->get('term');
$users = null;

if ($term) {
$users = $this->userService->suggestUser($term);
}

$response = new JsonResponse();
$response->setData($users);

return $response;
}

Service


public function suggestUsers($term)
{
$users = $this->userRepository->findLimitedBySearchTermOnId($term);
if ($users) {
$users = array_map('current', $users);
}

return $users;
}

Repository


public function findLimitedBySearchTermOnId($idPrefix, $limit = 10)
{
return $this->createQueryBuilder('u')
->select('u.id')
->andWhere('u.id LIKE :idPrefix')
->setParameter('idPrefix', $idPrefix.'%')
->setMaxResults($limit)
->getQuery()
->getResult(DoctrineQuery::HYDRATE_SCALAR);
}

Example response


Assuming that you typed e2c in search textbox. As a result, you should get response like below.


Array
(
[0] => Array
(
[id] => e2c000-111-222-333
)
[1] => Array
(
[id] => e2c999-444-555-666
)
)