Skip to content

Instantly share code, notes, and snippets.

@aimeric
Created January 23, 2017 00:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save aimeric/f98af4a3f728bea9e3c9a0918d2a7e2b to your computer and use it in GitHub Desktop.
Save aimeric/f98af4a3f728bea9e3c9a0918d2a7e2b to your computer and use it in GitHub Desktop.
Symfony Ajax live search (autocomplete)
<?php
/* src/AppBundle/Controller/DefaultController */
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Entity;
use AppBundle\Repository\EntityRepository;
class DefaultController extends Controller
{
/**
* Creates a new ActionItem entity.
*
* @Route("/search", name="ajax_search")
* @Method("GET")
*/
public function searchAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$requestString = $request->get('q');
$entities = $em->getRepository('AppBundle:Entity')->findEntitiesByString($requestString);
if(!$entities) {
$result['entities']['error'] = "keine Einträge gefunden";
} else {
$result['entities'] = $this->getRealEntities($entities);
}
return new Response(json_encode($result));
}
public function getRealEntities($entities){
foreach ($entities as $entity){
$realEntities[$entity->getId()] = $entity->getFoo();
}
return $realEntities;
}
}
<?php
/* src/AppBundle/Repository/EntityRepository */
namespace AppBundle\Repository;
/**
* EntityRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class EntityRepository extends \Doctrine\ORM\EntityRepository
{
public function findEntitiesByString($str){
return $this->getEntityManager()
->createQuery(
'SELECT e
FROM AppBundle:Entity e
WHERE e.foo LIKE :str'
)
->setParameter('str', '%'.$str.'%')
->getResult();
}
}
<!DOCTYPE html>
<html>
<!-- app/Resources/views/template.html.twig -->
<head>
<title></title>
</head>
<body>
<div class="sidebar-search">
<div class="input-group custom-search-form">
<input type="text" id="search" class="form-control" placeholder="Suche...">
</div>
<!-- /input-group -->
</div>
<ul class="nav" id="side-menu">
<li>
<a href="#"> Entities<span class="fa arrow"></span></a>
<ul class="nav nav-second-level" id="entitiesNav">
</ul>
</li>
</ul>
</body>
</html>
<!-- jQuery is necessary -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
var searchRequest = null;
$("#search").keyup(function() {
var minlength = 3;
var that = this;
var value = $(this).val();
var entitySelector = $("#entitiesNav").html('');
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "{{ path('ajax_search') }}",
data: {
'q' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
var result = JSON.parse(msg);
$.each(result, function(key, arr) {
$.each(arr, function(id, value) {
if (key == 'entities') {
if (id != 'error') {
entitySelector.append('<li><a href="/daten/'+id+'">'+value+'</a></li>');
} else {
entitySelector.append('<li class="errorLi">'+value+'</li>');
}
}
});
});
}
}
});
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment