Search code examples
javascriptspring-mvcspring-bootthymeleafpnotify

How to add success notification after form submit


I would like to add success notification after user submitted the form.

I've already checked out the Pnotify js library -https://sciactive.com/pnotify/, which looks nice. But no idea how I can use in my CRUD project. I'm using Spring Boot and Thymeleaf for a frontend.

I checked docs:

<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>

This is my form:

<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>

The notification is showing on click action, in my case I need to show after form submission. Could you advise and share with your expertise? Maybe other alternatives.


Solution

  • Here is an alternative.

    You can follow PRG pattern and use RedirectAttributes to add flash attributes.

    For example:

    @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";
    }
    

    And just show this message in the view rendered by /someGetUrl handler.