<p:autocomplete> multiple
Last updated
Was this helpful?
Last updated
Was this helpful?
cuando utilice autocomplete múltiples debe indicar los metodos
<p:ajax event="itemSelect" listener="#{calendarioSolicitudController.handleSelect}"
update="eventDetails"
/>
<p:ajax event="itemUnselect" listener="#{calendarioSolicitudController.handleSelect}"
update="eventDetails"
/>
Lo usamos para seleccionar varios entitys por ejemplo multiples roles para un usuario.
Tenemos un entity con un List<> @Referenced
Entity Usuario
@Getter
@Setter
public class Usuario {
@Id
private String username;
private String password;
private String nombre;
private String cedula;
private String celular;
private String cargo;
private String email;
@Referenced(documment = "Rol",
field = "idrol", javatype = "String", lazy = false,
repository = "com.avbravo.transporteejb.repository.RolRepository")
private List<Rol> rol;
private String activo;
@Embedded
List<UserInfo> userInfo;
public Usuario() {
}
@Override
public String toString() {
return "Usuario{" + "username=" + username + ", password=" + password + ", nombre=" + nombre + ", celular=" + celular + ", cargo=" + cargo + ", email=" + email + ", rol=" + rol + ", userInfo=" + userInfo + '}';
}
}
Entity Rol
@Getter
@Setter
public class Rol {
@Id
private String idrol;
private String rol;
private String activo;
@Embedded
List<UserInfo> userInfo;
public Rol() {
}
@Override
public String toString() {
return "Rol{" + "idrol=" + idrol + ", rol=" + rol + '}';
}
}
Dibujar el componente <p:autocomplete> en la pagina .xhtml, en el value indicar el rolList que se definió en el controller y el completeMethod al método definido en el controller.
Se debe usar el evento Ajax para que mantenga actualizada la lista.
value="#{usuarioController.rolList}"
completeMethod="#{usuarioController.completeFiltrado}"
<p:autoComplete dropdown="false"
multiple="true"
scrollHeight="250"
size="25"
emptyMessage="#{app['info.nohayregistros']}"
value="#{usuarioController.rolList}"
completeMethod="#{usuarioController.completeFiltrado}"
var="p"
required="true"
itemLabel="#{p.idrol}"
itemValue="#{p}" forceSelection="true">
<f:converter binding="#{rolConverter}"/>
<f:attribute name="field" value="idrol"/>
<f:attribute name="fielddropdown" value="false"/>
<f:attribute name="fieldquerylenth" value="1"/>
<p:ajax event="itemSelect" listener="#{rolController.handleSelect}"
/>
<f:facet name="itemtip">
<h:panelGrid columns="1" cellpadding="5">
<h:outputText value="#{msg['field.idrol']} #{p.idrol}" />
<h:outputText value="#{msg['field.rol']} #{p.rol}" />
</h:panelGrid>
</f:facet>
</p:autoComplete>
Crear el método completeFiltrado(), buscamos por regex en base a los caracteres y nos aseguramos que no se seleccionada previamente.
UsuarioController.java
//Para multiples roles
List<Rol> rolList = new ArrayList();
@Inject
RolRepository rolRepository;
public List<Rol> completeFiltrado(String query) {
List<Rol> suggestions = new ArrayList<>();
List<Rol> temp = new ArrayList<>();
try {
Boolean found = false;
query = query.trim();
if (query.length() < 1) {
return suggestions;
}
String field = (String) UIComponent.getCurrentComponent(FacesContext.getCurrentInstance()).getAttributes().get("field");
temp = rolRepository.findRegex(field, query, true, new Document(field, 1));
if (rolList.isEmpty()) {
if (!temp.isEmpty()) {
suggestions = temp;
}
} else {
if (!temp.isEmpty()) {
for (Rol r : temp) {
found = false;
for(Rol r2:rolList){
if(r.getIdrol().equals(r2.getIdrol())){
found=true;
}
}
if(!found){
suggestions.add(r);
}
}
}
}
} catch (Exception e) {
JsfUtil.errorMessage("complete() " + e.getLocalizedMessage());
}
return suggestions;
}
Cargar el rolList con la lista del entity seleccionado.
rolList = usuario.getRol();
@PostConstruct
public void init() {
try {
String action = loginController.get("usuario");
String id = loginController.get("username");
String pageSession = loginController.get("pageusuario");
//Search
loginController.put("searchusuario", "_init");
writable = false;
usuarioList = new ArrayList<>();
usuarioFiltered = new ArrayList<>();
usuario = new Usuario();
usuarioDataModel = new UsuarioDataModel(usuarioList);
if (id != null) {
Optional<Usuario> optional = usuarioRepository.find("username", id);
if (optional.isPresent()) {
usuario = optional.get();
rolList = usuario.getRol();
usuario.setPassword(JsfUtil.desencriptar(usuario.getPassword()));
usuarioSelected = usuario;
writable = true;
}
}
if (action != null && action.equals("gonew")) {
usuario = new Usuario();
usuarioSelected = usuario;
writable = false;
}
if (pageSession != null) {
page = Integer.parseInt(pageSession);
}
Integer c = usuarioRepository.sizeOfPage(rowPage);
page = page > c ? c : page;
move();
} catch (Exception e) {
JsfUtil.errorMessage("init() " + e.getLocalizedMessage());
}
}
Cargar rolList con los datos del entity seleccionado en la opciòn view
rolList = usuario.getRol();
public String prepare(String action, Object... item) {
String url = "";
try {
loginController.put("pageusuario", page.toString());
loginController.put("usuario", action);
switch (action) {
case "new":
usuario = new Usuario();
usuarioSelected = new Usuario();
writable = false;
break;
case "view":
if (item.length != 0) {
usuarioSelected = (Usuario) item[0];
usuario = usuarioSelected;
rolList = usuario.getRol();
loginController.put("username", usuario.getUsername());
}
url = "/pages/usuario/view.xhtml";
break;
case "golist":
url = "/pages/usuario/list.xhtml";
break;
case "gonew":
url = "/pages/usuario/new.xhtml";
break;
}
} catch (Exception e) {
JsfUtil.errorMessage("prepare() " + e.getLocalizedMessage());
}
return url;
}
Limpiar rolList
rolList = new ArrayList<>();
@Override
public String isNew() {
try {
writable = true;
if (JsfUtil.isVacio(usuario.getUsername())) {
writable = false;
return "";
}
Optional<Usuario> optional = usuarioRepository.findById(usuario);
if (optional.isPresent()) {
writable = false;
JsfUtil.warningMessage(rf.getAppMessage("warning.idexist"));
return "";
} else {
String id = usuario.getUsername();
usuario = new Usuario();
usuario.setUsername(id);
rolList = new ArrayList<>();
usuarioSelected = new Usuario();
}
} catch (Exception e) {
JsfUtil.errorMessage("isNew()" + e.getLocalizedMessage());
}
return "";
}
Asignar rolList al entity a guardar
usuario.setRol(rolList);
public String save() {
try {
Optional<Usuario> optional = usuarioRepository.findById(usuario);
if (optional.isPresent()) {
JsfUtil.warningMessage(rf.getAppMessage("warning.idexist"));
return null;
}
if (!usuario.getPassword().equals(passwordnewrepeat)) {
//password nuevo no coincide
JsfUtil.warningMessage(rf.getMessage("warning.passwordnocoinciden"));
return "";
}
usuario.setRol(rolList);
usuario.setPassword(JsfUtil.encriptar(usuario.getPassword()));
usuario.setUserInfo(userInfoServices.generateListUserinfo(loginController.getUsername(), "create"));
if (usuarioRepository.save(usuario)) {
revisionHistoryTransporteejbRepository.save(revisionHistoryServices.getRevisionHistory(usuario.getUsername(), loginController.getUsername(),
"create", "usuario", usuarioRepository.toDocument(usuario).toString()));
JsfUtil.successMessage(rf.getAppMessage("info.save"));
reset();
} else {
JsfUtil.successMessage("save() " + usuarioRepository.getException().toString());
}
} catch (Exception e) {
JsfUtil.errorMessage("save()" + e.getLocalizedMessage());
}
return "";
}
Asignar el rolList al entity principalusuario.setRol(rolList);
usuario.setRol(rolList);
@Override
public String edit() {
try {
usuario.setRol(rolList);
usuario.setPassword(JsfUtil.encriptar(usuario.getPassword()));
usuario.getUserInfo().add(userInfoServices.generateUserinfo(loginController.getUsername(), "update"));
//guarda el contenido anteriorusuario.setRol(rolList);
//guarda el contenido actualizado
revisionHistoryTransporteejbRepository.save(revisionHistoryServices.getRevisionHistory(usuario.getUsername(), loginController.getUsername(),
"update", "usuario", usuarioRepository.toDocument(usuario).toString()));
usuarioRepository.update(usuario);
JsfUtil.successMessage(rf.getAppMessage("info.update"));
} catch (Exception e) {
JsfUtil.errorMessage("edit()" + e.getLocalizedMessage());
}
return "";
}