I had a problem, which I solved, but I feel like my solution is a bad hack. Is there a better way?
I have a page, on which I placed the form, which shows properties of some object, as in example (obvious details omitted).
Ticket.java:
@Entity
public class Ticket {
@Id
private Long id;
private String title;
private byte priority;
// Getters, setters...
}
TicketController.java
@RequestScoped
public class TicketController {
private Ticket ticket = new Ticket();
// Getters, setters...
public String doUpdateTicket() {
Ticket t = ticketEJB.getTicketById(ticket.getId());
t.setTitle(ticket.getTitle());
t.setPriority(ticket.getPriority());
ticketEJB.updateTicket(t);
ticket = t;
return "view.faces";
}
}
edit.xhtml (just the form, everything else is boilerplate)
<h:form>
<h:inputHidden value="#{ticketController.ticket.id}" />
<h:panelGrid columns="2">
<h:outputLabel value="ID"/>
<h:outputLabel value="#{ticketController.ticket.id}"/>
<h:outputLabel value="Title: "/>
<h:inputText value="#{ticketController.ticket.title}"/>
<h:outputLabel value="Priority: "/>
<h:inputText value="#{ticketController.ticket.priority}" />
<h:commandButton value="Submit"
action="#{ticketController.doUpdateTicket}" />
</h:panelGrid>
</h:form>
Also there is TicketEJB, which is responsible for fetching those tickets, persisting, etc.
So I create a hidden input in the form, then (in managed bean) I find ticket, using provided id, then manually copy all the fields from ticket object of managed bean to the fetched ticket, then persist it… It involves the violation of DRY principle (I already stumbled on a bug when I added a field to Ticket, but forgot to copy it in the doUpdateTicket().
So, maybe there is a better way to do this?
Just get the original ticket from the EJB during
preRenderViewof a view scoped bean instead of creating a new one yourself. Assuming that the ticket ID is been passed as a request parameter with nameid:edit.xhtmlTicketControllerThe only difference is that the input fields don’t blank out. But isn’t that just the whole idea behind an “edit” form? That issue is then also immediately fixed that way.
Oh and your
really needs to be a