How to change a list of another Managedbean

Asked

Viewed 429 times

2

I have developed a search area on my system where the user can add an item to their list of items. Like a shopping cart.

The search area uses a different Managedbean than the user panel that has a datatable that is loaded in another managedBean.

What I want: I am already persisting the item correctly, however I use the Sessionscoped user panel and wanted the datatable list to update the new item immediately.

The way it is now I have to log on from the user and log on again for the item to load. I cannot change to viewScoped as I have other components (dialog and confirmDialog) on the page that need data in memory.

Bean to Search page with method that registers a new item:

@ManagedBean(name = "api")
@SessionScoped
public class AplicacaoBean implements Serializable{
private static final long serialVersionUID = 1L;

// Pega o usuário logado
@ManagedProperty(value = "#{uBean.usuario}")
private Usuario usuario;

//Outros atributos e métodos

public String acompanharCaso() {
    Patrulheiro patrul = new Patrulheiro();
    if (usuario.getEmailAddress() != null
            && usuario.getEmailAddress() != "") {

        try {
            patrul = (Patrulheiro) buscarPatrulheiroPorEmail();
            assocLocaliza = new PatrulDesapLocaliza();

            assocLocaliza.setDesaparecido(desaparecido);
            assocLocaliza.setPatrulheiro(patrul);
            List<PatrulDesapLocaliza> acompanhamentos = Arrays
                    .asList(assocLocaliza);
            patrul.setPatrulLocalizaDesap(acompanhamentos);

            new PatrulheiroJPA().gravarAtualizar(patrul);
            FacesUtil
                    .addSuccessMessageWithDetail("frmDialogo",
                            "Dados enviados",
                            "Agora você está acompanhando esse caso! Verifique no painel de usuário");
        } catch (Exception e) {
            e.printStackTrace();
            // Não é um Patrulheiro
            FacesUtil.addErrorMessageWithDetail("frmDialogo", "Atenção",
                    "Você deve ser um Patrulheiro para acompanhar o caso!");
        }

    } else {
        // Nao está logado
        FacesUtil.addErrorMessageWithDetail("frmDialogo", "Atenção",
                "Logue-se como Patrulheiro para acompanhar o caso!");
    }
    return null;
}
}

Bean to User page with the list that should receive the new item:

@ManagedBean(name = "patrulBean")
@SessionScoped
public class PatrulheiroBean implements Serializable{
  private static final long serialVersionUID = 1L;
  // Pega o usuário logado
  @ManagedProperty(value = "#{uBean.usuario}")
  private Usuario usuario;

  //Outros métodos e atributos

  @PostConstruct
  public void inicializar() {
      try {
          limpar();
          //lista que deve receber o novo desaparecido adicionado
          listaDesaparecido = new DesaparecidoJPA()
                  .buscarDesaparecidosPorIdPatrulheiro(usuario);

      } catch (Exception e) {
          System.out.println("Não foi possível resgatar os dados da lista de acompanhados");
          e.printStackTrace();
      }
  }

  public void limpar() {
      desaparecido = new Desaparecido();
      descricao = new DescricaoDesaparecido();
      patrulheiro = new Patrulheiro();
      assocLocaliza = new PatrulDesapLocaliza();
  }
}

It would be possible for me to upload and change this user panel list into another bean, or when the user enters your list panel to be updated?

2 answers

1

Include Managedbean as a Property and upgrade its collection.

@ManagedBean(name = "api")
@SessionScoped
public class AplicacaoBean implements Serializable{
private static final long serialVersionUID = 1L;

@ManagedProperty(value = "#{uBean.usuario}")
private Usuario usuario;

@ManagedProperty(value = "#{patrulBean}")
private PatrulheiroBean patrulheiroBean;

public String acompanharCaso() {
    //...
    patrulheiroBean.atualizaColecao();
}
  • Cool, that works, but another error came up. When I first log in with Ranger Nullpointer occurs: FATAL: JSF1073: java.lang.NullPointerException obtido durante o processamento de RENDER_RESPONSE 6: UIComponent-ClientId=, Message=null&#xA;nov 25, 2015 12:00:01 AM com.sun.faces.context.ExceptionHandlerImpl log&#xA;FATAL: No associated message&#xA;java.lang.NullPointerException&#xA; at br.com.aenc.entity.Usuario.hashCode(Usuario.java:126). But if I log in again there is no error.

  • In the line of this class User is like this: @Override&#xA; public int hashCode() {&#xA; final int prime = 31;&#xA; int result = 1;&#xA; result = prime * result + id; //Linha com erro&#xA; return result;&#xA; }

  • This error is related to Property @ManagedProperty(value = "#{uBean.usuario}") private Usuario usuario; that already existed in your code before I proposed the change. In that case you will have to see in your logic what is occurring.

  • Yes, it seems that if I use two managerProperties this error occurs in a Bean, because in Patrulheirobean I also load the same property "#{uBean.usuario}" to take user data.

  • No, I have Mbs in which I use 4 managedProperties smoothly.

  • I was able to find the cause, but not the solution: That bean api is my index and is referenced first on the run, when I try to log in patrulheiro Nullpointer occurs because its object has already been referenced and was null. If I run the direct login page the error does not occur. I tried erase the property uBean of api and use from the property patrulBean.usuario.nome, but the same error occurs.

Show 1 more comment

0


I managed to solve this problem, after trying to use @ManagedProperty(value = "#{patrulBean}") that caused me the mistakes in the comments.

I used the tag f:event with the guy preRenderView and made the call to the method that loads the list every time the page is called:

<ui:composition template="/WEB-INF/template/Layout.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">

<f:metadata>
    <f:event type="preRenderView" listener="#{patrulBean.iniciarLista}" />
</f:metadata>
...

More: JSF 2 Prerenderviewevent example

Thanks for the help too Nilson

Browser other questions tagged

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