Erro no JSF - não encontra método

26/07/2011

0

Tenho o seguinte trecho em uma página jsp

<h:outputLabel value="Descrição:"/>
            <h:panelGroup>
                <h:inputText id="descricao" size="40" maxlength="150" value="#{cadastroContaBean.contaEdicao.descricao }" label="Descrição" required="true"></h:inputText>
                <rich:suggestionbox for="descricao" suggestionAction="#{cadastroContaBean.sugerirDescricao }" width="230" height="120" var="item">
                    <h:column>
                        <h:outputText value="#{item }"/>
                    </h:column>
                </rich:suggestionbox>
                <h:message for="descricao" showSummary="true" showDetail="false" styleClass="msgErro"></h:message>
            </h:panelGroup>


Quando o métdo sugerirDescricao da managed bean CadastroContaBean é chamado aparece o seguinte erro

GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/Financeiro] threw exception [/contas/cadastroConta.jsp(49,4) '#{cadastroContaBean.sugerirDescricao }' Method not found: com.algaworks.dwjsf.financeiro.visao.CadastroContaBean@369bb.sugerirDescricao(java.lang.Object)] with root cause
org.apache.jasper.el.JspMethodNotFoundException: /contas/cadastroConta.jsp(49,4) '#{cadastroContaBean.sugerirDescricao }' Method not found: com.algaworks.dwjsf.financeiro.visao.CadastroContaBean@369bb.sugerirDescricao(java.lang.Object)

Ou seja, diz que meu método não foi encontrado, porém ele está lá. Vou mostrar meus códigos completos:

cadastroConta.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f"  uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h"  uri="http://java.sun.com/jsf/html"%>
<%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cadastro de conta</title>
<link rel="stylesheet" type="text/css" href="../css/estilo.css"/>
</head>
<body>
<f:view>
    <h:form id="frm">
        <h1><h:outputText value="Cadastro de conta"/></h1>
        
        <h:messages layout="table" showSummary="true"
            showDetail="false" globalOnly="true"
            styleClass="msgErro" infoClass="msgInfo"
            style="font-weight: bold"/>
        
        <h:panelGrid columns="2">
            <h:outputLabel value="Código:" rendered="#{cadastroContaBean.contaEdicao.id != null }"></h:outputLabel>
            <h:panelGroup rendered="#{cadastroContaBean.contaEdicao.id != null }">
                <h:inputText id="codigo" size="10" value="#{cadastroContaBean.contaEdicao.id }" label="Código da conta" disabled="true"/>
                <h:message for="codigo" showSummary="true" showDetail="false" styleClass="msgErro"/>
            </h:panelGroup>
            
            <h:outputLabel value="Pessoa:"/>
            <h:panelGroup>
                <h:selectOneMenu id="pessoa" value="#{cadastroContaBean.contaEdicao.pessoa }" label="Pessoa" required="true">
                    <f:selectItems value="#{cadastroContaBean.pessoas }"/>
                </h:selectOneMenu>
                <h:message for="pessoa" showSummary="true" showDetail="false" styleClass="msgErro"/>    
            </h:panelGroup>
            
            <h:outputLabel value="Tipo:"/>
            <h:panelGroup>
                <h:selectOneRadio id="tipo" value="#{cadastroContaBean.contaEdicao.tipo }" label="Tipo da Conta" required="true">
                    <f:selectItems value="#{cadastroContaBean.tiposLancamentos }"/>
                </h:selectOneRadio>
                <h:message for="tipo" showSummary="true" showDetail="false" styleClass="msgErro"></h:message>
            </h:panelGroup>
            
            <h:outputLabel value="Descrição:"/>
            <h:panelGroup>
                <h:inputText id="descricao" size="40" maxlength="150" value="#{cadastroContaBean.contaEdicao.descricao }" label="Descrição" required="true"></h:inputText>
                <rich:suggestionbox for="descricao" suggestionAction="#{cadastroContaBean.sugerirDescricao }" width="230" height="120" var="item">
                    <h:column>
                        <h:outputText value="#{item }"/>
                    </h:column>
                </rich:suggestionbox>
                <h:message for="descricao" showSummary="true" showDetail="false" styleClass="msgErro"></h:message>
            </h:panelGroup>                         <h:outputLabel value="Valor:"/>             <h:panelGroup>                 <h:inputText id="valor" size="12" maxlength="10" value="#{cadastroContaBean.contaEdicao.valor }" label="Valor" required="true">                     <f:convertNumber minFractionDigits="2"/>                 </h:inputText>                 <h:message for="valor" showSummary="true" showDetail="false" styleClass="msgErro" ></h:message>             </h:panelGroup>                         <h:outputLabel value="Data vencimento:"/>             <h:panelGroup>                 <rich:calendar id="dataVencimento" inputSize="12" value="#{cadastroContaBean.contaEdicao.dataVencimento }" label="Data Vencimento" required="true" datePattern="dd/MM/yyyy" enableManualInput="true" />                 <h:message for="dataVencimento" showSummary="true" showDetail="false" styleClass="msgErro"></h:message>             </h:panelGroup>                         <h:outputLabel value="Data baixa:"/>             <h:panelGroup>                 <rich:calendar id="dataBaixa" inputSize="12" value="#{cadastroContaBean.contaEdicao.dataBaixa }" label="Data Baixa" required="false" datePattern="dd/MM/yyyy" enableManualInput="true" />                 <h:message for="dataBaixa" showSummary="true" showDetail="false" styleClass="msgErro"></h:message>             </h:panelGroup>                         <h:panelGroup>                 <a4j:commandButton value="Salvar" actionListener="#{cadastroContaBean.salvar }" reRender="frm" type="submit"/>                 <h:commandButton value="Cancelar" action="menu" immediate="true"></h:commandButton>             </h:panelGroup>         </h:panelGrid>     </h:form> </f:view> </body> </html>


CadastroContaBean.java
package com.algaworks.dwjsf.financeiro.visao;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;

import com.algaworks.dwjsf.financeiro.dominio.Conta;
import com.algaworks.dwjsf.financeiro.dominio.Pessoa;
import com.algaworks.dwjsf.financeiro.dominio.TipoConta;
import com.algaworks.dwjsf.financeiro.negocio.ContaService;
import com.algaworks.dwjsf.financeiro.negocio.PessoaService;
import com.algaworks.dwjsf.financeiro.negocio.RegraNegocioException;

public class CadastroContaBean {

    private Conta contaEdicao;
    private List<SelectItem> tiposContas;
    private List<SelectItem> pessoas;
    
    public String inicializar(){
        this.contaEdicao = new Conta();
        this.tiposContas = null;
        this.pessoas = null;
        System.out.println("1");
        return "cadastroConta";
    }
    
    public void salvar(ActionEvent event){
        FacesContext context = FacesContext.getCurrentInstance();
        try{
            new ContaService().salvar(this.contaEdicao);
            this.contaEdicao = new Conta();
            FacesMessage msg = new FacesMessage("Conta salva com sucesso!");
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            context.addMessage(null, msg);
        }
        catch(RegraNegocioException e){
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), e.getMessage()));
        }
        catch(Exception e){
            e.printStackTrace();
            FacesMessage msg = new FacesMessage("Erro inesperado ao salvar conta!");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, msg);
        }
    }
    
    public List<SelectItem> getPessoas(){
        if(this.pessoas == null){
            this.pessoas = new ArrayList<SelectItem>();
            List<Pessoa> pessoas = new PessoaService().listarTodas();
            this.pessoas.add(new SelectItem(null, "Selecione"));
            for(Pessoa pessoa: pessoas){
                this.pessoas.add(new SelectItem(pessoa, pessoa.getNome()));
            }
        }
        return this.pessoas;
    }
    
    public List<SelectItem> getTiposLancamentos(){
        if(this.tiposContas == null){
            this.tiposContas = new ArrayList<SelectItem>();
            for(TipoConta tipo: TipoConta.values()){
                this.tiposContas.add(new SelectItem(tipo, tipo.toString()));
            }
        }
        return tiposContas;
    }
    
    public List<String> sugerirDescricao(Object event){
        return new ContaService().pesquisarDescricoes(event.toString());
    }     public Conta getContaEdicao() {         return contaEdicao;     }     public void setContaEdicao(Conta contaEdicao) {         this.contaEdicao = contaEdicao;     } }


faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>

<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
    
    <application>
        <message-bundle>
            com.algaworks.dwjsf.financeiro.recursos.messages
        </message-bundle>
    </application>
    
    <application>
          <view-handler>org.ajax4jsf.application.AjaxViewHandler</view-handler>
    </application>
    
    <managed-bean>
        <managed-bean-name>cadastroContaBean</managed-bean-name>
        <managed-bean-class>com.algaworks.dwjsf.financeiro.visao.CadastroContaBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>         <managed-bean>         <managed-bean-name>consultaContaBean</managed-bean-name>         <managed-bean-class>com.algaworks.dwjsf.financeiro.visao.ConsultaContaBean</managed-bean-class>         <managed-bean-scope>session</managed-bean-scope>     </managed-bean>         <managed-bean>         <managed-bean-name>helloRichBean</managed-bean-name>         <managed-bean-class>com.algaworks.dwjsf.financeiro.visao.HelloRichBean</managed-bean-class>         <managed-bean-scope>request</managed-bean-scope>     </managed-bean>         <navigation-rule>         <navigation-case>             <from-outcome>cadastroConta</from-outcome>             <to-view-id>/contas/cadastroConta.jsp</to-view-id>         </navigation-case>         <navigation-case>             <from-outcome>consultaConta</from-outcome>             <to-view-id>/contas/consultaConta.jsp</to-view-id>         </navigation-case>     </navigation-rule>         <navigation-rule>         <navigation-case>             <from-outcome>menu</from-outcome>             <to-view-id>/menu.jsp</to-view-id>             <redirect/>         </navigation-case>     </navigation-rule>         <converter>         <converter-for-class>java.lang.Enum</converter-for-class>         <converter-class>com.algaworks.dwjsf.financeiro.conversores.EnumConverter</converter-class>     </converter>         <converter>         <converter-for-class>com.algaworks.dwjsf.financeiro.dominio.Pessoa</converter-for-class>         <converter-class>com.algaworks.dwjsf.financeiro.conversores.PessoaConverter</converter-class>     </converter> </faces-config>


ContaService.java
package com.algaworks.dwjsf.financeiro.negocio;

import java.math.BigDecimal;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.algaworks.dwjsf.financeiro.dominio.Conta;
import com.algaworks.dwjsf.financeiro.util.HibernateUtil;

public class ContaService {
    
    public void salvar(Conta conta) throws RegraNegocioException{
    if(conta.getValor().compareTo(BigDecimal.ZERO) <= 0){
        throw new RegraNegocioException("Valor da conta deve ser maior que zero.");
    }
    
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    
    session.saveOrUpdate(conta);
    
    tx.commit();
    session.close();
    }
    
    public Conta pesquisarPorId(Long id){
        Session session = HibernateUtil.getSession();
        try{
            return(Conta) session.get(Conta.class, id);
        }
        finally{
            session.close();
        }
    }
    
    @SuppressWarnings("unchecked")
    public List<Conta> listarTodas(){
        Session session = HibernateUtil.getSession();
        try{
            return session.createCriteria(Conta.class).addOrder(Order.desc("dataVencimento")).list();
        }
        finally{
            session.close();
        }
    }
    
    public void excluir(Conta conta) throws RegraNegocioException{
        if(conta.getDataBaixa() != null){
            throw new RegraNegocioException("Esta conta não pode ser excluída, pois já foi baixada");
        }
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();
        
        session.delete(conta);
        
        tx.commit();
        session.close();
    }
    

    @SuppressWarnings("unchecked")
    public List<String> pesquisarDescricoes(String descricao){
        Session session = HibernateUtil.getSession();
        try{
            return session.createCriteria(Conta.class).setProjection(Projections.distinct(Projections.property("descricao"))).add(Restrictions.ilike("descricao", descricao, MatchMode.ANYWHERE)).addOrder(Order.asc("descricao")).list();
        }
        finally{
            session.close();
        }
    } }


log completo do erro

GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/Financeiro] threw exception [/contas/cadastroConta.jsp(49,4) '#{cadastroContaBean.sugerirDescricao }' Method not found: com.algaworks.dwjsf.financeiro.visao.CadastroContaBean@369bb.sugerirDescricao(java.lang.Object)] with root cause
org.apache.jasper.el.JspMethodNotFoundException: /contas/cadastroConta.jsp(49,4) '#{cadastroContaBean.sugerirDescricao }' Method not found: com.algaworks.dwjsf.financeiro.visao.CadastroContaBean@369bb.sugerirDescricao(java.lang.Object)
    at org.apache.jasper.el.JspMethodExpression.invoke(JspMethodExpression.java:73)
    at org.richfaces.component.UISuggestionBox.setupValue(UISuggestionBox.java:492)
    at org.richfaces.component.UISuggestionBox.broadcast(UISuggestionBox.java:424)
    at javax.faces.component.UIData.broadcast(UIData.java:1093)
    at org.richfaces.component.UISuggestionBox.broadcast(UISuggestionBox.java:421)
    at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:329)
    at org.ajax4jsf.component.AjaxViewRoot.broadcastAjaxEvents(AjaxViewRoot.java:348)
    at org.ajax4jsf.application.AjaxViewHandler.processAjaxEvents(AjaxViewHandler.java:216)
    at org.ajax4jsf.application.AjaxViewHandler.renderView(AjaxViewHandler.java:169)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206)
    at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
    at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
    at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:403)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:301)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:162)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)


Robson Silva

Robson Silva

Responder

Posts

26/07/2011

Davi Costa

Dá uma olhada nesse parâmetro se é Object mesmo. Na verdade se deveria ser Object ou outro tipo de parâmetro, ou até mesmo sem parâmetro algum.

att Davi
Responder

27/07/2011

Robson Silva

Dá uma olhada nesse parâmetro se é Object mesmo. Na verdade se deveria ser Object ou outro tipo de parâmetro, ou até mesmo sem parâmetro algum.

att Davi


O parâmetro é Object mesmo, em todos os exemplos na internet do suggestionbox do richfaces o parametro é Object
Responder

27/07/2011

Davi Costa

Retirado do livro Pratical RichFaces:

http://sica.googlecode.com/svn-history/r145/trunk/Documentos/Materiales/Katz-Practical_RichFaces.pdf

...
Using <rich:suggestionbox>
<rich:suggestionbox> is a true suggestion component; the component retrieves suggested
data from the server based on what was entered. I’ll show how to build the example shown
here. As input is entered, you want to see states that start with that letter, but not only the
name; you also want the capital and state flag.
Here is how this component works. The user starts entering a value into the input field,
and a request is sent to the server where a listener is invoked. The listener is being passed the
value entered into the input field. The listener then returns suggested values based on the
input entered. Basically, it is the developer’s responsibility to implement the part that returns
the suggested values, while the component knows how to render the returned data.
The <rich:suggestionbox> component doesn’t provide the input field, so you have to attach
the component to a particular input field. In the following example, I’ll start by showing the
managed bean first:
public class StatesSuggestionBean {
private List<State> statesList;
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@PostConstruct
public void init() {
statesList = new ArrayList<State>();
statesList.add(new State("Alabama", "Montgomery"));
statesList.add(new State("Alaska", "Juneau"));
statesList.add(new State("Arizona", "Phoenix"));
statesList.add(new State("Arkansas", "Little Rock"));
statesList.add(new State("California", "Sacramento"));
statesList.add(new State("Colorado", "Denver"));
statesList.add(new State("Connecticut", "Hartford"));
statesList.add(new State("Delaware", "Dover"));
statesList.add(new State("Florida", "Tallahassee"));
statesList.add(new State("Georgia", "Atlanta"));
statesList.add(new State("Hawaii", "Honolulu"));
statesList.add(new State("Idaho", "Boise"));
statesList.add(new State("Illinois", "Springfield"));
statesList.add(new State("Indiana", "Indianapolis"));
statesList.add(new State("Iowa", "Des Moines"));
statesList.add(new State("Kansas", "Topeka"));
statesList.add(new State("Kentucky", "Frankfort"));
statesList.add(new State("Louisiana", "Baton Rouge"));
statesList.add(new State("Maine", "Augusta"));
statesList.add(new State("Maryland", "Annapolis"));
statesList.add(new State("Massachusetts", "Boston"));
statesList.add(new State("Michigan", "Lansing"));
statesList.add(new State("Minnesota", "St. Paul"));
statesList.add(new State("Mississippi", "Jackson"));
statesList.add(new State("Missouri", "Jefferson City"));
statesList.add(new State("Montana", "Helena"));
statesList.add(new State("Nebraska", "Lincoln"));
statesList.add(new State("Nevada", "Carson City"));
statesList.add(new State("New Hampshire", "Concord"));
statesList.add(new State("New Jersey", "Trenton"));
statesList.add(new State("New Mexico", "Santa Fe"));
statesList.add(new State("New York", "Albany"));
statesList.add(new State("North Carolina", "Raleigh"));
statesList.add(new State("North Dakota", "Bismarck"));
statesList.add(new State("Ohio", "Columbus"));
statesList.add(new State("Oklahoma", "Oklahoma City"));
statesList.add(new State("Oregon", "Salem"));
statesList.add(new State("Pennsylvania", "Harrisburg"));
statesList.add(new State("Rhode Island", "Providence"));
statesList.add(new State("South Carolina", "Columbia"));
statesList.add(new State("South Dakota", "Pierre"));
statesList.add(new State("Tennessee", "Nashville"));
statesList.add(new State("Texas", "Austin"));
statesList.add(new State("Utah", "Salt Lake City"));
statesList.add(new State("Vermont", "Montpelier"));
statesList.add(new State("Virginia", "Richmond"));
statesList.add(new State("Washington", "Olympia"));
statesList.add(new State("West Virginia", "Charleston"));
statesList.add(new State("Wisconsin", "Madison"));
statesList.add(new State("Wyoming", "Cheyenne"));
}
public List<State> getStatesList() {
return statesList;
}
}

The State class looks like this:
public class State {
private String name;
private String capital;
private String flagImage;
// getters and setters omitted for code clarity
public State (String name, String capital){
this.name = name;
this.capital = capital;
this.flagImage =
"/images/states/flag_"+(name.toLowerCase()).replace(" ", "")+".gif";
}
}

So, this is your model. You haven’t yet implemented the listener that will return the suggested
values. You will do that shortly. Let’s now write the JSF page.
To start, your page will look like this:
<h:form>
<h:inputText value="#{statesSuggestionBean.state}" id="stateInput"/>
</h:form>
Nothing really is interesting here—it’s just a standard input field. The next step is to attach
the suggestion box component to this input field. Basically, as you start typing, you would like
to see state information based on the input entered.
First, let’s create the suggestion box and attach it to the input field:
<h:form>
<h:inputText value="#{statesSuggestionBean.state}" id="stateInput"/>
<rich:suggestionbox for="stateInput">
</rich:suggestionbox>
</h:form>
The for attribute points to the ID of the input component. Next, you need to create the
suggestion action that will return values based on input provided. Here is how it looks; it is
placed inside the managed bean:
public ArrayList <State> suggest (Object value){
String input = (String)value;
ArrayList <State> result = new ArrayList <State>();
for(State state : statesList) {
if ((state.getName().toLowerCase()).startsWith(input.toLowerCase()))
result.add(state);
}
return result;
}
All you are doing is going through the list of states and checking whether the current state
name starts with the input entered. Because this is inside a managed bean, you are free to
implement any other method of retrieving the suggested values. What’s important is that the
action needs to return a collection of objects to be displayed in a pop-up menu. Let’s go back
to the page and add markup to display the values:
<rich:suggestionbox suggestionAction="#{statesSuggestionBean.suggest}"
var="state"
for="stateInput">
<h:column>
#{state.name}
</h:column>
</rich:suggestionbox>
You first use the suggstionAction attribute to bind to the suggest action in the managed
beans. This action will return suggested states. If you notice, you are using <h:column> here.
The suggestion box component pop-up menu works just like a data table. You have also specified
a var attribute to display each record from the collection.
Running what you have so far will result in the following:
Adding More Columns
Because the component works similarly to a data table, you can add columns and display more
information in the pop-up menu. Here’s code to add two more columns to the suggestion box:
<rich:suggestionbox suggestionAction="#{statesSuggestionBean.suggest}"
var="state"
for="stateInput">
<h:column>
#{state.name}
</h:column>
<h:column>
#{state.capital}
</h:column>
<h:column>
<h:graphicImage value="#{state.flagImage}"/>
</h:column>
</rich:suggestionbox>

And here’s the code to add the width attribute:
<h:inputText value="#{statesSuggestionBean.state}" id="stateInput"/>
<rich:suggestionbox suggestionAction="#{statesSuggestionBean.suggest}"
var="state"
for="stateInput"
width="350">
<h:column>..<h:column>
</rich:suggestionbox>
As you can see, the component is very flexible. You can display any type of information in
any number of columns.
Adding More Features
Notice that when a selection is made, the state name is inserted (or set) into the input field. The
state name is inserted by default because it is the first column defined. Suppose instead of the state
name, you want to select the capital name. Rearranging the columns is not a good solution. All
you have to do is set the fetchValue attribute to the value to be inserted into the input field:
<rich:suggestionbox suggestionAction="#{statesSuggestionBean.suggest}"
var="state"
for="stateInput"
width="350"
fetchValue="#{state.capital}">
It doesn’t matter in what order the columns are displayed. Using fetchValue, you can
always select the property to insert. You can use the fetchValue attribute to define any insertion
value. For example:
fetchValue="#{state.name} – #{state.capital}"
Another useful attribute is minChars, which specifies the minimum number of characters
in the input needed to activate the pop-up menu. If the suggestion list is rather large, it might
not be efficient to start filtering when only a few characters have been entered. So, to delay the
activation, you can set minChars, for example:
<rich:suggestionbox suggestionAction="#{statesSuggestionBean.suggest}"
var="state"
for="stateInput"
width="350"
fetchValue="#{state.capital}"
minChars="3">
This means that no request will be sent until three characters have been entered. All standard
Ajax optimization attributes are available as well.
If no data is returned from the server, you can display a default message notifying the user
that no information was returned by setting the nothingLabel attribute:
<rich:suggestionbox suggestionAction="#{statesSuggestionBean.suggest}"
var="state"
for="stateInput"
width="350"
fetchValue="#{state.capital}"
minChars="3"
nothingLabel="No states found">
Let’s move to the next component, which also provides similar suggestlike functionality,
but instead of getting information from the server, it prerenders everything to the client.




att Davi
Responder

05/08/2011

Dyego Carmo

Opa !

Resolvido ?

Se sim, por favor feche o chamado :)

Valeu !
Responder

Assista grátis a nossa aula inaugural

Assitir aula

Saiba por que programar é uma questão de
sobrevivência e como aprender sem riscos

Assistir agora

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar