Как я могу заполнить значение в форме внутри модального с использованием Bootstrap и thymeleaf? - PullRequest
0 голосов
/ 22 мая 2018

В моем весеннем загрузочном проекте у меня есть страница html, которая содержит список студентов.На этой странице у меня есть два варианта Edit и Delete для каждого студента.Я хочу показывать значение в модальном для каждой информации о студенте, когда я нажимаю Edit.Но я не могу этого сделать.Еще одна странная вещь - каждый раз, когда я нажимаю на любой Edit, форма заполняет только первого члена списка.Возможно, мне придется добавить код JavaScript или что-то еще.Вот скриншот страницы со списком учеников ![enter image description here] 1

Мой html файл

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml" xmlns:sf="http://www.w3.org/1999/xhtml" lang="en">
<head>
    <title>Student List</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<script th:if="${existRoll != null}">
    $(function () {
        $('#myModal').modal('show');
    });
</script>

<body>
<div class="container">

        <h1 style="text-align:center;">Students List</h1>
        <table class="table table-striped">
            <tr>
                <th>Id</th>
                <th>Roll</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Age</th>
                <th>Setting</th>
            </tr>

            <tr th:each="student : ${studentList}">
                <td th:text="${student.id}"></td>
                <td th:text="${student.roll}"></td>
                <td th:text="${student.firstName}"></td>
                <td th:text="${student.lastName}"></td>
                <td th:text="${student.age}"></td>
                <td>
                    <button type="button"
                            class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Edit
                    </button>

                    <div class="modal fade" id="myModal" role="dialog">
                        <div class="modal-dialog">

                            <!-- Modal content-->
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal">&times;</button>

                                </div>
                                <div class="modal-body">


                                    <!--Form code start from here  -->


                                    <!-- Form Name -->
                                    <legend>Registration Form</legend>

                                    <form class="form-horizontal" action="#" th:action="@{/doRegistration}"
                                          method="post">
                                        <fieldset>

                                            <div class="form-group">
                                                <label class="col-md-4 control-label" for="roll">Roll</label>
                                                <div class="col-md-4">

                                                    <input id="id" path="id" name="id" type="hidden"
                                                           placeholder="id" class="form-control input-md"
                                                           th:value="${student.id}"/>

                                                    <input id="roll" path="roll" name="roll" type="text"
                                                           placeholder="Roll" class="form-control input-md"
                                                           th:value="${student.roll}"/>

                                                    <span th:if="${existRoll !=null}" style="color:Red;"> Already Exist !</span>
                                                </div>
                                            </div>


                                            <!-- Text input-->
                                            <div class="form-group">
                                                <label class="col-md-4 control-label" for="firstName">First Name</label>
                                                <div class="col-md-4">
                                                    <input id="firstName" path="firstName" name="firstName"
                                                           type="text" placeholder="firstName"
                                                           class="form-control input-md" th:value="${student.firstName}"
                                                    />
                                                </div>
                                            </div>


                                            <!-- Text input-->
                                            <div class="form-group">
                                                <label class="col-md-4 control-label" for="lastName">Last Name
                                                </label>
                                                <div class="col-md-4">
                                                    <input id="lastName" path="lastName" name="lastName"
                                                           type="text" placeholder="lastName"
                                                           class="form-control input-md"
                                                           th:value="${student.lastName}"/>
                                                </div>
                                            </div>


                                            <!-- Text input-->
                                            <div class="form-group">
                                                <label class="col-md-4 control-label" for="age">Age
                                                </label>
                                                <div class="col-md-4">
                                                    <input id="age" path="age" name="age"
                                                           type="text" placeholder="age" class="form-control input-md"
                                                           th:value="${student.age}"/>
                                                </div>
                                            </div>


                                            <!-- Text input-->
                                            <div class="form-group">
                                                <label class="col-md-4 control-label" for="pass">Password</label>
                                                <div class="col-md-4">
                                                    <input id="pass" path="pass" name="pass"
                                                           type="password" placeholder="password"
                                                           class="form-control input-md"
                                                           th:value="${student.pass}"/>
                                                </div>
                                            </div>

                                            <!-- Button -->
                                            <div class="form-group">
                                                <label class="col-md-4 control-label" for="register"></label>
                                                <div class="col-md-4">
                                                    <button id="register" name="register" class="btn btn-primary">
                                                        Register
                                                    </button>
                                                </div>
                                            </div>

                                        </fieldset>
                                    </form>

                                </div>

                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                </div>


                            </div>

                        </div>
                    </div>


                    <a th:href="@{/deleteStudent/(id=${student.id})}"
                       onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>
                </td>
            </tr>

        </table>
    </div>

</body>
</html>

И весь мой Controller класс

package org.avijit.Controller;


import org.avijit.Entity.Student;
import org.avijit.Service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


@Controller
public class StudentController {

    @Autowired
    StudentService studentService;

    @RequestMapping(value = "/logForm", method = RequestMethod.GET)
    public String gotoHome() {
        return "Login";
    }

    @RequestMapping(value = "/loginCheck", method = RequestMethod.POST)
    public String checkLogin(@RequestParam String roll, @RequestParam String pass, Model model) {
        if (studentService.existsByRollAndPass(roll, pass)) {
            return "Welcome";
        } else {
            model.addAttribute("logError", "logError");
            return "Login";
        }
    }


    @RequestMapping(value = "/registration")
    public String registration(Model model) {
        model.addAttribute(new Student());
        return "Registration";
    }

    @RequestMapping(value = "/getStudents")
    public String getStudents(Model model) {
        List<Student> studentList = studentService.getStudents();
        model.addAttribute(studentList);
        return "StudentList";
    }

    @RequestMapping(value = "/deleteStudent", method = RequestMethod.GET)
    public String deleteStudent(@RequestParam(name = "id") int id) {
        studentService.deleteStudent(id);
        return "redirect:/getStudents";
    }

    @RequestMapping(value = "/editStudent/{id}", method = RequestMethod.GET)
    public String editStudent(@PathVariable("id") int id, Model model) {
        Student student = studentService.getStudent(id);
        model.addAttribute("student", student);
        return "StudentList";
    }



    @RequestMapping(value = "/demo")
    public String demoRegistration(Model model) {
        model.addAttribute(new Student());
        return "DemoRegistration";
    }

    @RequestMapping(value = "/doRegistration", method = RequestMethod.POST)
    public String doRegistration(@Valid @ModelAttribute("student") Student student, BindingResult result, Model model) {
        if (result.hasErrors()) {
            model.addAttribute("hasError", true);
            return "DemoRegistration";
        } else {
            if (student.getId() == null && !studentService.rollExist(student.getRoll())) {
                studentService.saveStudent(student);
                return "Welcome";
            } else if (student.getId() == null && studentService.rollExist(student.getRoll())) {
                model.addAttribute("existRoll", "existRoll");
                model.addAttribute("hasError", true);
                return "DemoRegistration";
            } else {
                Student student1 = studentService.getStudent(student.getId());
                if (student1.getId() != null && !student1.getRoll().equals(student.getRoll()) && studentService.rollExist(student.getRoll())) {
                    model.addAttribute("hasError", "hasError");
                    model.addAttribute("existRoll", "existRoll");
                    return "redirect:/getStudents";
                } else {
                    student1.setFirstName(student.getFirstName());
                    student1.setLastName(student.getLastName());
                    student1.setRoll(student.getRoll());
                    student1.setAge(student.getAge());
                    student1.setPass(student.getPass());
                    studentService.saveStudent(student1);
                    return "redirect:/getStudents";
                }
            }
        }
    }

}

1 Ответ

0 голосов
/ 23 мая 2018

Потратив 1 час в стеке, я наконец нашел решение.Я немного изменил свой HTML-код

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Edit </button>

до

 <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" th:attrappend="data-target=${student.id}">Edit </button>

и <div class="modal fade" id="myModal" role="dialog"> до

<div class="modal fade" id="myModal" role="dialog" th:attrappend="id=${student.id}">

Теперь все работает нормально!

...