f2pro
Janeiro 18, 2011, 2:19pm
#1
Preciso selecionar um estabelecimento para poder mudar os menus do meu sistema, mas estou levando um laço na hora de pegar o valor do estabelecimento escolhido…
estou usando o primefaces 2.1 e JSF 2.0
segue abaixo os codigos
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:include src="../includes/head.html"/>
<h:body>
<f:view contentType="text/html">
<!-- <ui:include src="../includes/cabecalho.html"/> -->
<div id="conteudo">
<h:form id="form">
<p:panel style=" width: 329px; margin: 0px auto; margin-top: 15%;">
<h:panelGrid columns="2">
<h:outputText value="Selecione :"/>
<h:selectOneMenu>
<f:selectItems value="#{estabelecimentoMB.estabelecimentos}" var="estabelecimento" itemLabel="#{estabelecimento.nome_razao}" itemValue="#{estabelecimento.codigo_estab}" />
</h:selectOneMenu>
</h:panelGrid>
<p:commandButton value="Selecionar" actionListener="#{estabelecimentoMB.escreveEstabelecimento}" immediate="true">
<f:setPropertyActionListener value="#{estabelecimento}" target="#{estabelecimentoMB.estabelecimentoSelecionado}" />
</p:commandButton>
</p:panel>
</h:form>
</div>
</f:view>
</h:body>
</html>
estabelecimento.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mb;
import beans.Estabelecimento;
import dao.EstabelecimentoJpaController;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
/**
*
* @author F2PRO
*/
@ManagedBean
@RequestScoped
public class EstabelecimentoMB implements Serializable {
/** Creates a new instance of EstabelecimentoMB */
private List<Estabelecimento> estabelecimentos = new ArrayList<Estabelecimento>();
EstabelecimentoJpaController jpa = new EstabelecimentoJpaController();
SelectItem estabelecimentoSelecionado = new SelectItem();
public SelectItem getEstabelecimentoSelecionado() {
return estabelecimentoSelecionado;
}
public void setEstabelecimentoSelecionado(SelectItem estabelecimento) {
//this.estabelecimentoSelecionado = estabelecimento;
System.out.println("valor :" + estabelecimento.getLabel());
}
public List<Estabelecimento> getEstabelecimentos() {
return estabelecimentos;
}
public void setEstabelecimentos(List<Estabelecimento> estabelecimentos) {
this.estabelecimentos = estabelecimentos;
}
public EstabelecimentoJpaController getJpa() {
return jpa;
}
public void setJpa(EstabelecimentoJpaController jpa) {
this.jpa = jpa;
}
public EstabelecimentoMB() {
this.estabelecimentos = jpa.findEstabelecimentoEntities();
}
public void escreveEstabelecimento(ActionEvent actionEvent){
//System.out.println("selecionado: " + this.estabSelecionado.getCodigo_estab());
//System.out.println();
}
}
como faço para pegar o valor do meu select?
[]'s
O selectOneMenu precisa estar ligado à alguma lista no ManagedBean.
<h:selectOneMenu value="#{estabelecimentoMB.estabelecimentosSelecionados}">
<f:selectItems value="#{estabelecimentoMB.estabelecimentos}" ... />
</h:selectOneMenu>
f2pro
Janeiro 18, 2011, 3:06pm
#3
cara… eu dei um print
public void escreveEstabelecimento(ActionEvent actionEvent){
System.out.println("selecionado: " + this.selecionado.getValue());
}
e ele retorna
e mudei o meu select pra maneira que tu me falou
<h:form id="form">
<p:panel style=" width: 329px; margin: 0px auto; margin-top: 30%;">
<h:panelGrid columns="2">
<h:outputText value="Selecione :"/>
<h:selectOneMenu value="#{estabelecimentoMB.selecionado}">
<f:selectItems value="#{estabelecimentoMB.estabelecimentos}" var="estabelecimento" itemLabel="#{estabelecimento.nome_razao}" itemValue="#{estabelecimento.codigo_estab}" />
</h:selectOneMenu>
</h:panelGrid>
<p:commandButton value="Selecionar" actionListener="#{estabelecimentoMB.escreveEstabelecimento}" immediate="true">
</p:commandButton>
</p:panel>
</h:form>
porque não passa o valor?
Precisa ter os gets e sets.
Mas ele só será setado ao executar algum action, e não actionListener.
f2pro
Janeiro 18, 2011, 3:23pm
#5
Vlw… esqueci de coloca os get e sets aqui mas havia criado… erro meu
…
public SelectItem getSelecionado() {
return selecionado;
}
public void setSelecionado(SelectItem selecionado) {
this.selecionado = selecionado;
}
além disso fiz a alteração no commandButton e deixei ele assim
<p:commandButton value="Selecionar" action="#{estabelecimentoMB.escreveEstabelecimento}" immediate="true">
</p:commandButton>
eu alterei o actionListener pelo action
e a minha função escreveEstabelecimento também foi alterada
tive de retirar o antigo parametro q recebia pois deu erro ao chamar a função, creio que seja pela assinatura
erro
public void escreveEstabelecimento(){
System.out.println("selecionado: " + this.selecionado.getValue());
//System.out.println();
}
mas mesmo alterando continua retornando null
f2pro
Janeiro 18, 2011, 3:45pm
#7
Bah gurizada… meu amigo q tbm tava pesquisando conseguiu resolve ai o problema…
de uma maneira simples…
em vez de pegar o objeto inteiro pegamos apenas o id dele sendo do tipo int (primitivo e nao precisando converter) pois tinhamos visto na net várias maneiras e uma delas dizia para converter e isso dava uma volta gigantesca no sistema
agradeço a ajuda de todos e já posto os codigos inteiros para avaliação e ajuda aos próximos
index.html
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:include src="../includes/head.html"/>
<h:body>
<f:view contentType="text/html">
<!-- <ui:include src="../includes/cabecalho.html"/> -->
<div id="conteudo">
<h:form id="form">
<p:panel style=" width: 329px; margin: 0px auto; margin-top: 30%;">
<h:panelGrid columns="2">
<h:outputText value="Selecione :"/>
<h:selectOneMenu value="#{estabelecimentoMB.selecionado}" >
<f:selectItems value="#{estabelecimentoMB.estabelecimentos}" var="estabelecimento" itemLabel="#{estabelecimento.nome_razao}" itemValue="#{estabelecimento.codigo_estab}" />
</h:selectOneMenu>
</h:panelGrid>
<p:commandButton value="Selecionar" action="#{estabelecimentoMB.escreveEstabelecimento}">
</p:commandButton>
</p:panel>
</h:form>
</div>
</f:view>
</h:body>
</html>
EstabelecimentoMB.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mb;
import beans.Estabelecimento;
import dao.EstabelecimentoJpaController;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author F2PRO
*/
@ManagedBean
@RequestScoped
public class EstabelecimentoMB implements Serializable {
/** Creates a new instance of EstabelecimentoMB */
private List<Estabelecimento> estabelecimentos = new ArrayList<Estabelecimento>();
EstabelecimentoJpaController jpa = new EstabelecimentoJpaController();
int selecionado;
public int getSelecionado() {
return selecionado;
}
public void setSelecionado(int selecionado) {
this.selecionado = selecionado;
}
public List<Estabelecimento> getEstabelecimentos() {
return estabelecimentos;
}
public void setEstabelecimentos(List<Estabelecimento> estabelecimentos) {
this.estabelecimentos = estabelecimentos;
}
public EstabelecimentoJpaController getJpa() {
return jpa;
}
public void setJpa(EstabelecimentoJpaController jpa) {
this.jpa = jpa;
}
public EstabelecimentoMB() {
this.estabelecimentos = jpa.findEstabelecimentoEntities();
}
public void escreveEstabelecimento(){
System.out.println("selecionado: " + this.selecionado);
//System.out.println();
}
}
abraços…
Olá Amigos. Eu estou ainda com problemas no selectOneMenu . Meu retorno continua NULL mesmo com o converter certinho.
package br.com.totalsig.controller;
import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import br.com.totalsig.model.Empresa;
import br.com.totalsig.repository.EmpresaRepository;
@Named
@SessionScoped
public class Configuracao implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private EmpresaRepository empresaRepository;
private List<Empresa> listaEmpresas;
Empresa empresa;
public Configuracao(){
limparCampos();
}
public void selecionarEmpresa(){
System.out.println("Gravar Empresa na Session: "+this.empresa);
}
public List<Empresa> getListaEmpresas() {
return listaEmpresas;
}
public void setListaEmpresas(List<Empresa> listaEmpresas) {
this.listaEmpresas = listaEmpresas;
}
public void inicializar(){
listaEmpresas = empresaRepository.listaEmpresas();
}
public Empresa getEmpresa() {
return empresa;
}
public void setEmpresa(Empresa empresa) {
this.empresa = empresa;
}
private void limparCampos() {
empresa = new Empresa();
listaEmpresas = null;
}
}
No arquivo XHTML
<ui:composition template="/WEB-INF/template/LayoutPadrao.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui" xmlns:o="http://omnifaces.org/ui">
<ui:define name="titulo">TotalSig - Softwares Corporativos</ui:define>
<ui:define name="corpo">
<f:metadata>
<f:event listener="#{configuracao.inicializar}" type="preRenderView" />
</f:metadata>
<br />
<br />
<div align="center">
<IMG src="resources/images/img_home_empresa.png" />
</div>
<h3 align="center">Selecione uma Empresa</h3>
<div align="center">
<p:selectOneMenu id="empresa" value="#{configuracao.empresa}">
<f:selectItem itemLabel="" />
<f:selectItems value="#{configuracao.listaEmpresas}" var="empresa"
itemLabel="#{empresa.nome}" itemValue="#{empresa}"
itemDescription="#{empresa.nome}" />
<f:ajax listener="#{configuracao.selecionarEmpresa(empresa)}" />
</p:selectOneMenu>
</div>
</ui:define>
</ui:composition>