Как добавить уведомление об успехе после отправки формы - PullRequest
0 голосов
/ 08 декабря 2018

Я хотел бы добавить уведомление об успехе после того, как пользователь отправил форму.

Я уже проверил библиотеку Pnotify js - https://sciactive.com/pnotify/,, что выглядит неплохо.Но не знаю, как я могу использовать в своем проекте CRUD.Я использую Spring Boot и Thymeleaf для внешнего интерфейса.

Я проверил документы:

<button class="btn btn-default source" onclick="new PNotify({
                              title: 'Regular Success',
                              text: 'That thing that you were trying to do worked!',
                              type: 'success',
                              styling: 'bootstrap3'
                          });">Success</button>

Это моя форма:

<form action="#" th:action="@{/contractors-save}"
    th:object="${contractor}"
    method="post" class="form-horizontal form-label-left">

<div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Name</label>
    <div class="col-md-5 col-sm-5 col-xs-12">
        <input type="text" th:field="*{name}" class="form-control"
                placeholder="name"/>
    </div>
</div>

<div class="form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Description</label>
    <div class="col-md-5 col-sm-5 col-xs-12">
        <input type="text" th:field="*{description}"
                class="form-control"
                placeholder="description"/>
    </div>
</div>

<div class="modal-footer">
    <button type="button" class="btn btn-default"
            data-dismiss="modal">
        Close
    </button>
    <input type="submit" value="Save" class="btn btn-success">
</div>

Уведомление отображается при нажатии кнопки, в моем случае мне нужно показать после отправки формы.Не могли бы вы посоветовать и поделиться своим опытом?Может быть, другие альтернативы.

Ответы [ 2 ]

0 голосов
/ 10 декабря 2018

Я следовал шаблону PRG, как предложил @Minar Mahmud, поделится с моей реализацией:

Контроллер:

@RequestMapping(value = "/contractor-save", method = RequestMethod.POST)
public String saveContractor(@ModelAttribute(value = "contractor") Contractor contractor,
                         RedirectAttributes redirectAttributes) {
    Contractor savedContractor = contractorService.save(contractor);
    redirectAttributes.addFlashAttribute("notification",
        String.format("Contractor \"%s\" successfully saved", savedContractor.getName()));
    redirectAttributes.addFlashAttribute("action", "save");

return "redirect:/contractors";

}

И в HTML-файле, показываяУведомление о загрузке страницы с использованием JavaScript:

<script th:inline="javascript">
$(document).ready(function () {
    var notification = /*[[${notification}]]*/ "";
    var action = /*[[${action}]]*/ "";
    if (action === 'save') {
        new PNotify({
            title: 'Save contractor',
            text: notification,
            type: 'success',
            styling: 'bootstrap3',
            delay: 3000
        });
    } else if (action === 'remove') {
        new PNotify({
            title: 'Remove contractor',
            text: notification,
            type: 'success',
            styling: 'bootstrap3',
            delay: 3000
        });
    } else if (action === 'update') {
        new PNotify({
            title: 'Edit contractor',
            text: notification,
            type: 'success',
            styling: 'bootstrap3',
            delay: 3000
        });
    }
});

Пожалуйста, оставьте комментарий свободным.Я хотел бы знать, нормально ли это для производства?Просто чтобы быть уверенным, что я не изобретаю велосипед.

0 голосов
/ 09 декабря 2018

Вот альтернатива.

Вы можете следовать шаблону PRG и использовать RedirectAttributes для добавления атрибутов флэш.

Дляпример:

@RequestMapping(value = "/contractor", method = RequestMethod.POST)
public String handle(@Valid @ModelAttribute Contractor contractor,
                     BindingResult result,
                     RedirectAttributes redirectAttributes) {

    // Save contactor ...

    redirectAttributes.addFlashAttribute("message", "Successful!");

    return "redirect:/someGetUrl";
}

И просто показать это message в представлении, обработанном обработчиком /someGetUrl.

...