Primefaces binding Bean with form - jsf

I'm developing an application with primefaces, I´m trying to map my form with my Bean of User but i can't, this is my code:
<h:form>
<p:panelGrid columns="2">
<h:outputLabel for="usuario" value="Usuario: *"/>
<h:inputText id="usuario" binding="#{beanPrueba.user.usuario}"></h:inputText>
<h:outputLabel for="contrasena" value="Contraseña: *" />
<h:inputSecret id="contrasena"></h:inputSecret>
<f:facet name="footer">
<p:commandButton icon="ui-icon-check" value="Entrar" ajax="false"
action="#{beanPrueba.prueba()}"/>
</f:facet>
</p:panelGrid>
</h:form>
Backing bean:
#ManagedBean(name = "beanPrueba")
#SessionScoped
public class BeanLogin {
private Usuario user = new Usuario();
public Usuario getUser() {
return user;
}
public void setUser(Usuario user) {
this.user = user;
}
public void prueba()
{
try {
//my code
}
catch(Exception ex)
{
System.out.print(ex.getMessage());
}
}
in my bean declare a object of User, I'm using the object user for map my form with my bean but I get an error when map to bean with my form

You are using binding attribute completely wrong. In your case you shouldn't use binding, replace it with value attribute. binding is used if you want to bind whole component with some UIComponent property of your backing bean, and manage component attributes programmatically. Value provide connection between component value, and some backing bean property.

I think it's also wrong the syntax of method calling, it should be
<p:commandButton icon="ui-icon-check" value="Entrar" ajax="false"
action="#{beanPrueba.prueba}"/>
without parenthetis.

Related

parameters are not setting to managed property in jsf primefaces

I am trying to pass parameters from UI to service which is managed bean. Values are not getting set to bean properties
<ui>
<p:dialog header="Account Search" widget-var="account Search">
<h:inputText id="account Name" value="#{accountSub.request.accountName}"/>
<p:commandButton id="btnSearch" update="">
<h:inputText id="account Name" value="#{accountSub.request.accountNumber}"/>
<p:commandButton id="btnSearch" update="">
<p:ajax event="click" listener="#{accountSub.process}" update="#widgetVar(resultPanel)">
</p:dialog>
</ui>
Managed Bean
#ManagedBean
#VieweScoped
public class AccountSub {
private Account request;
//getter and setter for same
public void process(){
// process logic goes here.
}
}
class Account{
private String accountName;
private String accountNumber;
//getter and setter
}
There are a couple of errors in the example.
Id of input component is not valid. You should not include space.
Ajax Event 'click' is not supported
Use form element as below.
<h:form>
<p:dialog header="Basic Dialog" widgetVar="dlg1" minHeight="40">
<h:inputText id="name" value="#{accountSub.request.accountName}"/>
<h:inputText id="number" value="#{accountSub.request.accountNumber}"/>
<p:commandButton id="btnSearch" actionListener="#{accountSub.process}">Click</p:commandButton>
</p:dialog>
</h:form>

jsf inputText only displayed value when is readonly true or outputText

I have a h:inputText with valueChangeListener, when the user type some code another h:inputText display data from MySQL about that code, the valueChangeListener works but the second h:inputText not displayed the value and only do it when I set the readonly attribute or I change the component to h:outputText
my facelets page is:
<h:form id="idFacturacion">
<rich:panel>
<f:facet name="header">
<h:outputText value="FACTURACION AL CLIENTE" />
</f:facet>
<h:panelGrid columns="4">
<h:outputText value="Cedula: " />
<h:inputText value="#{facturaBean.encFactura.cedula}" onchange="submit();" valueChangeListener="#{facturaBean.processValueChange}" />
<h:outputText value="Nombre: " />
<h:inputText value="#{facturaBean.encFactura.nombre_cli}" />
</h:panelGrid>
</rich:panel>
</h:form>
facturaBean is:
#ManagedBean
#SessionScoped
public class FacturaBean {
private EncFactura encFactura = new EncFactura();
//getter and setter
public void processValueChange(ValueChangeEvent event){
String ced = event.getNewValue().toString();
try{
//do the database thing
if(resultSet.next()){
encFactura.setNombre_cli(resultSet.getString("nombre_cli"));
}else{
encFactura.setNombre_cli("");
}
}catch(SQLException error){
facesContext.addMessage(null, new FacesMessage("Hubo un error SQL."));
}
}
}
Please see
Change inputText value from listener method… and
Possible to execute `valueChangeListener` for `p:inputText` without hitting `enter` key?
May I suggest using ajax?
Here is a primefaces example but you could apply to richfaces..
<h:inputText value="#{facturaBean.stringOne}" >
<p:ajax event="change" listener="#{facturaBean.processValueChange}" update="strTwo"/> </h:inputText> <h:outputText value="Nombre: " />
<h:inputText id="strTwo" value="#{facturaBean.stringTwo}" />
</h:panelGrid>
private String stringOne= "";
private String stringTwo= "";
public void processValueChange(){
stringTwo = stringOne;
}
With getters etc.. basically on change, fires off to ajax, you do your database call etc, then it returns the response and updates your other input field, it's a much cleaner way than trying to submit forms etc..
Also are you sure you want session scope?

ValueChangeListener not being invoked upon submit

My valuechangelistener method is not being called as I expected. I have a h:selectOneRadio component (below) and I'm expecting the valueChangeListener to be called when I click the add button, but only the add method is getting invoked, the setSelectedItem method is completely ignored. What am I missing? Note the javascript dataTableSelectOneRadio is executing fine.
Here is the .xhtml
h:panelGrid
Select Client to Associate with Appointment
<h:dataTable id="addClient" styleClass="dataTable"
value="#{AddEntryMB.clientValues}" var="c" binding="#{AddEntryMB.dataTable}" >
<h:column>
<f:facet name="header">Select</f:facet>
<h:selectOneRadio valueChangeListener="#{AddEntryMB.setSelectedItem}"
immediate="true" onchange="dataTableSelectOneRadio(this);">
<f:selectItem itemValue="null" />
</h:selectOneRadio>
</h:column>
<h:column>
<f:facet name="header">Last Name</f:facet>
#{c.lastName}
</h:column>
</h:dataTable>
</h:panelGrid>
<h:panelGroup>
<h:commandButton action="#{AddEntryMB.add}" value="add" />
<h:commandButton action="cancel" value="cancel" immediate="true"/>
</h:panelGroup>
And here is the backing bean.
#ManagedBean(name="AddEntryMB")
#ViewScoped
public class AddEntryMB implements Serializable {
private int rowIndex;
private int idValue;
private transient HtmlDataTable dataTable;
public void setSelectedItem(ValueChangeEvent event) {
rowIndex = dataTable.getRowIndex();
}
public void add()
{
DefaultScheduleEntry entry = new DefaultScheduleEntry();
entry.setId(RandomStringUtils.randomNumeric(32));
entry.setStartTime(from);
entry.setEndTime(until);
entry.setTitle(title);
entry.setSubtitle(location);
entry.setDescription(comments);
}
The view scoped bean will be recreated during every RESTORE_VIEW phase when you bind a component by binding to a property of the view scoped bean. This is known as JSF issue 1492 and fixed for the upcoming JSF 2.2.
In this particular case, you'd better remove binding="#{AddEntryMB.dataTable}" and grab the current var="c" from the EL context.
public void setSelectedItem(ValueChangeEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
DefaultScheduleEntry c = context.getApplication().evaluateExpressionGet(context, "#{c}", DefaultScheduleEntry.class);
// ...
}

JSF Cannot set the current variable entity in the managed bean in order to understand which entity has been selected by the user

Im trying to implement the modification of an entity in JSF using Primefaces.
My main view, which lists the users is the following:
<p:growl id="growlEditUnit" showDetail="true" life="12000" />
<p:dialog id="dialogEditUnit" header="Edit Unit" widgetVar="editUnitDialog" showEffect="fade" hideEffect="fade" resizable="false" >
<ui:include src="editUnit.xhtml" />
</p:dialog>
<h:form id="form2">
<p:dataTable id="units" var="unit" value="#{unitController.unitsOfLoggedInUser}" >
<f:facet name="header">
Click Edit or Delete after selecting a unit to modify or remove it
</f:facet>
<p:column headerText="Code">
#{unit.unitCode}
</p:column>
<p:column headerText="Name">
#{unit.unitName}
</p:column>
<p:column headerText="Semester" >
#{unit.semester}
</p:column>
<p:column headerText="Academic Year">
#{unit.academicYear}
</p:column>
<p:column headerText="Twitter Username">
#{unit.twitterUsername}
</p:column>
<p:column headerText="Actions">
<p:commandButton id="editButton" value="Edit" action="#{unitController.setCurrent(unit)}" update=":dialogEditUnit" oncomplete"editUnitDialog.show()" />
</p:column>
</p:dataTable>
</h:form>
This view lists all the data correctly. However, when I press the current, my aim is to set the current attribute of the managed bean (code listed below) with the unit based on the button clicked. After this I try to update the edit dialog, so it will be filled with the values of that unit, and then make it visible using the oncomplete attribute. However, it seems that the managed been method setCurrent(unit) is never called when clicking the edit button. Subsequently the dialog is shown empty. Can someone help me with what am I doing wrong?
I am posting the managed bean code too.
#ManagedBean(name = "unitController")
#ViewScoped
public class UnitController implements Serializable {
private Unit current;
private List<Unit> unitsOfLoggedInUser;
#ManagedProperty(value="#{loginController.checkedUser}")
private Lecturer lecturer;
#EJB
private web.effectinet.ejb.UnitFacade ejbFacade;
#EJB
private web.effectinet.ejb.LecturerFacade lecturerFacade;
public UnitController() {
}
#PostConstruct
public void init(){
if (lecturer.getLecturerId() == null)
unitsOfLoggedInUser = null;
else
unitsOfLoggedInUser = (List<Unit>) lecturer.getUnitCollection();
}
public List<Unit> getUnitsOfLoggedInUser() {
return unitsOfLoggedInUser;
}
public void setCurrent(Unit current) {
this.current = current;
}
public Lecturer getLecturer() {
return lecturer;
}
public void setLecturer(Lecturer lecturer) {
this.lecturer = lecturer;
}
The action attribute of the commandButton is rendered without information on the value of the unit variable.
To pass the unit to the action method of your managed bean, then you need to pass the ID of unit in an <f:param> child tag of commandButton.
<p:commandButton action="#{managedBean.actionMethod}" ........>
<f:param name="unitid" value="#{unit.id}" />
</p:commandButton>
From your action method you can get the request parameter by the name from the ExternalContext and this will give you the ID of the unit that the commandButton was pressed for in your dataTable.

How to access component's children during a #PostConstruct method?

I want to handle all <p:panel> components inside the <h:panelGroup> in the backing bean. I have bound the <h:panelGroup> to a backing bean property. But during the #PostConstruct method the property is null. During the setter of the property setPanel(), the component has no children. If I submit something using a button, then I can get the panel's children.
What do I have to do to get the component's children during the #PostConstruct method?
View:
<h:panelGroup binding="#{wiz.panel}">
<p:panel header="one">
<h:outputText value="primeiro" />
</p:panel>
<p:panel header="two">
<h:outputText value="segundo" />
<h:inputText />
</p:panel>
<p:panel header="three">
<h:outputText value="terceiro" />
</p:panel>
<p:panel header="four">
<h:outputText value="quarto" />
</p:panel>
</h:panelGroup>
Backing bean
#PostConstruct
public void init() {
if (getPanel() != null) {
for (UIComponent comp : getPanel().getChildren()) {
if (comp instanceof Panel) {
System.out.println(((Panel) comp).getHeader());
}
System.out.println("not a panel child");
}
} else {
System.out.println("panel is null");
}
}
That is not possible. The #PostConstruct can be invoked long before the component tree is finished building. Rather hook on the preRenderView event. At that point the view is guaranteed to be already built. You can attach an event listener method by <f:event> in the view as follows:
<f:event type="preRenderView" listener="#{bean.init}" />
Don't forget to remove the #PostConstruct annotation from the init() method or to rename/split the method if necessary.
Needless to say that this approach is fishy. I suggest to rethink your approach and if necessary ask a new question wherein you state the functional requirement in detail. Perhaps the ultimate answer would be just using plain EL and/or rendered attribute.

Resources