Initialise List based on a JPA query? - jsf

Good afternoon. I have a list of operators which I initialize as follows.
#ManagedBean
#ViewScoped
public class TiemposBean implements Serializable {
#EJB
private OperariosFacade operariosFacade;
private List<Operarios> operariosList;
#PostConstruct
public void inicializarBean() {
operariosList = operariosFacade.findAll();
}
public List<Operarios> getOperariosList() {
return operariosList;
}
public void setOperariosList(List<Operarios> operariosList) {
this.operariosList = operariosList;
}
}
The list is initialized normally and I use it without any problem but I want to initialize it based on the following database query.
SELECT * FROM `operarios` WHERE `ESTADO_OPERARIO` = 1 AND `TIPO_ESTADO_OPERARIO` = 1;
In my JPQL query is as follows.
#NamedQuery(name = "Operarios.findByNombreLista", query = "SELECT o FROM Operarios o WHERE o.idEstadoOperario = :idEstadoOperario AND o.tipoEstadoOperario = :tipoEstadoOperario"),
And the method I built to invoke that query is as follows.
public void inicializarLista() {
String namedQuery = "Operarios.findByNombreLista";
Map<String, Object> parametros = new HashMap<>();
parametros.put("idEstadoOperario", 1);
parametros.put("tipoEstadoOperario", 1);
operariosList = operariosFacade.findByNamedQuery(namedQuery, parametros);
}
and there's modified my bean.
#ManagedBean
#ViewScoped
public class TiemposBean implements Serializable {
#EJB
private OperariosFacade operariosFacade;
private List<Operarios> operariosList;
#PostConstruct
public void inicializarBean() {
operariosList = new ArrayList<>();
}
public List<Operarios> getOperariosList() {
return operariosList;
}
public void setOperariosList(List<Operarios> operariosList) {
this.operariosList = operariosList;
}
}
and in my view I call it as follows
<p:outputLabel for="somOperario" value="Operario"/>
<p:selectOneMenu id="somOperario" value="#{tiemposBean.operarioSeleccionado}"
filter="true"
converter="operariosConverter">
<f:selectItem itemLabel="Seleccione uno"/>
<f:selectItems value="#{tiemposBean.operariosList}"
var="operarioVar"
itemValue="#{operarioVar}"
itemLabel="#{operarioVar.nombre}"
/>
</p:selectOneMenu>
<p:message for="somOperario" id="msg_somOperario"/>
But I don't initialize it to me that I am doing wrong please I need your help. thanks

Based on the code that you posted, the "inicializarLista" method is not called. You have a managed bean with:
#PostConstruct
public void inicializarBean() {
operariosList = new ArrayList<>();
}
But you are loading your list in:
public void inicializarLista()
Please, call the inicializarLista() inside #PostConstruct method:
#PostConstruct
public void inicializarBean() {
//This step is not necessary any more!
operariosList = new ArrayList<>();
inicializarLista();
}

Related

h:selectOneMenu along with f:selectItems always returns 0

Here's my XHTML code:
<h:selectOneMenu id="combo" value="#{TeamsHinzufuegenBean.selectedLeagueId}">
<f:selectItems value="#{TeamsHinzufuegenBean.leagues}"
var="league" itemValue="#{league.id}"
itemLabel="#{league.name}"/>
</h:selectOneMenu>
And my bean:
#ManagedBean(name = "TeamsHinzufuegenBean")
#ViewScoped
public class TeamsHinzufĂĽgenBean implements Serializable{
private static final long serialVersionUID = 1L;
private List<League> leagues;
private ArrayList<Team> teams = new ArrayList<Team>();
private String teamname;
private int selectedLeagueId=1;
#PostConstruct
public void init() {
leagues = Database.getInstance().getAllLeagues();
for(League l : leagues)
System.out.println(l);
}
public List<League> getLeagues() {
return leagues;
}
public void setLeagues(List<League> leagues) {
this.leagues = leagues;
}
public int getSelectedLeagueId() {
return selectedLeagueId;
}
public void setSelectedLeagueId(int selectedLeagueId) {
this.selectedLeagueId = selectedLeagueId;
}
public ArrayList<Team> getTeams() {
return teams;
}
public void setTeams(ArrayList<Team> teams) {
this.teams = teams;
}
public String getTeamname() {
return teamname;
}
public void setTeamname(String teamname) {
this.teamname = teamname;
}
}
The league-class has an attribute id but if I output the value of selectedLeagueId, it is always 0.
Check if getAllLeagues() contains objects that have an id and that it is correctly set

How to extend AjaxBehaviorEvent dispatched from #FacesComponent?

When I dispatch an ajax event from the Composite Component by using <cc:clientBehavior name="chartUpdated" event="change" targets="chartdata"/> I catch it in Facelet page by using <f:ajax event="chartUpdated" listener="#{bean.updateListener}">. And In backing bean I capture event of type AjaxBehaviorEvent.
public void updateListener(AjaxBehaviorEvent event){
...
}
I undertand that I can extend AjaxBehaviorEvent and pass within it object which has been changed. For example, Primefaces's Scheduler uses this approach:
<p:ajax event="eventMove" listener="#{scheduleView.onEventMove}" update="messages" />
And backing bean:
public void onEventMove(ScheduleEntryMoveEvent event) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event moved", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());
addMessage(message);
}
Is it possible to achieve the same functionality by using Composite Component together with the #FacesComponent ?
Thank you in advance!
Nice to meet you, again :)
continuing from your previous question:
Override queueEvent() to filter interesting events (changes from specific components) and postpone their enqueue to validation phase to be able to fetch converted & validated values:
#FacesComponent("rangeComponent")
public class RangeComponent extends UIInput implements NamingContainer
{
private final List<AjaxBehaviorEvent> customEvents = new ArrayList<>();
...
#Override
public void queueEvent(FacesEvent event)
{
FacesContext context = getFacesContext();
if(event instanceof AjaxBehaviorEvent)
{
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String eventName = params.get("javax.faces.behavior.event");
Object eventSource = event.getSource();
if("change".equals(eventName) && (from.equals(eventSource) || to.equals(eventSource)))
{
customEvents.add((AjaxBehaviorEvent) event);
return;
}
}
super.queueEvent(event);
}
#Override
public void validate(FacesContext context)
{
super.validate(context);
if(from.isValid() && to.isValid())
{
for(AjaxBehaviorEvent event : customEvents)
{
SelectEvent selectEvent = new SelectEvent(this, event.getBehavior(), this.getValue());
if(event.getPhaseId().equals(PhaseId.APPLY_REQUEST_VALUES))
{
selectEvent.setPhaseId(PhaseId.PROCESS_VALIDATIONS);
}
else
{
selectEvent.setPhaseId(PhaseId.INVOKE_APPLICATION);
}
super.queueEvent(selectEvent);
}
}
}
...
}
then add the specific event listener to your managed bean:
#ManagedBean
#ViewScoped
public class RangeBean implements Serializable
{
private static final long serialVersionUID = 1L;
private String range = "01/01/2015-31/12/2015";
public void onSelect(SelectEvent event)
{
Messages.addGlobalInfo("[{0}] selected: [{1}]", event.getComponent().getId(), event.getObject());
}
public String getRange()
{
return range;
}
public void setRange(String range)
{
this.range = range;
}
}

How can I use multiple value in Input text field JSF

In my xhtml there are 3 input field which calculate remaining day of two <p:calendar> dates. In next step I want to store calculated remaining day to MY DB.
<p:dataTable styleClass="vtable" editable="true" var="user"
editMode="cell" value="#{userBean.employeeList}">
<p:column styleClass="columntd" headerText="#{text['user.startedDate']}">
<p:calendar widgetVar="fromCal" value="#{vacationBean.vacation.beginDate}">
<p:ajax event="dateSelect" listener="#{dayDiffBean.fromSelected}"
update="diff" />
</p:calendar>
</p:column>
<p:column styleClass="columntd"
headerText="#{text['user.finishedDate']}">
<p:calendar widgetVar="toCal" value="#{vacationBean.vacation.endDate}">
<p:ajax event="dateSelect" listener="#{dayDiffBean.toSelected}"
update="diff" />
</p:calendar>
</p:column>
<p:column styleClass="columntd"
headerText="#{text['employee.remainingdays']}">
<p:inputText id="diff" styleClass="daysNumber"
value="#{dayDiffBean.diff}" />
</p:column>
</p:dataTable>
<h:commandButton styleClass="sndbutton1"
value="#{text['employee.send']}" action="#{vacationBean.addVac}"/>
I used value="#{dayDiffBean.diff} to get remaining day and now I also want to use my vacationbean to store remaingday to my db using like this : value="#{vacationBean.vacation.balanceDay}"
But I cant use 2 value in inputtext field like this:
<p:inputText value="dayDiffBean.diff" value1="vacationBean.vacation.balanceDay">
How can i solve this problem?
This is my vacation bean code:
#ManagedBean(name="vacationBean")
#ViewScoped
public class VacationBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Date vEndDate;
private boolean selected;
private Date vStartDate;
private Date createdDate;
private String isNobody;
Requestrelax vacation;
Employee e;
Calendar javaCalendar = null;
private short balanceDay;
#EJB
VacationLocal vacations;
#ManagedProperty(value="#{loginBean.userId}")
Integer userId;
#EJB
EmployeesLocal employees;
#PostConstruct
public void init(){
System.out.println("0");
//System.out.println("STATrtsg >> . "+ diff.getDiff());
vacation=new Requestrelax();
e=employees.getEmployee(userId);
vacation.setEmployee(e);
System.out.println("balanday is:"+balanceDay);
}
public void addVac(){
System.out.println("1");
javaCalendar = Calendar.getInstance();
Date currenDate=Calendar.getInstance().getTime();
vacation.setCreatedDate(currenDate);
vacation.setBalanceDay(balanceDay);
vacations.addEmployeeVacation(vacation);
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Employee getE() {
return e;
}
public void setE(Employee e) {
this.e = e;
}
public Requestrelax getVacation() {
return vacation;
}
public void setVacation(Requestrelax vacation) {
this.vacation = vacation;
}
public Date getvEndDate() {
return vEndDate;
}
public void setvEndDate(Date vEndDate) {
this.vEndDate = vEndDate;
}
public Date getvStartDate() {
return vStartDate;
}
public void setvStartDate(Date vStartDate) {
this.vStartDate = vStartDate;
}
public short getBalanceDay() {
return balanceDay;
}
public void setBalanceDay(short balanceDay) {
this.balanceDay = balanceDay;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getIsNobody() {
return isNobody;
}
public void setIsNobody(String isNobody) {
this.isNobody = isNobody;
}
}
And daydiffbean code :
#ManagedBean(name="dayDiffBean")
#SessionScoped
public class DayDiffBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Date from;
private Date to;
private String diff="";
private final long oneDay=1000*60*60*24;
public void fromSelected(SelectEvent event){
from=(Date) event.getObject();
calDiff();
}
public void toSelected(SelectEvent event){
to=(Date) event.getObject();
calDiff();
}
public void calDiff(){
if(from==null||to==null){
diff="N/A";
return;
}
diff=(to.getTime()-from.getTime())/oneDay+"";
}
public String getDiff() {
return diff;
}
public void setDiff(String diff) {
this.diff = diff;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getFrom() {
return from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
}
From the code, one way to add balanceDay to your vacationBean is by passing the diff string as a parameter to addVac() method (notice action in the second line):
<h:commandButton styleClass="sndbutton1" value="#{text['employee.send']}"
action="#{vacationBean.addVac(dayDiffBean.diff)}"/>
Then, for your VacationBean.addVac():
// 'diff' is now being passed in as a parameter
public void addVac(String diff) {
System.out.println("1");
javaCalendar = Calendar.getInstance();
Date currenDate=Calendar.getInstance().getTime();
vacation.setCreatedDate(currenDate);
vacation.setBalanceDay(balanceDay);
// UPDATED
// so now you can set balanceDay
setBalanceDay(Short.parseShort(diff));
vacations.addEmployeeVacation(vacation);
}

Netbeans CRUD generator: customization and is it efficient for real applications?

I use netbeans 7.2.1. Is JSF CRUD Generated code efficient for real applications?
I have created a test database and used netbeans CRUD generator. It uses DataModel and PaginationHelper instead of Lists for CRUD operations. There is an Entity Test.java, a TestFacade.java and TestController.java. and jsf files list.xhtml, edit.xhtml, view.xhtml, create.xhtml. I added a NemdQuery to entity file:
#Entity
#NamedQuery(name = "Test.findByTestCriteria", query = "SELECT t FROM Test t WHERE t.testCriteria = true")
public class Test implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "title")
private String title;
#Column(name = "testCrieteria")
private boolean testCrieteria;
public Test() {
}
//Getters and Setters
And created the query in TestFacade.java:
#Stateless
public class TestFacade extends AbstractFacade<Test> {
#PersistenceContext(unitName = "testPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public TestFacade() {
super(Test.class);
}
public List<Test> testCriteria(){
Query q = em.createNamedQuery("Test.findByTestCriteria",Test.class);
return q.getResultList();
}
}
And I have added a method in TestController.java to retrieve testCriteria Query:
#ManagedBean(name = "testController")
#SessionScoped
public class TestController implements Serializable {
private Test current;
private DataModel items = null;
private DataModel testCriteria = null;
#EJB
private com.test.TestFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public Test getSelected() {
if (current == null) {
current = new Test();
selectedItemIndex = -1;
}
return current;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Test) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
//getting testCriteria items
public DataModel getTestCriteria(){
if(items == null){
items = getPagination().createPageDataModel();
}
testCriteria = new ListDataModel(ejbFacade.testCriteria());
return testCriteria;
}
//custom view page
public String viewTest(){
current = (Test) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "ViewTest?faces-redirect=true";
}
//custom viewTestCriteria
public String viewTestCriteria(){
current = (Test) getTestCriteria ().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "ViewTest?faces-redirect=true";
}
And Retrieving testCriteria in a p:dataGrid in index.xhtml:
<h:form>
<p:dataGrid value="#{testController.testCriteria()}" var="item" columns="4">
<p:column>
<h:panelGrid columns="1">
<h:commandLink id="viewTestCriteria" value="#{item.title}" action="#{testController.viewTestCriteria()}"/>
</h:panelGrid>
</p:column>
</p:dataGrid>
</h:form>
With this code all testCriteria data are there in index.xhtml but when I click the commadnButton to view them they all show the first Item. It seems that in the DataGrid it doesn't get the selected item. And if I refresh the List.xhtml which contains all test data, and then coming back to index.xhtml and pressing commandLink it throws a NoRowAvailable exception.
I hope I have stated my question clearly and I would appreciate any guide because I am new to this technology.
Update:
After googling and research for two days and thinking I thought of using <f:setPropertyActionListener value="#{item.id}" target="#{testController.selected.id}"> and <f:param name="#{testController.selected.id}" value="#{item.id}"> but it didn't work.
Update:
So far I'm almost confident that no row is getting selected so the data grid returns first row. But I'm still not sure how to modify viewTestCriteria() to set the current item and selectedItemIndex correctly.

h:selectManyListBox setter not setting all the values selected

<h:selectManyListbox id="sectorsListBox" size="2" multiple="multiple" value="#{Mybean.classificationSelectedItems}">
<f:selectItems id="sectors" value="#{Mybean.classificationSelectItems}"/>
</h:selectManyListbox>
Backing Bean has:
public class Mybean
{
private Map<String,String> classificationSelectItems = new LinkedHashMap<String,String>();
private List<String> classificationSelectedItems = new ArrayList<String>();
//getter and setter for both.
}
init()
{
classificationSelectItems.put("INS","Insurance")
classificationSelectItems.put("HLC","HealthCare")
}
The select many box gets initialized with these 2 values but the problem is only the last selected entry is getting stored in classificationSelectedItems. Why is that so ? And how do I get all the selected entries stored in the list of classificationSelectedItems ?
Adding FYI, the init method is class by Spring.
I have tested with an examle(reference:http://www.mkyong.com/jsf2/jsf-2-multiple-select-listbox-example/), good luck :)
Facelets:
<h:form id="form">
<h:selectManyListbox value="#{user.favFood1}" >
<f:selectItems value="#{user.favFood2Value}" />
</h:selectManyListbox>
<h:commandButton value="test"/>
</h:form>
Bean:
#ManagedBean(name = "user")
#ViewScoped
public class UserBean implements Serializable {
private static final long serialVersionUID = 1L;
public List<String> favFood1;
private Map<String, Object> food2Value;
public UserBean() {
favFood1 = new ArrayList<String>();
food2Value = new LinkedHashMap<String, Object>();
food2Value.put("Food2 - Fry Checken", "Fry Checken1"); //label, value
food2Value.put("Food2 - Tomyam Soup", "Tomyam Soup2");
food2Value.put("Food2 - Mixed Rice", "Mixed Rice3");
}
public List<String> getFavFood1() {
return favFood1;
}
public void setFavFood1(List<String> favFood1) {
this.favFood1 = favFood1;
}
public Map<String, Object> getFavFood2Value() {
return food2Value;
}
}
I noticed exactly this behaviour when I used a Collection in the setter method, like
public void setClassificationSelectedItems(Collection<String> in){
// store it somewhere
}
This setter is called during the restore phase but not during the update phase, so the previously set value will be set, but never the new one. If you use a List, it works as expected:
public void setClassificationSelectedItems(List<String> in){
// store it somewhere
}
Note that you will need to redeploy the application after such a change because the JSP needs to be recompiled but this isn’t done automatically.

Resources