galao
galao

Reputation: 1301

Inserting multiple datas in 1 entity in a page

i have a CRUD generated create form:

<div class="create-form">
    <h:form>
        <h:inputText id="name" value="#{pointController.selected.name}" title="#{bundle.CreatePointTitle_name}" required="true" />

        <h:inputText id="term" value="#{pointController.selected.term}" title="#{bundle.CreatePointTitle_term}" required="true" />

        <p:commandButton styleClass="btn" action="#{pointController.create}" value="#{bundle.CreatePointSaveLink}" />
    </h:form>
</div>
<button>add new form</button>

i have a button that if clicked it will create another form same as above using javascript. (2 inputText, name and term)

my goal is, with 2 or more forms, depending how many forms the user wants, with 1 commandButton that is clicked it will insert everything in the database.

example:

first form: name = first form test, term = first form testterm
2nd form: name = 2nd form test, term= 2nd form testterm

after clicking the command button

2 rows will be inserted in the same table in the database.

but i'm not sure what would be the structure for page for this.

Upvotes: 0

Views: 975

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

You can't send data from many forms in a single request using JSF components, you should serialize all the data and send it manually. It would be better to have a List<Item> and every time you click in the button it will create a new item on the list and update an UIContainer that will display the items of the list.

This would be a start example of the above:

@ManagedBean
@ViewScoped
public class ItemBean {
    private List<Item> lstItem;

    public ItemBean() {
        lstItem = new ArrayList<Item>();
        addItem();
    }
    //getters and setter...

    public void addItem() {
        lstItem.add(new Item());
    }

    public void saveData() {
        //you can inject the service as an EJB or however you think would be better...
        ItemService itemService = new ItemService();
        itemService.save(lstItem);
    }
}

JSF code (<h:body> content only):

<h:form id="frmItems">
    <h:panelGrid id="pnlItems">
        <ui:repeat value="#{itemBean.lstItem}" var="item">
            Enter item name
            <h:inputText value="#{item.name}" />
            <br />
            Enter item description
            <h:inputText value="#{item.description}" />
            <br />
            <br />
        </ui:repeat>
    </h:panelGrid>
    <p:commandButton value="Add new item" action="#{itemBean.addItem}"
        update="pnlItems" />
    <p:commandButton value="Save data" action="#{itemBean.saveData}" />
</h:form>

Upvotes: 1

Related Questions