3
respostas

keypress está executando action do h:commandButton

Boa noite, está ocorrendo algo estranho que não compreendi. Quando coloco o event="keypress" no campo isbn, o método do bean é chamado corretamente, mas, ao finalizar, chama também o método que está no action do h:commandButton, mas o botão não foi clicado, e aí fica somente a mensagem do método do h:commandButton. Se eu deixar event="blur", a validação ocorre corretamente validando somente o campo isbn.

<?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:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">

<h:head />
<h:body>
    <h1>Novo Livro</h1>
    <h:form>
        <h:messages id="messages"/>
        <fieldset>
            <legend>Dados do Livro</legend>
            <h:panelGrid columns="2">

                <h:outputLabel value="Titulo:" for="titulo" />
                <h:inputText id="titulo" value="#{livroBean.livro.titulo}" required="true" requiredMessage="Título obrigatório" validatorMessage="Valor máximo de 40 caracteres">
                    <f:validateLength maximum="40"/>
                    <f:ajax event="blur" render="messages"/>
                </h:inputText>

                <h:outputLabel value="ISBN:" for="isbn" />
                <h:inputText id="isbn" value="#{livroBean.livro.isbn}" validator="#{livroBean.comecaComDigitoUm}">
                    <f:ajax event="keypress" render="messages"/>
                </h:inputText>

                <h:outputLabel value="Preço:" for="preco" />
                <h:inputText id="preco" value="#{livroBean.livro.preco}" validatorMessage="Preço deve ser entre 1 e 1000" >
                    <f:validateDoubleRange minimum="1.0" maximum="1000.00"/>
                </h:inputText>

                <h:outputLabel value="Data de Lançamento:" for="dataLancamento" />
                <h:inputText id="dataLancamento" value="#{livroBean.livro.dataLancamento.time}" >
                    <f:convertDateTime pattern="dd/MM/yyyy HH:mm" />
                </h:inputText>

            </h:panelGrid>
        </fieldset>

        <fieldset>
            <legend>Dados do Autor</legend>
            <h:outputLabel value="Selecione o Autor: " for="autor"/>
            <h:selectOneMenu value="#{livroBean.autorId}" id="autor">
                <f:selectItem itemLabel="Selecione..." itemValue="#{null}" noSelectionOption="true"/>
                <f:selectItems value="#{livroBean.autores}" var="autor" itemLabel="#{autor.nome}" itemValue="#{autor.id}"/>
            </h:selectOneMenu>
            <h:commandButton value="Gravar Autor" action="#{livroBean.gravarAutor}">
                <f:ajax execute="autor" render="tabelaAutores messages"/> 
            </h:commandButton>
            <br />
            <h:commandLink value="Cadastrar novo autor" action="#{livroBean.formAutor}" immediate="true"/>

            <h:dataTable value="#{livroBean.autoresDoLivro}" var="autor" id="tabelaAutores">
                <h:column>
                    <h:outputText value="#{autor.nome}"/>
                </h:column>
            </h:dataTable>
        </fieldset>

        <h:commandButton value="Gravar" action="#{livroBean.gravar}">        
            <f:ajax execute="@form" render="@form :tabelaLivros" />
        </h:commandButton>
    </h:form>    

    <h:dataTable value="#{livroBean.livros}" var="livro" id="tabelaLivros">
        <h:column>
          <f:facet name="header">Título</f:facet>
          <h:outputText value="#{livro.titulo}" />
        </h:column>

        <h:column>
          <f:facet name="header">ISBN</f:facet>
          <h:outputText value="#{livro.isbn}" />
        </h:column>

        <h:column>
          <f:facet name="header">Preço</f:facet>
          <h:outputText value="#{livro.preco}" />
        </h:column>

        <h:column>
          <f:facet name="header">Data</f:facet>
          <h:outputText value="#{livro.dataLancamento.time}" >
              <f:convertDateTime pattern="dd/MM/yyyy HH:mm" timeZone="America/Sao_Paulo"/>
          </h:outputText>
        </h:column>        
    </h:dataTable>        

</h:body>

</html>
3 respostas

Oi Marcio, tudo bem?

estranho esse comportamento mesmo.... copiei seu código aqui e funcionou normal. Você pode enviar o seu Bean tb?

Oi Samir, segue o bean

package br.com.caelum.livraria.bean;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import br.com.caelum.livraria.dao.DAO;
import br.com.caelum.livraria.modelo.Autor;
import br.com.caelum.livraria.modelo.Livro;

@ManagedBean
@ViewScoped
public class LivroBean {

    private Livro livro = new Livro();

    private Integer autorId;

    public Integer getAutorId() {
        return autorId;
    }

    public void setAutorId(Integer autorId) {
        this.autorId = autorId;
    }

    public Livro getLivro() {
        return livro;
    }

    public void setLivro(Livro livro) {
        this.livro = livro;
    }

    public List<Autor> getAutores(){
        return new DAO<Autor>(Autor.class).listaTodos();
    }

    public List<Autor> getAutoresDoLivro(){
        return this.livro.getAutores();
    }

    public List<Livro> getLivros() {
        return new DAO<Livro>(Livro.class).listaTodos();
    }    

    public void gravarAutor(){
        Autor autor = new DAO<Autor>(Autor.class).buscaPorId(this.autorId);
        if(autor == null){
            FacesContext.getCurrentInstance().addMessage("autor", new FacesMessage("Selecione um Autor"));
        }else{
            this.livro.adicionaAutor(autor);
            System.out.println("Livro escrito por: " + autor.getNome());
        }
    }

    public void gravar() {
        System.out.println("Gravando livro " + this.livro.getTitulo());

        if (livro.getAutores().isEmpty()) {
            //throw new RuntimeException("Livro deve ter pelo menos um Autor.");
            FacesContext.getCurrentInstance().addMessage("autor", new FacesMessage("Livro deve ter pelo menos um Autor."));
            return;
        }

        if(this.livro.getId() == null){
            new DAO<Livro>(Livro.class).adiciona(this.livro);
        }else{
            new DAO<Livro>(Livro.class).atualiza(this.livro);
        }
        this.livro = new Livro();
    }

    public void remover(Livro livro){
        System.out.println("Removendo livro");
        new DAO<Livro>(Livro.class).remove(livro);
    }

    public void removerAutorDoLivro(Autor autor){
        this.livro.removeAutor(autor);
    }

    public String formAutor(){
        System.out.println("Chamando o formulário do Autor");
        return "autor?faces-redirect=true";
    }

    public void comecaComDigitoUm(FacesContext fc, UIComponent component, Object value) throws ValidatorException{
        String valor = value.toString();
        if(!valor.startsWith("1")){
            throw new ValidatorException(new FacesMessage("ISBN deve começar com 1"));
        }
    }
}

fala Marcio, tudo bem?

parece estar tudo ok com o seu Bean e com a sua view. O erro continua?

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software