I am working in seam with jsf1.2.
Everything working fine for me, except the search operation. Can anyone please suggest me to go in a right way?
Here, how I am having my form:
<h:form class="input-list" id="searchUser" style="width:100%;"
name="searchUser">
<div class="edit-label">FIRST NAME :</div>
<h:inputText tabindex="1" id="firstName" type="text" class="miniusername clp"
value="#{userListAction.firstName}" required="true">
<f:validateLength minimum="3" maximum="20" />
</h:inputText>
<h:commandButton value="Search" tabindex="2" style="margin-left: 5px"
action="#{userListAction.retrieveName}" class="usersearch">
</h:commandButton>
</h:form>
My interface:
#Local
public interface UserListAction extends Serializable {
public List<User> retrieveCustomers();
public List<User> retrieveEmployees();
public List<User> getUsersList();
public CLRPUser getLoginUser();
public List<User> retrieveName();
#WebRemote
public String deleteById(Integer userId);
#WebRemote
public CLRPUser getUserById(Integer userId);
public UserTypeEnum getUserType();
public void setUserType(UserTypeEnum userType);
public void setFirstName(String firstName);
public String getFirstName();
public CLRPUser getCurrentUser();
public void setCurrentUser(CLRPUser currentUser);
}
Action class which implements the interface:
#Name("userListAction")
#Stateless
#AutoCreate
public class UserListActionImpl implements UserListAction {
#In
protected UserService userService;
#Out(value = "userType", scope = ScopeType.CONVERSATION, required = false)
private UserTypeEnum userType;
#In
private LoggedInUser loggedInUser;
#Out(value = "currentUser", scope = ScopeType.CONVERSATION, required = false)
#In(value = "currentUser", scope = ScopeType.CONVERSATION, required = false)
private CLRPUser currentUser;
#In(value = "firstName", scope = ScopeType.CONVERSATION, required = false)
private String firstName;
/**
*
*/
private static final long serialVersionUID = 8649412602585430272L;
/*
* (non-Javadoc)
*
* #see com.ermms.clrp.user.UserAction#getUsersList()
*/
public List<User> retrieveName() {
System.out.print("FirstName is :" + firstName);
return userService.getAllUsers(firstName);
}
public UserTypeEnum getUserType() {
return this.userType;
}
public void setUserType(UserTypeEnum userType) {
this.userType = userType;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
#Override
public CLRPUser getCurrentUser() {
// TODO Auto-generated method stub
return null;
}
#Override
public void setCurrentUser(CLRPUser currentUser) {
// TODO Auto-generated method stub
}
}
Console says the First name is : null.
I tried more times, but lost my mind in this. Please suggest me.
Why do you inject the firstName in the userListAction-component? Where should this come from?
If there is nothing more, I guess it works as follows:
user enters first name and clicks the command button
the form gets submitted and the entered first name is set into the model using the setter-method
when executing the command button-action Seam-bijection takes place and injects the value for the firstName stored in "some" context. Since it is not defined anywhere, null is injected.
So if you need the injection (for any case), you should put the correct value in the contest at any place. If not, just remove the #In annotation.
Related
I am studying a PrimeFaces AutoComplete demo. I shortenied it from the full showcase demo. http://www.primefaces.org/showcase/ui/input/autoComplete.xhtml
AutoCompleteBean.java
#ManagedBean
public class AutoCompleteBean {
private Query query;
private List<Query> queries = new ArrayList<Query>();
#PostConstruct
public void init() {
queries.add(new Query(0, "Afterdark", "afterdark"));
queries.add(new Query(1, "Afternoon", "afternoon"));
queries.add(new Query(2, "Afterwork", "afterwork"));
queries.add(new Query(3, "Aristo", "aristo"));
}
public List<Query> completeQuery(String query) {
List<Query> filteredQueries = new ArrayList<Query>();
for (int i = 0; i < queries.size(); i++) {
Query skin = queries.get(i);
if(skin.getName().toLowerCase().contains(query)) {
filteredQueries.add(skin);
}
}
return filteredQueries;
}
public void onItemSelect(SelectEvent event) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Item Selected", event.getObject().toString()));
}
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
Query.java
public class Query {
private int id;
private String displayName;
private String name;
public Query() {}
public Query(int id, String displayName, String name) {
this.id = id;
this.displayName = displayName;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
I omitted a Convert class, which I think is not that relevant.
search.xhtml
<h:form>
<p:growl id="msgs" showDetail="true" />
<h:panelGrid columns="2" cellpadding="5">
<p:autoComplete id="queryPojo" value="#{autoCompleteView.query}"
completeMethod="#{autoCompleteView.completeQuery}" var="query"
itemLabel="#{query.displayName}" itemValue="#{query}"
converter="queryConverter" forceSelection="true" />
<p:commandButton value="search" oncomplete="PF('dlg').show()"/>
</h:panelGrid>
</h:form>
I have three questions for this:
1) completeMethod="#{autoCompleteView.completeQuery}": completeQuery method is called without passing a parameter, but it's defined as completeQuery(String query). How does this work?
2) value="#{autoCompleteView.query}". Query is an object defined in AutoCompleteBean. How can this Query object take user input string as its value? Usually InputText's value is good for taking user's input, which is a String value.
3) Can I still add an attribute "action=..." to the p:autoComplete componenet?
The converter class that you omitted here plays the real game.... Lets see your questions
As you see converter class overrides 2 methods
getAsString and getAsObject
1)the value
completeMethod="#{autoCompleteView.completeQuery}
gets refactred to
autoCompleteView.completeQuery(autoCompleteView.query);
as you can find to string method in Query class.
2).as converter is defined for autocomplete it calls getAsString method to render on screen. when selected getAsObject method is called to convert string value to object(Query).
3)you can use ajax select event
<p:ajax event="select" listener="#{autoCompleteView.someMethod}">
or call a remoteCommand by onSelect attribute in p:autoComplete
<p:autoComplete id="queryPojo" value="#{autoCompleteView.query}" onSelect="someRemoteCommand();"
completeMethod="#{autoCompleteView.completeQuery}" var="query"
itemLabel="#{query.displayName}" itemValue="#{query}"
converter="queryConverter" forceSelection="true" />
<p:remoteCommand name="someRemoteCommand" update="queryPojo" actionListener="#{autoCompleteView.execute}" />
This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 7 years ago.
I know this has been discussed a lot, and I also tried most of resolution, but I still got this error:
sourceId=comboNewTaskParent[severity=(ERROR 2), summary=(comboNewTaskParent: Validation Error: Value is not valid), detail=(comboNewTaskParent: Validation Error: Value is not valid)]
Here is the code for HTML:
<h:outputLabel value="Parent task" for="comboNewTaskParent" />
<div class="formRight">
<h:selectOneMenu id="comboNewTaskParent" value="#{taskController.parentTask}" converter="#{taskConverter}"
<f:selectItems value="#{comboTaskByProject}" var="task" itemValue="#{task}" itemLabel="#{task.taskName}" />
</h:selectOneMenu>
</div>
Here is the code of my entity bean:
package com.projectportal.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the Task database table.
*
*/
#Entity
#Table(name="Task")
public class Task implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(unique=true, nullable=false, length=36)
private String taskId;
#Column(length=1000)
private String taskDesc;
#Column(nullable=false)
private int taskDurationHour;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable=false)
private Date taskEstimated;
#Column(nullable=false, length=200)
private String taskName;
#Column(nullable=false)
private float taskPercentComplete;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable=false)
private Date taskStartDate;
//bi-directional many-to-one association to Priority
#ManyToOne
#JoinColumn(name="priorityId", nullable=false)
private Priority priority;
//bi-directional many-to-one association to Project
#ManyToOne
#JoinColumn(name="projectId")
private Project project;
//bi-directional many-to-one association to Status
#ManyToOne
#JoinColumn(name="statusId", nullable=false)
private Status status;
//bi-directional many-to-one association to Task
#ManyToOne
#JoinColumn(name="parentTaskId")
private Task parentTask;
//bi-directional many-to-one association to Task
#OneToMany(mappedBy="parentTask")
private List<Task> childTasks;
//bi-directional many-to-one association to Task
#ManyToOne
#JoinColumn(name="preTaskId")
private Task preTask;
//bi-directional many-to-one association to Task
#OneToMany(mappedBy="preTask")
private List<Task> dependentTasks;
//bi-directional many-to-one association to UserXTask
#OneToMany(mappedBy="task")
private List<UserXTask> userXtasks;
public Task() {
}
public String getTaskId() {
return this.taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskDesc() {
return this.taskDesc;
}
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
public int getTaskDurationHour() {
return this.taskDurationHour;
}
public void setTaskDurationHour(int taskDurationHour) {
this.taskDurationHour = taskDurationHour;
}
public Date getTaskEstimated() {
return this.taskEstimated;
}
public void setTaskEstimated(Date taskEstimated) {
this.taskEstimated = taskEstimated;
}
public String getTaskName() {
return this.taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public float getTaskPercentComplete() {
return this.taskPercentComplete;
}
public void setTaskPercentComplete(float taskPercentComplete) {
this.taskPercentComplete = taskPercentComplete;
}
public Date getTaskStartDate() {
return this.taskStartDate;
}
public void setTaskStartDate(Date taskStartDate) {
this.taskStartDate = taskStartDate;
}
public Priority getPriority() {
return this.priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Project getProject() {
return this.project;
}
public void setProject(Project project) {
this.project = project;
}
public Status getStatus() {
return this.status;
}
public void setStatus(Status status) {
this.status = status;
}
public Task getParentTask() {
return this.parentTask;
}
public void setParentTask(Task parentTask) {
this.parentTask = parentTask;
}
public List<Task> getChildTasks() {
return this.childTasks;
}
public void setChildTasks(List<Task> childTasks) {
this.childTasks = childTasks;
}
public Task getPreTask() {
return this.preTask;
}
public void setPreTask(Task preTask) {
this.preTask = preTask;
}
public List<Task> getDependentTasks() {
return this.dependentTasks;
}
public void setDependentTasks(List<Task> dependentTasks) {
this.dependentTasks = dependentTasks;
}
public List<UserXTask> getUserXtasks() {
return this.userXtasks;
}
public void setUserXtasks(List<UserXTask> userXtasks) {
this.userXtasks = userXtasks;
}
}
The controller:
public #Model class TaskController {
#Inject private EntityManager em;
#Inject Identity identity;
#Inject Logger log;
#Inject Event<Task> taskEventSrc;
#Named
#Produces
private List<Task> requestTaskList;
private Task parentTask;
private Task newTask;
#Produces
#Named
public Task getNewTask(){
return this.newTask;
}
/**
*
*/
public TaskController() {
// TODO Auto-generated constructor stub
}
#PostConstruct
public void loadSelfTasks(){
// Init
newTask = new Task();
// Get user from DB.
User user = em.find(User.class, identity.getUser().getId());
requestTaskList = new ArrayList<Task>();
// Loop user's tasks.
for(UserXTask userTask : user.getUserXtasks()){
requestTaskList.add(userTask.getTask());
}
log.info("Tasks for user: " + user.getFirstname() + " loaded.");
}
/**
* Create task.
* #throws Exception
*/
public void createTask() throws Exception{
log.info("Persistencing task: " + newTask.getParentTask().getTaskId());
em.persist(newTask);
taskEventSrc.fire(newTask);
newTask = new Task();
}
/**
* #return the parentTask
*/
public Task getParentTask() {
return parentTask;
}
/**
* #param parentTask the parentTask to set
*/
public void setParentTask(Task parentTask) {
this.parentTask = parentTask;
}
}
And of course the converter:
#Named
/**
* #author lastcow
*
*/
public class TaskConverter implements Converter {
#Inject EntityManager em;
#Inject Logger log;
/* (non-Javadoc)
* #see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
*/
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
log.info("=========== Convert to Object " + value);
if(value.equals("0")){
return null;
}
Task t = em.find(Task.class, value);
log.info("======== Got : " + t.getTaskName());
return t;
}
/* (non-Javadoc)
* #see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
*/
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
log.info("=========== Convert to String " + value);
return ((Task)value).getTaskId();
}
}
from what logged, the convert are working as it, but when I try to submit the form, always throw 'Validation Error: Value is not valid' ERROR, I have struck here for almost 2 days.
Anyone please give some suggestions.
BTW, I tried put equals and hashCode in Task.java, doesn't working either.
Thanks in advance.
Validation Error: Value is not valid
This error will be thrown when the equals() method of the selected item hasn't returned true for any of the available items in <f:selectItem(s)>. Thus, this can technically have only 2 causes:
The equals() method of your Task class is missing or broken.
The <f:selectItems value="#{comboTaskByProject}"> has incompatibly changed during the postback request of the form submit as compared to during the initial request of the form display.
To fix cause #1, make sure that you understand how to implement equals() properly. You can find kickoff examples here: Right way to implement equals contract
To fix cause #2, make sure that the #{comboTaskByProject} never canges during postback. Best is to put it in the view scope or broader, or to make sure that request based conditions for populating that list are preserved in the postback request by e.g. using <f:viewParam>.
See also:
Our selectOneMenu wiki page
Validation Error: Value is not valid
I am not sure which version of JSF you are using. As far as I know, the converter in HTML should be used like this converter="javax.faces.DateTime". Where this part javax.faces.DateTime is converter name defined in faces-config.xml or in converter class with #FacesConverter.
I try to bring the property of one ManagedBean (SessionScoped) (loginBean) to another (RequestScoped) ManagedBean (newsBean):
<c:set value="#{loginBean.user.nickname}" target="#{newsBean}" property="author" />
<h3>News verfassen:</h3>
<h:form>
<p:inputText label="Titel" value="#{newsBean.title}"></p:inputText>
<p:inputTextarea label="Inhalt" value="#{newsBean.description}"></p:inputTextarea>
<p:commandLink type="button" value="Absenden" action="#{newsBean.writeMsg}"></p:commandLink>
</h:form>
I thought that I can use the c:set tag like in the case I want to set a attribute "staticly".. :)
Maybe someone can help me?
Domii
----- AFTER ANSWER ------
LoginBean:
#ManagedBean
#SessionScoped
public class LoginBean {
public LoginBean() {
email = "";
pwd = "";
device = "";
user = null;
}
private String email;
private String pwd;
private User user;
private String device;
/**
* #return the user
*/
public User getUser() {
return user;
}
/**
* #param user the user to set
*/
public void setUser(User user) {
this.user = user;
}
And NewsBean:
public class NewsBean {
#ManagedProperty("#{loginBean.user.nickname}")
private String nickname;
private String title;
private String description;
/**
* Creates a new instance of NewsBean
*/
public NewsBean() {
}
And yes i also declare the getter /setter for nickname in user!
Just use #ManagedProperty.
#ManagedBean
#ViewScoped
public class NewsBean {
#ManagedProperty("#{loginBean.user.nickname}")
private String author;
// ...
}
I am getting the null Converter error for what I thought was a very simple scenario:
<!-- My View -->
<ui:composition template="/template/template_v1.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<!-- Simplified for clarity -->
<h:form>
<div class="block-panel customer-data">
<h:outputLabel for="txtUsername">Username:</h:outputLabel>
<h:inputText id="txtUsername" name="Username"
value="#{userBean.user.id}"
styleClass="text" />
<rich:message id="errorUsername" for="txtUsername"/>
</div>
<!-- Other fields omitted for clarity -->
</h:form>
/* The User Bean - simplified */
#ManagedBean
#ViewScoped
public class UserBean implements Serializable {
private User user;
public User getUser() {
// Contains logic for reading a user from the database or creating a new
// user object
return user;
}
public void setUser(User user) {
this.user = user;
}
}
/* The user Entity - Simplified */
#Entity
#Table(name = "user")
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name = "user_type", discriminatorType = DiscriminatorType.STRING)
public class User implements IEntity<String>, Serializable {
private static final long serialVersionUID = 1L;
private String id;
#Id
#Column(name = "username", length = 50)
#NotNull(message = "{userIdMandatory}")
#Size(max = 50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
}
/* The IEntity interface */
public interface IEntity<ID extends Serializable> {
ID getId();
void setId(final ID pId);
}
So essentially I'm trying to bind a string property of my user entity to a inputText field. As far as I'm concerned there should be no need for a conversion so I shouldn't be getting the error I'm seeing.
Interestingly, if I add the following getter and setter to my entity:
public String getTmpId() {
return this.id;
}
public void setTmpId(String id) {
this.id = id;
}
And then make the necessary changes to my view to bind to tmpId rather than id, everything works as expected.
This seems like a bug to me either to do with the fact that I am binding to a getter/setter defined in an interface, defined in a generic interface or because the getter is marked with the Id attribute. I would appreciate someone else's ideas however.
As an aside, I have inherited this design and don't particularly like it so I may just end up refactoring it to introduce a new username property rather than trying to use the Id.
To the best of my knowledge I believe this is caused by an obscure bug in BeanELResolver which is used to get the type of the property being bound to - rather than returning String it is returning Serializable, for which there is no converter and hence the error I am seeing.
It's not particularly elegant, but I have worked around this by adding a userId property to my userBean and then binding to that in my view instead of the Id property on the user entity. I then use that value to set the Id manually on the entity when I save it:
<!-- My New View -->
<ui:composition template="/template/template_v1.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<!-- Simplified for clarity -->
<h:form>
<div class="block-panel customer-data">
<h:outputLabel for="txtUsername">Username:</h:outputLabel>
<h:inputText id="txtUsername" name="Username"
value="#{userBean.userId}"
styleClass="text" />
<rich:message id="errorUsername" for="txtUsername"/>
</div>
<!-- Other fields omitted for clarity -->
/* The New User Bean - simplified */
#ManagedBean
#ViewScoped
public class UserBean implements Serializable {
private string userId;
private User user;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public User getUser() {
// Contains logic for reading a user from the database or creating a new
// user object
return user;
}
public void setUser(User user) {
this.user = user;
}
public void saveUser() {
if (user.getId() == null) {
user.setId(userId);
}
// Actual saving omitted for brevity
}
}
I'm a JSF Newbie and having problem with displaying data using datatable. These is my scenario:
I want to display the contract(s) assigned to the Customer
JSF page's Datatable : customerdetail.jsp
<h:dataTable id="dt_contract_list" value="#{customerBean.customer.contracts}" var="item">
<h:column>
<f:facet name="header">
<h:outputText value="Contract Identifier"/>
</f:facet>
<h:outputText style="" value="#{item.contractIdentifier}"></h:outputText>
</h:column>
</h:dataTable>
Entity Bean : Customer.java
#Entity
#NamedQueries({
#NamedQuery(name="getCustomerByName", query="SELECT customer FROM Customer customer WHERE customer.name = :name"),
#NamedQuery(name="getAllCustomer", query="SELECT customer FROM Customer customer")
})
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
#OneToMany(targetEntity = Contract.class,
mappedBy = "customer",
cascade = CascadeType.ALL,
fetch=FetchType.EAGER)
private List<Contract> contracts = new ArrayList<Contract>();
public Customer() {
super();
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public List<Contract> getContracts() {
return this.contracts;
}
#Override
public boolean equals(Object object) {
if (this.getClass().isInstance(object)) {
return this.getName().equals(((Customer) object).getName());
} else {
return false;
}
}
}
BackingBean : CustomerBean.java
public class CustomerBean implements Serializable {
#EJB
private CustomerControllerLocal customerController;
private Customer customer;
public CustomerBean() {
customer = new Customer();
}
public String createCustomer() {
// create customer
}
public String updateCustomer() {
// update customer
}
public String deleteCustomer() {
// delete custoer
}
public String getCustomerByName() {
try {
customerController.getCustomerByName(customer.getName());
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "customer_got";
}
public String assignContractsToCustomer() {
// assign contract to customer
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
There's no errors and the whole business logic layer, data layer were tested and work fine but the result is null (and it shouldn't!) and no sign of any exception. Can anyone help me figure it out what's wrong with this? T___T
Your facelet code looks ok.
In your entity class there is one thing that looks suspicious. It is this line:
private List<Contract> contracts = new ArrayList<Contract>();
In the entity classe for my own projects (classes generated by netbeans) the relationship lists are never initialized. I am no expert in JPA but you could try it without the initialization part.