首先,您必须开始创建返回json数据的路由和操作。jQuery的自动完成远程功能为您提供了带有索引“
term ” 的$ _GET variabele,并希望返回JSON。这是一个使用名称为 City 且属性 为$
name 的实体的示例 __
namespace AppBundleController;use SensioBundleframeworkExtraBundleConfigurationRoute;use SymfonyBundleframeworkBundleControllerController;use SymfonyComponentHttpFoundationRequest;use SymfonyComponentHttpFoundationJsonResponse;class CityController extends Controller{ public function autocompleteAction(Request $request) { $names = array(); $term = trim(strip_tags($request->get('term'))); $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('AppBundle:City')->createQueryBuilder('c')->where('c.name LIKE :name')->setParameter('name', '%'.$term.'%')->getQuery()->getResult(); foreach ($entities as $entity) { $names[] = $entity->getName(); } $response = new JsonResponse(); $response->setData($names); return $response; }}其次,您可以像查看jQuery自动完成功能的源代码一样制作树枝视图。唯一的区别是 autocomplete() 函数中的 源
变量。在那里,您必须使用路径键(例如 city_autocomplete ) 指定te Twig 的
path() 函数。 __ __ __
(此视图需要其他路线和其他(正常)操作。)
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>jQuery UI Autocomplete - Remote datasource</title> <link rel="stylesheet" href="//pre.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="//pre.jquery.com/jquery-1.10.2.js"></script> <script src="//pre.jquery.com/ui/1.11.4/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css"> <style> .ui-autocomplete-loading { background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat; } </style> <script> $(function() { function log( message ) { $( "<div>" ).text( message ).prependTo( "#log" ); $( "#log" ).scrollTop( 0 ); } $( "#birds" ).autocomplete({ source: "{{ path('city_autocomplete') }}", minLength: 2, select: function( event, ui ) { log( ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value ); } }); }); </script></head><body><div > <label for="birds">Birds: </label> <input id="birds"></div><div > Result: <div id="log" ></div></div></body></html>最后,您可以稍微更改此视图并使用自己的表单。



