mercredi 22 mars 2017

Getting the selected values from a checkbox list to the controller with Spring Boot

I'm using Spring Boot with Thymeleaf as viewer, and I want to delete all selected items from a table. Therefore, I need to pass to the controller a list with the values from the selected checkboxes.

This is my approach for the controller:

@PostMapping("/admin/rates/prices/delete")
public String delete(@ModelAttribute Rate price, ServletWebRequest request){

    if(request.getParameterValues("idChecked") != null){
        for(String idCheckedStr : request.getParameterValues("idChecked")){
            int idrate = Integer.getInteger(idCheckedStr);
            rateRepository.deleteRate(idrate);
            } 
    }
    return "redirect:/admin/rates/prices";
}

I get a Null Pointer Exception:

java.lang.NullPointerException: null
at com.rentalwebs.controllers.rates.PriceListController.delete(PriceListController.java:42)

I think this method should collet the values::

request.getParameterValues("idChecked")

This is the line at the form, which creates each checkbox with the Thymeleaf annotations:

<input type="checkbox" th:name="idChecked" th:value="${price.idrate}"/>

That's the view code for the form:

<form th:action='@{/admin/rates/prices/delete}'
      method="POST"
      th:object="${rate}">

     <button type="submit" name='delete' value="delete"
             class='btn btn-secondary btn-sm'
             th:text="#{delete}"
             data-toggle="tooltip" data-placement="right"
             th:title="#{delete.selected}">
     </button>

     <p></p>
     <table class='table table-sm responsive'>
           <thead class='thead-default'>
                <tr>
                    <th><input type="checkbox" id="checkAll"/></th>
                    <th th:text='#{from}'></th>
                    <th th:text='#{to}'></th>
                    <th th:text='#{price}'></th>
                </tr>
           </thead>
           <tbody>
                  <tr th:each="price : ${prices}">
                      <td>
                          <input type="checkbox" th:name="idChecked" th:value="${price.idrate}"/>
                      </td>
                      <td th:text="${#temporals.format(price.datefrom, 'dd/MM/yyyy')}"></td>
                      <td th:text="${#temporals.format(price.dateto, 'dd/MM/yyyy')}"></td>
                      <td th:text="${price.price} + '&nbsp; €'"></td>                                        
                  </tr>
           </tbody>
     </table>
</form>

Thank you in advance for your help :-)




Aucun commentaire:

Enregistrer un commentaire