1

I am currently learning Java EE using JBoss and I am kind of stuck with a simple problem. Even though it should be common I did not find a solution in the internet.

I want to display a list of contacts and if a contact is selected a details page opens and the contact information can be edited.

The contact is a JPA Entity. Creating new contacts and displaying a list of contacts and a details page works fine. However I have trouble updating the contact information.

If a contact is clicked I open a details page and pass the id as get parameter. Now the following JSF code is executed:

<f:metadata>
  <f:viewParam name="contactID" value="#{contactUpdate.contactID}" />
</f:metadata>


<h:form>
  <h:outputLabel for="firstName" value="First Name:" />
  <h:inputText id="firstName" value="#{contactUpdate.contact.firstName}" />
  <h:commandButton id="register" action="#{contactUpdate.updateContact()}" value="Update" />
</h:form>

That is the bean (getter and setters removed):

@Stateful
@Named
@RequestScoped
public class ContactUpdate {

@Inject
private EntityManager em;

private Contact contact;
private long contactID;


public void updateContact(){
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    transaction.commit();
}

public void setContactID(long contactID) {
    this.contactID = contactID;

    setContact(em.find(Contact.class, contactID));
}

}

If I update it, the contact is null. I assume that the request scope is too short and already cleared. Is it possible to set the contactID upon commit?

I thought it would also be possible to use @ViewScoped, but doing so the <f:viewParam> does not work anymore.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

1 Answers1

1

Because you're preparing the contact in a setter of a view parameter, you need to pass the contact ID back as request parameter so that the request scoped bean can prepare it properly:

<h:commandButton id="register" action="#{contactUpdate.updateContact()}" value="Update">
    <f:param name="contactID" value="#{contactUpdate.contactID}" />
</h:commandButton>

But better would be to not do any business logic in setters (and definitely also not in getters) and use <f:event type="preRenderView"> instead. This way the @ViewScoped will work as expected.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555