Inserting multiple datas in 1 entity in a page - jsf

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.

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>

Related

JSF - How can I retain the transient values within a ui:repeat after an immediate action

I created a very simple example based on my project in order to illustrate my doubt. Just a way to register a person with a list of telephone numbers.
MainController.java
private String name;
private List<Phone> phoneList;
// Getters and Setters
#PostConstruct
private void init() {
phoneList = new ArrayList<>();
}
public static class Phone implements Serializable {
private String number;
// Getters and Setters
#Override
public String toString() {
return number != null ? number : "null";
}
}
public void add() {
phoneList.add(new Phone());
}
public void save() {
System.out.println("Name: " + name + "; " + phoneList.toString());
}
index.xhtml
<h:form>
<h:inputText value="#{mainController.name}" required="true" />
<ui:repeat var="phone" value="#{mainController.phoneList}" varStatus="status">
<h:inputText value="#{phone.number}" required="true" />
</ui:repeat>
<h:commandButton action="#{mainController.add()}" value="Add Phone" immediate="true" />
<h:commandButton action="#{mainController.save()}" value="Save" />
</h:form>
In my example, note that all phone fields that are added MUST be filled in (required = true).
The problem is: when I type name and click add (to add a phone) the value of the field is maintained. But when I type a first phone and click add, the phone's value is not maintained. This occurs for all fields within the component ui:repeat.
Is there a way to preserve the input values within a after an immediate request, as with the name field?
Extra note: Other strange behavior I noticed is when add at least two phone fields, let the first blank and fills the second, and saves the form. After a failed validation (due to phone blank), click add will make all fields are filled with the value of the second phone.
Wildfly 9.0.2, JSF Api (Jboss) 2.2.12
Thanks to #BalusC comment. The OmniFaces library has two taghandlers that can be used in this case. In both cases input values will be preserved in case of validation failure. Note that h:commandButton should be with <h:commandButton immediate="false" />.
ignoreValidationFailed
In this case all validation failures will be ignored (including converter failures). Note that the h:form have to be changed to o:form. Also, the failures messages will still be displayed, which can be solved putting a proper condition in the rendered attribute. The files will look like this:
index.xhtml
<o:form>
<h:inputText value="#{mainController.name}" required="true" />
<ui:repeat var="phone" value="#{mainController.phoneList}" varStatus="status">
<h:inputText value="#{phone.number}" required="true" />
</ui:repeat>
<h:commandButton action="#{mainController.add()}" value="Add Phone">
<o:ignoreValidationFailed />
</h:commandButton>
<h:commandButton action="#{mainController.save()}" value="Save" />
</o:form>
<h:messages rendered="#{facesContext.validationFailed}" />
skipValidators
In this case only the validation failures will be ignored (the converters will still run). The failures messages will not be displayed, except for the converters. Note that this taghandler is only available since the 2.3 version. The files will look like this:
index.xhtml
<h:form>
<h:inputText value="#{mainController.name}" required="true" />
<ui:repeat var="phone" value="#{mainController.phoneList}" varStatus="status">
<h:inputText value="#{phone.number}" required="true" />
</ui:repeat>
<h:commandButton action="#{mainController.add()}" value="Add Phone">
<o:skipValidators />
</h:commandButton>
<h:commandButton action="#{mainController.save()}" value="Save" />
</h:form>
The solution that I use to this problem is to create an external field to the loop, which stores a JSON containing the values that should be saved. This field, to be outside the loop, properly saves values after each try and restore the missing values when necessary. I use two functions JavaScript and JQuery library.
So the files would look like this:
index.xhtml
<h:outputScript library="jquery" name="jquery.min.js" />
<h:outputScript library="all" name="all.js" />
<h:form>
<h:inputText value="#{mainController.name}" required="true" />
<ui:repeat var="phone" value="#{mainController.phoneList}" varStatus="status">
<h:inputText styleClass="savePhoneNumber" value="#{phone.number}" required="true" onchange="saveUiRepeatInput('#{allPhoneNumber.clientId}', 'savePhoneNumber')" />
</ui:repeat>
<h:inputHidden id="allPhoneNumber" binding="#{allPhoneNumber}" />
<h:outputScript>loadUiRepeatInput('#{allPhoneNumber.clientId}', 'savePhoneNumber')</h:outputScript>
<h:commandButton action="#{mainController.add()}" value="Add Phone" immediate="true" />
<h:commandButton action="#{mainController.save()}" value="Save" />
</h:form>
all.js
function saveUiRepeatInput(inputAll, inputClass) {
document.getElementById(inputAll).value = JSON.stringify($('.' + inputClass).map(function() { return this.value; }).get());
}
function loadUiRepeatInput(inputAll, inputClass) {
var jsonAll = document.getElementById(inputAll).value;
if (jsonAll) {
var array = JSON.parse(jsonAll);
$('.' + inputClass).each(function(i) { if (i < array.length) this.value = array[i]; });
}
}
Although work perfectly (including via ajax, with some minor changes), it looks like a hack, not an ideal solution. So if anyone can help with any solution strictly based on JSF, I will be grateful. Thanks.

Populate user form (edit row) with user-specific data in JSF Managed Bean

I'm using JSF (Primefaces) in Liferay and have some problems.
I have list of people (dataTable) with Edit button for every row in dataTable. Users have property that differ one row from others, e.g. football, basketball, tennis, and every user have some of these categories. Depending on those properties, there is different page/form that needs to be filled. So, I have one ManagedBean (PendingRequest.java) that acts like dispatcher/switcher who recieves data about that person in a row and switches user to appropriate form. Form has backing bean (e.g. page signFootballer.xhtml has bean Footballer.java that have getters and setters for fields in page signFootballer.xhtml).
So, user clicks on Edit button for some row in a table, method dispatchRequest starts running and checks for category (football,...) and depending on category and initialize new object of class Footballer and sets its properties to fill form (e.g. setName("John"), etc... because it is "edit user" functionality of application).
public String dispatchRequest(Person p) {
if (p.getCategory.equals("Tennis")) {
return "NOT_OK";
} else if (p.getCategory().equals("Basketball")) {
return "NOT_OK";
} else if (p.getCategory().equals("Football")) {
Footballer f = new Footballer();
f.setName("John");
f.setLastName("Doe");
return "OK";
} else {
return "NOT_OK";
}
}
After that, I'm switching to form signFootballer.xhtml via faces-config.xml. And it goes correctly, but problem is that my form is empty.
I'm aware this isn't correct approach but I need advice, can you suggest me what is the best way how to update some row from dataTable having in mind that I need to differ rows by category and then open appropriate page and corresponding backing bean that will fill form. Because I'm not sure it is possible by using this Dispatcher class.
EDIT:
#BalusC, This is not real case, but just showing example to help you understand my problem. I have 3 different form, depending on cases for FootballPlayer, BasketballPlayer and TennisPlayer.
signFootballer.xhtml
<h:form enctype="multipart/form-data" id="form">
<div id="container">
<div class="divs">
<p style="margin-left: 22%; width:60%; font-size: 20px; font-weight: bold">Sign contract</p>
<table>
<tr>
<td>
<p:outputLabel for="name" value="First name:*" styleClass="f_text" />
<p:inputText id="name" value="#{footballer.name}" required="true" />
</td>
<td>
<p:outputLabel for="surname" value="Last name:" styleClass="f_text" />
<p:inputText id="surname" value="#{footballer.surname}" required="true" />
</td>
</tr>
</table>
</div>
<div class="submit">
<p:commandButton value="Send" id="submit" update="err_msg1 err_msg2 err_msg3" action="#{Footballer.submitForm}" styleClass="button" />
</div>
</div>
</h:form>
Footballer.java (additional variables and method are deleted)
#ManagedBean
#ViewScoped
public class Footballer {
private String name;
private String surname;
public void submitForm() {
// Validate data and save in database
}
// GETTERS AND SETTERS
pendingRequest.xhtml (it is list of request that hasn't been confirmed yet - from database)
<h:form id="form">
<h:panelGroup id="table-wrapper">
<p:dataTable id="dt" var="req" value="#{pendingRequest.requestList}">
<f:facet name="header">
Pregled prijava
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{req.id}" />
</p:column>
<p:column headerText="Category">
<h:outputText value="#{req.category}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{req.name}" />
</p:column>
<p:column headerText="Prezime">
<h:outputText value="#{req.surname}" />
</p:column>
<p:column headerText="Delete/Edit" width="10%" style="text-align:center" >
<p:commandLink immediate="true" update=":form:table-wrapper" action="#{pendingRequest.deleteRecord(p)}"/>
<p:commandLink immediate="true" action="#{pendingRequest.dispatchRequest(p)}" style="margin-left:5px;"/>
</p:column>
</p:dataTable>
</h:panelGroup>
</h:form>
PendingRequests.java (class which method is run after user choose to edit some request from a list of pending requests)
#ManagedBean
#ViewScoped
public class PendingRequest {
public List<Requests> requestList = new ArrayList<Requests>(); // "Requests" is entity class generated from database
public List<Requests> getRequestList() {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//save example - without transaction
Session session = sessionFactory.openSession();
session.beginTransaction();
List<Requests> tempList = session.createCriteria(Requests.class).list();
session.getTransaction().commit();
return tempList;
}
public void setRequestList(List<Requests> requestList) {
this.requestList = requestList;
}
public void deleteRecord(Requests p) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
session.delete(p);
session.getTransaction().commit();
} catch (HibernateException ex) {
ex.printStackTrace();
session.getTransaction().rollback();
}
}
public void dispatchRequest(Requests p) {
if (p.getCategory().equals("Football")) {
//TRANSFER ID OF THAT REQUEST TO Footballer class to populate fields in signFootball.xhtml
} else if (p.getCategory.equals("Basketball")) {
//TRANSFER ID OF THAT REQUEST TO BasketballPlayer class to populate fields in signBasketballPlayer.xhtml
} else if (p.getCategory().equals("Tennis")) {
//TRANSFER ID OF THAT REQUEST TO TennisPlayer class to populate fields in signTennisPlayer.xhtml
} else {
System.out.println("OTHER...");
}
}
Method dispatchRequests is inspecting category (football, basketball, tennis) of request and depending on it, needs to open appropriate form and fill it with values. That is the same form as for new request creation, just now it would be filled with data from database.
So, if user clicks request for Footballer it needs to pass request id probably in Footballer class constructor? Because the fields need to be set before the page is rendered?
That part of this story isn't very clear to me. I'm new to JSF and I would appreciate very much if you could give me some suggestions how to do edit funcionality?
Note: This is just an idea.
It would be sufficient to create inline dataTable editor. On edit button call bean actionListener to extract user object based on the dataTable index. Check its category and populate related class object. Then get object properties to fill fields. Render button based on the property to identify action. Call another bean actionListener on update / save button and forward data to the service layer. On successful operation show relevant message.

Issue passing parameters using f:viewParam

I have a JSF page that displays numerous data items pulled from a DB given an account. The page has a SelectOneMenu that lists all accounts in the DB to choose from and a commandButton to trigger reloading the page with the newly selected account. My issue is when I click the commandButton the page reloads but is not taking the newly selected account. The "else" in method pullData() is being executed.
My JSF page:
<f:metadata>
<f:viewParam name="account" value="#{accountAnalysisBean.account}" />
<f:viewParam name="start" value="#{accountAnalysisBean.start}" />
<f:viewParam name="end" value="#{accountAnalysisBean.end}" />
<f:event type="preRenderView" listener="#{accountAnalysisBean.pullData}" />
</f:metadata>
<h:form>
<p:panelGrid columns="6">
<f:facet name="header">
<p:selectOneMenu id="pickAccount" value="#{accountAnalysisBean.pickAccount}" required="true">
<f:selectItems value="#{editAccountBean.allAccounts}" />
</p:selectOneMenu>
<p:calendar id="start" value="#{accountAnalysisBean.start}" />
<p:calendar id="end" value="#{accountAnalysisBean.end}" />
<p:commandButton value="Get Account" actionListener="#{accountAnalysisBean.updateAccount}" />
<f:param name="start" value="#{accountAnalysisBean.start}"/>
<f:param name="end" value="#{accountAnalysisBean.end}"/>
<f:param name="account" value="#{accountAnalysisBean.pickAccount}"/>
</p:commandButton>
</f:facet>
</p:panelGrid>
</h:form>
My Bean:
#ManagedBean
#RequestScoped
public class AccountAnalysisBean {
private String account = "";
private String id = "";
private String pickAccount = "";
private Date start;
private Date end;
//----getters and setters----
public void pullData() {
if (account != "") {
//pull various fields from database given account value
} else {
//set default null values
}
}
public String updateAccount(ActionEvent actionEvent) {
fix = DAOFactory.getInstance("fix_site2.jdbc");
datalist = fix.getMyDataDAO();
account = datalist.findAccountID(pickAccount); //returns an ID from a DB given account selected from menu
return "/AccountAnalysis.xhtml?includeViewParams=true";
}
//remainder of code omitted for clarity
}
I am using JSF 2.2 and PrimeFaces 4
Let's walk through what's likely happening here:
<f:viewParam/> will set the value in your AccountAnalysisBean bean on initial page load, using the defined setter
As soon as the page is done loading, AccountAnalysisBean is destroyed: it's a #RequestScoped bean.
So, as at the time you're clicking on your commandButton, you're starting with a fresh copy of AccountAnalysisBean with nothing in it.
Consider:
Making AccountAnalysisBean a #ViewScoped bean
Getting rid of that actionListener and use the action attribute instead. Going by the code sample you have here, you don't really need it.

JSF update inputText after selectOneMenu choice

I want to change the inputTexts' values when I choose another Skin from my selectOneMenu.
Everything is doing well, my Converter gives back the right Object from the menu, but the inputTexts are not updated.
<h:form>
<h:selectOneMenu id="dropdownSkin"
value="#{helloBean.currentSkin}" defaultLabel="Select a skin.."
valueChangeListener="#{helloBean.skinValueChanged}" immediate="true"
onchange="this.form.submit()" converter="SkinConverter" >
<f:selectItems value="#{helloBean.mySkinsSI}" var="c"
itemValue="#{c.value}" />
</h:selectOneMenu>
<br />
<h:inputText id="name" value="#{helloBean.currentSkin.title}"></h:inputText>
<br />
<h:inputText id="tcolor" value="#{helloBean.currentSkin.titleBar.textColor}"></h:inputText>
<br />
<h:inputText id="bcolor" value="#{helloBean.currentSkin.titleBar.backgroundColorStart}"></h:inputText>
</h:form>
Here is what my Bean looks like. I debugged it and the Object currentSkin is set correctly. Now i need to know how to update the textfields content.
#ManagedBean
#SessionScoped
public class HelloBean implements Serializable {
private static final long serialVersionUID = 1L;
private List<ExtendedSkin> mySkins;
private List<SelectItem> mySkinsSI;
private ExtendedSkin currentSkin;
public void skinValueChanged(ValueChangeEvent e) {
currentSkin = (ExtendedSkin) e.getNewValue();
FacesContext.getCurrentInstance().renderResponse();
}
public List<ExtendedSkin> getMySkins() {
mySkins = XMLParser.readExtendedSkins();
return mySkins;
}
public List<SelectItem> getMySkinsSI() {
mySkinsSI = new LinkedList<SelectItem>();
for (ExtendedSkin s : getMySkins()) {
mySkinsSI.add(new SelectItem(s, s.getTitle()));
}
return mySkinsSI;
}
public void setMySkinsSI(List<SelectItem> myItems) {
this.mySkinsSI = myItems;
}
public ExtendedSkin getCurrentSkin() {
if (currentSkin == null) {
currentSkin = getMySkins().get(0);
}
return currentSkin;
}
public void setCurrentSkin(ExtendedSkin currentSkin) {
this.currentSkin = currentSkin;
}
}
The problem here is that the converter is doing its work filling the helloBean.currentSkin object, but the values in the <h:inputText> that are bounded to this helloBean.currentSkin: title, textColor and backgroundColorStart will be send to the server and replace the actual values that were loaded by the converter. In other words:
The converter is executed and builds the helloBean.currentSkin based on the selected value.
The <h:inputText id="name"> empty value is sent to server and will be injected in helloBean.currentSkin.title. Same behavior for the other 2 <h:inputText>s.
The view will be loaded using the selected helloBean.currentSkin and it will load the helloBean.currentSkin.title with the empty value. Same behavior for the other 2 <h:inputText>s.
There are two possible solutions to this problem:
Move the <h:inputText>s outside the form, so the empty values won't be send to the server. When loading the view, it will maintain the values loaded in the converter.
<h:form>
<h:selectOneMenu id="dropdownSkin"
value="#{helloBean.currentSkin}" defaultLabel="Select a skin.."
valueChangeListener="#{helloBean.skinValueChanged}" immediate="true"
onchange="this.form.submit()" converter="SkinConverter" >
<f:selectItems value="#{helloBean.mySkinsSI}" var="c"
itemValue="#{c.value}" />
</h:selectOneMenu>
</h:form>
<br />
<h:inputText id="name" value="#{helloBean.currentSkin.title}"></h:inputText>
<!-- rest of Facelets code... -->
Since you're loading the helloBean.currentSkin while changing the selected value on your dropdownlist, you can add ajax behavior using <f:ajax> tag component inside the <h:selectOneMenu> and update the fields in a cleaner way. I would opt for this solution.
<h:form>
<!-- Note that there's no need of the onchange JavaScript function -->
<h:selectOneMenu id="dropdownSkin"
value="#{helloBean.currentSkin}" defaultLabel="Select a skin.."
valueChangeListener="#{helloBean.skinValueChanged}" immediate="true"
converter="SkinConverter" >
<f:selectItems value="#{helloBean.mySkinsSI}" var="c"
itemValue="#{c.value}" />
<f:ajax process="#this" render="name tcolor bcolor" />
</h:selectOneMenu>
<br />
<h:inputText id="name" value="#{helloBean.currentSkin.title}" />
<h:inputText id="tcolor" value="#{helloBean.currentSkin.titleBar.textColor}" />
<br />
<h:inputText id="bcolor"
value="#{helloBean.currentSkin.titleBar.backgroundColorStart}" />
</h:form>
You can learn more about <f:ajax> in online tutorial like this one.
Since you're going to use an ajax call in your page, you should change your managed bean scope from #SessionScoped to #ViewScoped. More info about this here: Communication in JSF 2

How to dynamically refresh h:selectManyCheckbox selectItems

I am trying to implement a scenario using JSF. I have a commandExButton and when user click this button "A" it shows the panelDialog which contains the selectManyCheckBox items. I generat these items in the backend bean by parsing one file which is continuously getting updated. What I want is, whenever I click this button "A" I should get the latest selectItems by parsing the file through the backend bean. But what I get it the same selectItem which was generated when page rendered first time. So as of now I have a workaround, in which I included one refresh button which actually refresh the page and then user click "A" to get the latest selectItem by parsing the current file's content. But is it doable in anyway without adding new button and using the existing button?
Following is the code which I am using
<td>
<hx:commandExButton id="preferenceButton" styleClass="form" value="#{nls.preferenceLink}"
title="#{nls.preferenceLinkTitle}" type="submit" />
</td>
<td>
<h:form id="PrefForm" rendered="#{Test.isCurrent}">
<hx:panelDialog type="modal" id="preferenceSet" styleClass="panelDialog" for="preferenceButton"
title="#{nls.preferenceDialogTitle}">
<h:outputText styleClass="panelStartMessage" style="display:block;"
value="#{nls.preferenceDialogWindowText}" />
<h:panelGroup rendered="#{Test.hasSelectItem }"
style="display:block;width:300px;height:360px;overflow:auto;" styleClass="panelGroup"
id="prefPanelGroup">
<h:selectManyCheckbox value="#{Test.selectedItems}" layout="pageDirection">
<f:selectItems value="#{Test.selectItems}" />
</h:selectManyCheckbox>
</h:panelGroup>
<hx:panelBox styleClass="information_box" id="noCommandWindow" layout="lineDirection"
rendered="#{!Test.hasSelectItem }">
<h:outputText styleClass="outputText" id="cmdInfo" value="#{nls.noCommands}" />
</hx:panelBox>
<hx:panelBox id="buttonBox1" styleClass="panelStartBox" layout="lineDirection">
<hx:commandExButton id="submitPref" styleClass="commandExButton" type="submit"
value="#{nls.submit}" action="#{Test.action}">
<hx:behavior event="onclick" behaviorAction="hide" targetAction="preferenceSet"
id="behaviorSubmitPref" />
</hx:commandExButton>
<hx:commandExButton id="CancelPref" styleClass="commandExButton" type="submit"
value="#{nls.cancel}" action="Test">
<hx:behavior event="onclick" behaviorAction="hide" targetAction="preferenceSet"
id="behaviorCancelPref" />
</hx:commandExButton>
</hx:panelBox>
</hx:panelDialog>
</h:form>
</td>
Code in Bean:
public class Test{
private List<String> selectedItems;
private List<SelectItem> selectItems;
public List<SelectItem> getSelectItems() {
// populate the selectItem here...
}
}
Store the List<SelectItem> selectItems in a separate session scoped bean (assuming that your current one is request scoped), fill it during its construction and add a method like reload() which you invoke only after processing the selected item in the action method. You can access the session scoped bean from inside the request scoped one by #ManagedProperty.

Resources