Search code examples
htmljsf-2primefacesejb

Reset input fields of a form after successful submit


I have a form which creates a new Employee. My backing bean is @SessionScoped. When I create the first employee, everything went well. However, when I'm about to create the second employee, the form still displays the properties of the first employee in the input fields.

How do I reset them without changing the scope of the bean? The scope is mandatory for other purposes. i use a managed Bean ( controller) where i have "Create employe"

public String createEmploye()

{

    employe = new Employe();

    employe.setId(this.id);
    employe.setNom(this.nom);
    employe.setPrenom(this.prenom);
    employe.setNum_telephone(this.num_telephone);
    employe.setAdresse(this.adresse);
    employe.setNum_poste(this.num_poste);

    employeBean.addEmploye(employe);

    employe.setNom("");

    return "ListEmployes.xhtml?faces-redirect=true";
    // return ("ListEmployes.xhtml");

}

Solution

  • Recreate the Employee instance after saving it in the DB.

    public void save() {
        service.save(employee);
        employee = new Employee(); // <--- Just add this line.
    }
    

    Unrelated to the concrete problem, I however strongly recommend to reconsider your bean design. Shouldn't it rather be split into two beans? One request/view scoped for the form itself and another session scoped one for the real session scoped data which get injected in the request/view scoped one. This way you can after the save just perform a redirect to the same view in order to start with a clean form (and have the additional benefit that the very same employee doesn't get duplicated in the DB when you refresh the page after submit).

    See also:


    Update as per the update, it seems that you're duplicating/flattening all properties of Employee in the backing bean instead of letting the form refer them directly. I strongly recommend to not duplicate/flatten the model properties into the controller.

    @ManagedBean
    @SessionScoped
    public class Manager {
    
        private Employee employee = new Employee();
    
        @EJB
        private EmployeeService service;
    
        public void createEmployee() {
            service.create(employee);
            employee = new Employee();
        }
    
        public Employee getEmployee() {
            return employee;
        }
    
    }
    

    with

    <h:inputText value="#{manager.employee.firstname}" />
    <h:inputText value="#{manager.employee.lastname}" />
    <h:inputText value="#{manager.employee.telephone}" />
    <h:inputText value="#{manager.employee.street}" />
    ...