简体   繁体   中英

get id from another table in javascript modal

Hello, good afternoon. I wanted to see how to get the id of the roles in this case, I can retrieve all the user data in my modal. But I can't get the role back since it belongs to another table and when I ask for it, it brings me the whole table. Since I use a many-to-many relationship

This is my js

   $('.table .editBtn').on('click', function (event) {

        event.preventDefault();
        var href = $(this).attr('href');

        $.get(href, function (usuario) {
            $('.myForm #idUsuarioEdit').val(usuario.idUsuario);
            $('.myForm #nombreEdit').val(usuario.nombre);
            $('.myForm #apellidoEdit').val(usuario.apellido);
            $('.myForm #emailEdit').val(usuario.email);
            $('.myForm #rolesEdit').val(usuario.roles);
        });
        $('.myForm #editModal').modal();
    });

This is my controller

@GetMapping("/editarUsuario")
@ResponseBody
public Usuario editarUsuario(Model model, long idUsuario) throws Exception {

    model.addAttribute("listaUsuarios", usuarioService.getAllUsers());
    model.addAttribute("roles", rolDao.findAll());

    return usuarioService.getUsuarioById(idUsuario);
}

This is my html button

    <table id="listaUsuarios" class="table table-bordered table-hover table-striped">
        <thead class="thead-dark">
            <tr>
                <th scope="col">#</th>
                <th scope="col">Nombre</th>
                <th scope="col">Apellido</th>
                <th scope="col">E-mail</th>
                <th scope="col"></th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="usuario : ${listaUsuarios}">
                <td th:text="${usuario.idUsuario}"></td>
                <td th:text="${usuario.nombre}"></td>
                <td th:text="${usuario.apellido}"></td>
                <td th:text="${usuario.email}"></td>
                <td><div class="text-center">
                        <span th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')} or (${#authorization.expression('hasRole(''ROLE_USER'')')} and ${#httpServletRequest.remoteUser==usuario.email})">
                            <a class="btn btn-success editBtn" th:href="@{editarUsuario/(idUsuario=${usuario.idUsuario})}">Editar <i class="fas fa-edit"></i></a>
                        </span> 
                        <span th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}">   |   
                            <a class="btn btn-danger" href="#" th:onclick="'javascript:confirmaEliminar(\''+ ${usuario.idUsuario} +'\');'">Eliminar <i class="fas fa-user-times"></i></a>
                        </span>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>

This is my modal

<div class="myForm">
    <form th:object="${editarUsuario}" th:action="@{/editarUsuario}" method="post">
        <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalTitle" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLongTitle">Editar usuario</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <input class="form-control" type="hidden" id="idUsuarioEdit" name="idUsuario" />
                        </div>
                        <div class="form-group">
                            <label class="col-form-label" for="nombre">Nombre:</label>
                            <input class="form-control" type="text" id="nombreEdit" name="nombre" required />
                        </div>
                        <div class="form-group">
                            <label class="col-form-label" for="apellido">Apellido:</label>
                            <input class="form-control" type="text" id="apellidoEdit" name="apellido" required />
                        </div>
                        <div class="form-group">
                            <label class="col-form-label" for="email">E-mail:</label>
                            <input class="form-control" type="text" id="emailEdit" name="email" required />
                        </div>
                        <div class="form-group">
                            <label class="col-form-label" for="rol">Rol:</label>
                            <input class="form-control" type="text" id="rolesEdit" name="roles" required />
                            <!--<select class="form-control" id="rolesEdit" name="rol">
                                <option th:each="rol :${roles}" th:value="${rol.idRol}" th:text="${rol.nombre}"></option>
                            </select>-->
                        </div>
                        <!-- <div class="form-group">
                             <label class="col-form-label" for="rol">Rol:</label>
                             <select class="form-control" id="rolesEdit" name="roles">
                                 <option th:each="rol :${roles}" th:value="${rol.idRol}" th:text="${rol.nombre}"></option>
                             </select>
                         </div>
                         ERROR MESSAGE
                         <div class="content">
                             <div style="text-align: center;" class="alert-danger-registro" th:if="${formErrorMessage}" th:text="${formErrorMessage}">Error Message</div>
                        -->
                    </div>
                    <!--FOOTER-->
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                        <input type="submit" class="btn btn-primary" value="Guardar cambios"/>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

And.. my method for edit user

//metodo editar usuario
@Override
public Usuario editarUsuario(Usuario fromUser) throws Exception {
    Usuario toUser = getUsuarioById(fromUser.getIdUsuario());
    mapUser(fromUser, toUser);
    return usuarioDao.save(toUser);
}

//Mapeamos todo menos el password.
protected void mapUser(Usuario from, Usuario to) {
    to.setNombre(from.getNombre());
    to.setApellido(from.getApellido());
    to.setEmail(from.getEmail());
    to.setRoles(from.getRoles());
}

currently this is what i receive: modal edit

I've been trying for a long time but I can't receive the role id, thanks. Greetings

Try to explain where is the real problem, do you use some library or framework? You may try to find about how to join tables using the lib or the framework you are currently using. Or you just have to return the roles you have fetched with the user data, something like:

const allRoles = //fetch roles
const userInfo = //fetch user info
return {userData: userInfo, roles: allRoles}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM