gpt4 book ai didi

jquery - 在 Symfony2 实体字段中添加 JQuery 自动完成

转载 作者:行者123 更新时间:2023-12-03 22:32:31 25 4
gpt4 key购买 nike

我有一个处于一对多关系的城市和选民实体。我想将实体字段(下拉列表中的数千条记录)转换为文本输入,以便我可以在用户开始输入 2 个字母时实现 JQuery 自动完成大约两周后,我成功创建了 DataTransformer,它将实体字段转换为文本输入。现在我的问题是我仍在学习 JQuery/Ajax,我很困惑如何在 Symfony2 表单中实现它。

//formtype.php


private $entityManager;

public function __construct(ObjectManager $entityManager)
{
$this->entityManager = $entityManager;
}
$builder
->add('address', null, array(
'error_bubbling' => true
))
->add('city', 'text', array(
'label' => 'Type your city',
//'error_bubbling' => true,
'invalid_message' => 'That city you entered is not listed',
))
$builder->get('city')
->addModelTransformer(new CityAutocompleteTransformer($this->entityManager));

//datatransformer.php

class CityAutocompleteTransformer implements DataTransformerInterface
{
private $entityManager;

public function __construct(ObjectManager $entityManager)
{
$this->entityManager = $entityManager;
}

public function transform($city)
{
if (null === $city) {
return '';
}

return $city->getName();
}

public function reverseTransform($cityName)
{
if (!$cityName) {
return;
}

$city = $this->entityManager
->getRepository('DuterteBundle:City')->findOneBy(array('name' => $cityName));

if (null === $city) {
throw new TransformationFailedException(sprintf('There is no "%s" exists',
$cityName
));
}

return $city;
}
}

//controller.php

public function createAction(Request $request)
{
$entity = new Voters();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);

$validator = $this->get('validator');
$errors = $validator->validate($entity);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();


$this->addFlash('danger', 'You are successfully added!, Welcome to the growing Supporters, dont forget to share and invite this to your friends and relatives, click share buttons below, have a magical day!');

//return $this->redirect($this->generateUrl('voters_show', array('id' => $entity->getId())));
return $this->redirect($this->generateUrl('voters_list'));
} else {

$this->addFlash('danger', 'Oppss somethings went wrong, check errors buddy!');

return $this->render('DuterteBundle:Voters:neww.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
}

/**
* Creates a form to create a Voters entity.
*
* @param Voters $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Voters $entity)
{
$entityManager = $this->getDoctrine()->getManager();
$form = $this->createForm(new VotersType($entityManager), $entity, //here i passed the entity manager to make it work
array(
'action' => $this->generateUrl('voters_create'),
'method' => 'POST',
));

$form->add('submit', 'submit', array(
'label' => 'I Will Vote Mayor Duterte'
));

return $form;
}

使用此代码,我可以成功创建一个新选民,并且当用户输入的城市名称与数据库中已保存的名称不匹配时,我会抛出验证错误(formtype 中的invalid_message)。我现在缺少的是我想要的当用户输入至少两个字母时实现 JQuery 自动完成

Twig 部分

//twig.php

{{ form_start(form, {attr: {novalidate: 'novalidate'}} ) }}
{{ form_errors(form) }}
{{ form_row(form.comments,{'attr': {'placeholder': 'Why You Want '}}) }}
{{ form_row(form.email,{'attr': {'placeholder': 'Email is optional, you may leave it blank.But if you want to include your email, make sure it is your valid email '}}) }}
{{ form_end(form) }}

enter image description here

正如您所看到的,除了城市字段之外,表单本身由许多字段组成。这里,城市字段是一个下拉列表,由数据库中的一千多个条目组成。我可以成功地将这个下拉列表转换为文本字段使用DataTransformer。所以这里的问题是如何在这个具有许多字段的表单中实现JQuery Autocomplete。

感谢任何帮助

更新

根据用户 Frankbeen 的回答,我在 Controller 中添加了一个操作

public function autocompleteAction(Request $request)
{
$names = array();
$term = trim(strip_tags($request->get('term')));

$em = $this->getDoctrine()->getManager();

$entities = $em->getRepository('DuterteBundle:City')->createQueryBuilder('c')
->where('c.name LIKE :name')
->setParameter('name', '%'.$term.'%')
->getQuery()
->getResult();

foreach ($entities as $entity)
{
$names[] = $entity->getName()."({$entity->getProvince()})";
}

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

return $response;
}

还有js文件

{% block javascripts %}
{{ parent() }}
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}

$( "#project_bundle_dutertebundle_voters_city").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>
{% endblock %}

在这种情况下,

  $( "#project_bundle_dutertebundle_voters_city").autocomplete({

部分实际上是Symfony2在渲染表单时提供的城市字段的默认ID。JQuery自动完成现在可以工作,但问题是,我无法保存所选选项,触发了我在FormType.php中创建的invalid_message验证以及单击提交按钮时的 JQuery 脚本

Selected: Basista (Pangasinan Province) aka undefined

这表明所选值的 Id 未定义

$( "#project_bundle_dutertebundle_voters_city").autocomplete({
source: "{{ path('city_autocomplete') }}",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id ://this throw undefined
"Nothing selected, input was " + this.value );
}
});

最佳答案

首先,您必须开始创建返回 json 数据的路由和操作。 JQuery's autocomplete remote为您提供一个带有索引“term”的 $_GET 变量,并希望接收返回的 JSON。以下示例使用名称为 City 的实体和属性 $name

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
* City controller.
*
* @Route("/city")
*/
class CityController extends Controller
{
/**
* @Route("/autocomplete", name="city_autocomplete")
*/
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;
}
}

其次,您可以创建一个 Twig View ,就像 jQuery 自动完成的源代码一样。唯一的区别是 autocomplete() 函数中的 source 变量。在那里,您必须使用路线键指定 twig 的 path() 函数,例如 city_autocomplete

(此 View 需要另一条路线和另一条(正常)操作。)

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Remote datasource</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.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 class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>

<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>


</body>
</html>

最后,您可以稍微更改此 View 并使用您自己的表单。

关于jquery - 在 Symfony2 实体字段中添加 JQuery 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32334289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com