Help with autocomplete in Spring mvc and jquery

1

I am using the following:

  • Spring 4.3.5
  • Apache Tomcat 8
  • Hibernate 4.3.1
  • And I have implemented the following:

    My view box.xhtml

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@taglib prefix="spring" uri="http://www.springframework.org/tags"  %>
    <%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>        
        <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
        <title>Gestión de cajas</title>
        <style type="text/css">
            .tg  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
            .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
            .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
            .tg .tg-4eph{background-color:#f9f9f9}
        </style>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
        <script >
            $(function () {
                $("#tagsName").autocomplete({
                    source: function (request, response) {
                        $.getJSON("${pageContext.request.contextPath}/getAnexo.web", {
                            term: request.term
                        }, response);
                    }
                });
            });
        </script>
    
    </head>
    <body>
        <h1>Agregar una Caja</h1>
    
        <c:url var="addAction" value="/caja/add" ></c:url>
    
        <form:form action="${addAction}" commandName="caja" id="registro">
            <table>
                <c:if test="${!empty caja.descripcion}">
                    <tr>
                        <td>
                            <form:label path="idcaja">
                                <spring:message text="ID"/>
                            </form:label>
                        </td>
                        <td>
                            <form:input path="idcaja" readonly="true" size="8"  disabled="true" />
                            <form:hidden path="idcaja" />
                        </td> 
                    </tr>
                </c:if>                    
                <tr>               
                    <td>
                        <form:label path="descripcion">
                            <spring:message text="Descripcion"/>
                        </form:label>
                    </td>
                    <td>
                        <form:input path="descripcion" />
                    </td> 
                </tr>
                <tr>
                    <td>
                        <form:label path="encargado">
                            <spring:message text="Busque Encargado"/>
                        </form:label>
                    </td>
                    <td>                        
                        <form:input path="encargado" id="tagsName" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <c:if test="${!empty caja.descripcion}">
                            <input type="submit"
                                   value="<spring:message text="Editar Caja"/>" />
                        </c:if>
                        <c:if test="${empty caja.descripcion}">
                            <input type="submit"
                                   value="<spring:message text="Agregar Caja"/>" />
                        </c:if>
                    </td>
                </tr>
    
            </table>    
        </form:form>
    
        <h3>Lista de Perfiles</h3>
        <c:if test="${!empty list}">
            <table class="tg"> 
                <tr> 
                    <th width="80">Id</th>                    
                    <th width="200">Descripción</th>
                    <th width="220">Encargado</th>
                    <th width="120">Editar</th>
                    <th width="120">Eliminar</th>
                        <c:forEach items="${list}" var="caja"> 
                    <tr> 
                        <td>${caja.idcaja}</td>                         
                        <td>${caja.descripcion}</td>                         
                        <td>${caja.encargado.nombre}</td>
                        <td><a href="<c:url value='/editc/${caja.idcaja}' />" >Editar</a></td>
                        <td><a href="<c:url value='/removec/${caja.idcaja}' />" >Eliminar</a></td>
                    </tr> 
                </c:forEach> 
            </table>
        </c:if>
    
    
    </body>
    

    My controller boxController.java

    @Controller("cajaController")
    public class CajaController {
    
    @Autowired
    private CajaService cajaserv;
    
    @RequestMapping(value = "/vercajas", method = RequestMethod.GET)
    public String listPersons(Model model) {
        List<Caja> list = cajaserv.getAllCaja();
        model.addAttribute("caja", new Caja());
        model.addAttribute("list", list);
        return "caja";
    }
    
    @RequestMapping(value = "/caja/add", method = RequestMethod.POST)
    public String addPerson(@ModelAttribute("caja") Caja p) {
        cajaserv.crearModificar(p);
        return "redirect:/vercajas";
    }
    
    @RequestMapping("/editc/{idcaja}")
    public String editPerson(@PathVariable("idcaja") int id, Model model) {
        model.addAttribute("caja", cajaserv.getById(id));
        model.addAttribute("list", cajaserv.getAllCaja());
        return "caja";
    }
    
    @RequestMapping("/removec/{idcaja}")
    public String removePerson(@PathVariable("idcaja") int id) {
        Caja p = new Caja();
        p = cajaserv.getById(id);
        cajaserv.eliminar(p);
        return "redirect:/vercajas";
    }
    }
    

    Where autocompleto the person in charge in the view through this call, from AnexoController.java

    @RequestMapping(value = "/getAnexo.web", method = RequestMethod.GET)
    public @ResponseBody
    List<String> getMachedNames(@RequestParam("term") String name) {
        System.out.println("mostrar: "+name);
        List<Anexo> lista = anexoserv.getNames(name);        
        List<String> matchName = new ArrayList<String>();
        for (int i = 0; i < lista.size(); i++) {
            String get = lista.get(i).getNombre()+" "+lista.get(i).getApepat()+" "+lista.get(i).getApemat();
            matchName.add(get);
        }        
        return matchName;
    }
    

    The detail where I need help, is that the list that shows the following, actually shows the name of the manager, but when wanting to save it does not, since I only show as String list, it should show a list of objects Annex type, but I do not know how to implement it.

        
    asked by John Lopez 21.02.2017 в 01:14
    source

    1 answer

    0

    Good John Lopez,

    If I have understood correctly what you would like to send from the front to the back method "save", the object to which the property that appears in the autocomplete belongs. In this way after looking for it, find it and click on the save button, include it in your html table below.

    I see several points to try:

    1- Send the id or object as json to the autocomplete

    Your problem is that when you show the items in the autocomplete you just return the string.

    List<String> getMachedNames(@RequestParam("term") String name)
    

    You return a list of string, no more information (as you say above), you can return a list of objects in JSON, either the whole object or a new model with the name and id of the manager.

    2- Give autocomplete a list of objects with the information we want

    If we do this

     source: function( request, response ) {
        $.ajax({
            dataType: "json",
            type : 'Get',
            url: 'yourURL',
            success: function(data) {
                //data es nuestra list<anexoModel>  
                response( $.map( data, function(item) {
                    return {id: item.id , value: item.nombre   }
                    //por cada elemento en la lista , es decir data 
                    //mapeamos sus propiedades a un objeto plano
                    //Atención este objeto nuevo debe tener dos 
                    //o tres propiedades necesarias para que el 
                    //plugin funcione , pero puedes añadir más propiedades
                    //a cada objeto que luego utilizaremos en el guardado
                }));
            } 
        });
    } ....
    

    We will be saving more properties for each item in the list of plugin items. Then there is a method so that when an element is selected, something specific is done. What we will do, for example, fill in a hidden field with the id of the employee (if we want to send only the id and then make an insert in BD) or the whole object in a variable that we will send as json ...

    Let's save the id for example. For this we add as property of the autocomplete, select

     source: function( request, response ) {
        $.ajax({
            dataType: "json",
            type : 'Get',
            url: 'yourURL',
            success: function(data) {
                //data es nuestra list<anexoModel>  
                response( $.map( data, function(item) {
                    return {id: item.id , value: item.nombre   }
                    //por cada elemento en la lista , es decir data 
                    //mapeamos sus propiedades a un objeto plano
                    //Atención este objeto nuevo debe tener dos 
                    //o tres propiedades necesarias para que el 
                    //plugin funcione , pero puedes añadir más propiedades
                    //a cada objeto que luego utilizaremos en el guardado
                }));
            } 
        });
    },
    select: function(event, ui) {
       //accedemos al item seleccionado
       $('#miCampoIdOcultoQueEnviare').val(ui.item.id);
    }
    

    This way every time we select a manager we get their id and we save it.

    3- Receive the object or its id to be registered in the boxes

    Then you just have to add the id as a parameter, so you can use it to make a new insert with the reference of the id that we are already passing.

    You can send by ajax, by traditional form, receive multiple parameters, use an object in traditional form in this way

    <input name="caja.descripcion"   /> 
    <input name="caja.empleado.nombre"  />
    <input name="caja.empleado.id" /> 
    

    Then just as you do after sending POST you do a re-direction to the same page so that the changes can be seen

     return "redirect:/vercajas";
    

    Wait for a greeting.

        
    answered by 22.02.2017 / 19:50
    source