Ger
Ger

Reputation: 649

Spring boot + Thymeleaf - Object with id null when editing

When you select an Expense object from the data table for editing, the edit method in the controller sends the Expense object to the edit screen that is the same to insert a new record. When the object is sent to the save method, it has nullo code attribute where an insert occurs instead of an update. I do not understand why.

Controller

@Controller
@RequestMapping("/despesas")
public class DespesaController {

    @Autowired private DespesaService despesaService;
    @Autowired private DespesaRepository despesaRepository;

    @GetMapping("/add")
    public ModelAndView novo(Despesa despesa) {
        ModelAndView model = new ModelAndView("page/cadastro/despesa/cadDespesa");
        model.addObject("tiposDespesa", TipoDespesa.values());
        model.addObject("formasPagamento", FormaPagamento.values());
        model.addObject(despesa);
        return model;
    }

    @PostMapping("/save")
    public ModelAndView salvar(Despesa despesa, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            return novo(despesa);
        }
        despesa.setDataDespesa(new Date());
        despesaService.salvarDespesa(despesa);
        attributes.addFlashAttribute("mensagem", "Despesa Salva com Sucesso!");
        return new ModelAndView("redirect:/cadastroDespesa");
    }

    @GetMapping("/listDespesa")
    public ModelAndView listagemDeDespesas() {
        ModelAndView model = new ModelAndView("page/cadastro/despesa/listDespesa");
        model.addObject("despesas", despesaRepository.findAll());
        return model;
    }

    @GetMapping("/edit{id}")
    public ModelAndView editar(@PathVariable("id") Long codigo) {
        return novo(despesaRepository.findOne(codigo));
    }
}

FormEdit

<form th:object="${despesa}" method="POST" th:action="@{/despesas/save}">
 <div class="box-body">
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label>Data</label>
                <div class="input-group">
                    <div class="input-group-addon">
                        <i class="fa fa-calendar"></i>
                    </div>
                    <input type="text" th:field="*{dataDespesa}" class="form-control" disabled="disabled">
                </div>
            </div>
            <div class="form-group">
                <label>Valor</label>
                <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-dollar"></i></span>
                    <input type="text" th:field="*{valor}" class="form-control">
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label>Tipo Despesa</label> 
                    <select class="form-control select2" th:field="*{tipoDespesa}" style="width: 100%;">
                    <option th:each="tipo : ${tiposDespesa}" th:value="${tipo}" th:text="${tipo}"></option>
                </select>
            </div>
            <div class="form-group">
                <label>Forma Pagamento</label> 
                    <select class="form-control select2" th:field="*{formaPagamento}" style="width: 100%;">
                    <option th:each="forma : ${formasPagamento}" th:value="${forma}" th:text="${forma}"></option>
                </select>
            </div>
        </div>

        <div class="col-md-12">
            <div class="form-group">
                <label>Observação</label> 
                <input type="text" th:field="*{observacao}" class="form-control">
            </div>
        </div>
    </div>
 </div>
 <div class="box-footer">
    <button type="submit" class="btn btn-primary">Salvar</button>
    <a class="btn btn-default" th:href="@{/}">Cancelar</a>
 </div>
</form>

Data Table Where I select the object for editing

<table id="example2" class="table table-bordered table-hover">
    <thead>
      <tr>
        <th>Data</th>
        <th>Valor</th>
        <th>Tipo Despesa</th>
        <th>Forma Pagamento</th>
      </tr>
    </thead>
    <tbody>
      <tr th:each="obj : ${despesas}">
        <td data-title="Data" th:text="${#calendars.format(obj.dataDespesa, 'dd/MM/yyyy HH:mm:ss')}"></td>
        <td data-title="Valor" th:text="${#numbers.formatCurrency(obj.valor)}"></td>
        <td data-title="Tipo Despesa" th:text="${obj.tipoDespesa}"></td>
        <td data-title="Forma Pagamento" th:text="${obj.formaPagamento}"></td>
        <td><a th:href="@{/despesas/edit{id} (id=${obj.codigoDespesa})}"><i class="glyphicon glyphicon-pencil"></i></a></td>
      </tr>
    </tbody>
</table>

Upvotes: 2

Views: 2785

Answers (1)

cralfaro
cralfaro

Reputation: 5948

As sr.praneeth said you need to add the fields you want to populate into the form, usually the ID are not visible but you need to send them.

<form th:object="${despesa}" method="POST" th:action="@{/despesas/save}">
 <div class="box-body">
 <input type="hidden" th:field="*{id}"/>
 ...  
 </form>

Then in your Controller you will be able to retrieve the id value, null if its a creation, or informed if its an update

Upvotes: 1

Related Questions