27/09/2016 - SYMFONY
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.
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>
<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') }}" />
/**
* @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;
}
public function suggestUsers($term)
{
$users = $this->userRepository->findLimitedBySearchTermOnId($term);
if ($users) {
$users = array_map('current', $users);
}
return $users;
}
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);
}
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
)
)