About Selectoneradio

Asked

Viewed 181 times

0

Hello, guys. I’m creating a program that manipulates user registration. Each registered user has fields such as name, rg, Cpf...... and a field called status, which shows the status of this client’s registration. The status can be either "active" or "inactive". In this program, I’m having difficulties in the search screen to view registered users. On this screen there is a Selectoneradio that has three options: "active", "inactive" and "all".

On the search screen, a double filter will be performed. For example, if in the search field "Rune" is filled and the "active" option is selected in Selectoneradio, the system will have to search for all Runes with "active" status".

But I’m having trouble creating a function that identifies the option that the user has marked in Selectoneradio and perform the double search filter. The search by name I managed to implement, but I’m having difficulties to perform the filtering by name and status simultaneously. I’m posting the codes that influence the search screen. are "Search users.xhtml", "Search users.java", "Usuariosrep.java" and "Usuariofilter.java"

Searcher.xhtml. Search Users

<ui:define name="corpo">
    <h:form id="frmPesquisa">
    <p:messages showDetail="false" showSummary="true" autoUpdate="true" />

    <h1>Pesquisa de usuários</h1>

    <p:toolbar style="margin-top: 20px">
        <p:toolbarGroup>
            <p:commandButton value="Pesquisar" action="#{pesquisaUsuarioBean.pesquisar}" update="@form" />
        </p:toolbarGroup>
        <p:toolbarGroup align ="right">
            <p:button value="Novo" outcome="/usuarios/CadastroUsuario"/>
        </p:toolbarGroup>
    </p:toolbar>

    <p:panelGrid columns="2" id="painel" style="width: 100%; margin-top: 20px" columnClasses="rotulo, campo">
        <p:outputLabel value="Nome" for="nome"/>
        <p:inputText id="nome" size="60" maxlength="80"
        value="#{pesquisaUsuarioBean.filtro.nome}"/>
    </p:panelGrid>

    <p:dataTable id="usuariosTable"
            value="#{pesquisaUsuarioBean.usuariosFiltrados}" var="usuario"
            style="margin-top: 20px" emptyMessage="Nenhum usuario encontrado."
            rows="20" paginator="true" paginatorAlwaysVisible="false"
            paginatorPosition="bottom">

    <p:column headerText="Id" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.id}" />
    </p:column>

    <p:column headerText="Nome" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.nome}" />
    </p:column>

    <p:column headerText="RG" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.rg}" />
    </p:column>

    <p:column headerText="CPF" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.cpf}" />
    </p:column>

    <p:column headerText="Email" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.email}" />
    </p:column>

    <p:column headerText="Telefone" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.telefone}" />
    </p:column>

    <p:column headerText="Endereço" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.endereco}" />
    </p:column>

    <p:column headerText="Estado" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.estado}" />
    </p:column>

    <p:column headerText="CEP" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.cep}" />
    </p:column>

    <p:column headerText="Status" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.status}" />
    </p:column>

    <p:column headerText="Operações" style="width: 100px; text-align: center">
                <p:button outcome = "/usuarios/CadastroUsuario" icon="ui-icon-pencil" title="Editar">
                    <f:param name="usuario" value="#{usuario.id}" />
                </p:button>
            <p:commandButton icon="ui-icon-bloquear" title="Alterar status do cadastro" oncomplete="PF('confirmacaoExclusao').show()" process="@this" update="frmPesquisa:confirmacaoExclusaoDialog">
                <f:setPropertyActionListener value="#{usuario}" target="#{pesquisaUsuarioBean.usuarioSelecionado}"/>    
            </p:commandButton>
    </p:column>


    </p:dataTable>

        <p:confirmDialog header="Alterar status do cadastro"
            message="Tem certeza que deseja alterar o status do cadastro do usuário #{pesquisaUsuarioBean.usuarioSelecionado.nome}?"
            widgetVar="confirmacaoExclusao" id="confirmacaoExclusaoDialog">
            <p:button value="Não"
                onclick="PF('confirmacaoExclusao').hide(); return false;" />
            <p:commandButton value="Sim"
                oncomplete="PF('confirmacaoExclusao').hide();" action="#{pesquisaUsuarioBean.excluir}" process="@this" update="frmPesquisa:usuariosTable"/>
        </p:confirmDialog>
</h:form>
</ui:define>

Search user.java.

@Named@ViewScopedpublic class PesquisaUsuarioBean implements Serializable{

private static final long serialVersionUID = 1L;

@Inject
private UsuariosRep usuarios;

private UsuarioFilter filtro;

private List<Usuario> usuariosFiltrados;

private Usuario usuarioSelecionado;

@Inject
private CadastroUsuarioService cadastroUsuarioService;

public PesquisaUsuarioBean() {
    filtro = new UsuarioFilter();
}

public boolean isInativo() {
    boolean inativo = false;
    for (int x = 0;x < this.usuariosFiltrados.size(); x++)
    {
        String ContasInativas = this.usuariosFiltrados.get(x).getStatus();
        if ( ContasInativas.equals("Inativo"))
        {
            inativo = true;
        }
    }
    return inativo;
}

public void excluir() {
    FacesContext context = FacesContext.getCurrentInstance();
    if (this.usuarioSelecionado.getStatus().equals("Ativo"))
    {
        this.usuarioSelecionado.setStatus("Inativo");
    }
    else
    {
        this.usuarioSelecionado.setStatus("Ativo");
    }
    try {
        this.cadastroUsuarioService.salvar(this.usuarioSelecionado);
        context.addMessage(null, new FacesMessage("O status do cadastro do usuário " + usuarioSelecionado.getNome() + " com o CPF : " + usuarioSelecionado.getCpf() + " foi alterado com sucesso."));
    } catch (NegocioException e) {
        FacesMessage mensagem = new FacesMessage(e.getMessage());
        mensagem.setSeverity(FacesMessage.SEVERITY_ERROR);
        context.addMessage(null, mensagem);
    }
}

public void pesquisar() {
    usuariosFiltrados = usuarios.filtrados(filtro);
}

public List<Usuario> getUsuariosFiltrados() {
    return usuariosFiltrados;
}

public UsuariosRep getUsuarios() {
    return usuarios;
}

public UsuarioFilter getFiltro() {
    return filtro;
}

public Usuario getUsuarioSelecionado() {
    return usuarioSelecionado;
}

public void setUsuarioSelecionado(Usuario usuarioSelecionado) {
    this.usuarioSelecionado = usuarioSelecionado;
}
}

Usuariosrep.java

public class UsuariosRep implements Serializable {

private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;

public Usuario guardar(Usuario usuario) {
    EntityTransaction trx = manager.getTransaction();

    trx.begin();

    usuario = manager.merge(usuario);

    trx.commit();

    return usuario;
}

public Usuario porNome(String nome) 
{
    return manager.find(Usuario.class, nome);
}

public Usuario porId(Long id)
{
    return manager.find(Usuario.class, id);
}

public List<Usuario> listaDeUsu() 
{
    return manager.createQuery("from Usuario", Usuario.class).getResultList();
}

public List<Usuario> raizes()
{
    return  manager.createQuery("from Usuario",Usuario.class).getResultList(); 
}

@SuppressWarnings("unchecked")
public List<Usuario> filtrados(UsuarioFilter filtro) {

    Session session = manager.unwrap(Session.class);

    Criteria criteria = session.createCriteria(Usuario.class);

    if (filtro.getNome() != null) {
        criteria.add(Restrictions.eq("nome", filtro.getNome()));
    }

    // orderBy do SQL
    return criteria.addOrder(Order.asc("id")).list();
}

public void remover(Usuario usuario) {
    this.manager.remove(usuario);
    EntityTransaction trx = manager.getTransaction();
    trx.begin();
    manager.flush();
    trx.commit();
}
   }

Usuariofilter.java

public class UsuarioFilter implements Serializable {
private static final long serialVersionUID = 1L;

private String nome;

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

}

To shorten the code, I deleted some initial lines that deal with import, package and others.

Thanks in advance for any opinion or suggestion.

1 answer

0

Put in your Search View

...

<p:selectOneRadio id="id" value="#{pesquisaUsuarioBean.filtro.status}" >
    <f:selectItem itemLabel="Todos" itemValue="null" />
    <f:selectItem itemLabel="Ativo" itemValue="ativo" />
    <f:selectItem itemLabel="Inativo" itemValue="inativo" />
</p:selectOneRadio>

....

And in the Filter

...
private String status;

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}
...

In the criteria

....
if (filtro.getStatus() != null) {
    criteria.add(Restrictions.eq("status", filtro.getStatus()));
}
....
  • Right. Thank you very much, Jose. But when I mark the "all" option in Selectoneradio, how could I treat it? In this case the search will simply ignore the status field and search by name only.

  • Do So: <f:selectItem itemLabel="TODOS" itemValue="null" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.