PrimeFaces <f:attribute not working correctly with p:galleria attribute - primefaces

I have issue when trying to make command link from inside p:galleria component
The problem is despite the fact at run time the link value value="Show present #{present.name} #{present.presentId}" contains the correct value of the id as example value="Show present Foo 1" , when pressing the command link it sends the wrong id of the second object every time
<h:form>
<p:galleria value="#{presentBean.allPresentList}" var="present" panelWidth="500" panelHeight="313" showCaption="true">
<f:facet name="content">
<h:commandLink value="Show present #{present.name} #{present.presentId}" action="pretty:present" actionListener="#{presentBean.setPresentObj}">
<f:attribute name="present" value="#{present.presentId}"/>
</h:commandLink>
</f:facet>
</p:galleria>
</h:form>
#ManagedBean(name="presentBean")
#SessionScoped
public class PresentBean implements Serializable{
ArrayList<Present> allUserPresentList = new ArrayList<Present>();
#PostConstruct
private void usersPresent(){
PresentDao presentDao = new PresentDaoImpl();
allPresentList = (ArrayList<Present>) presentDao.findAllPresents();
}
public ArrayList<Present> getAllUserPresentList() {
return allUserPresentList;
}
public void setAllUserPresentList(ArrayList<Present> allUserPresentList) {
this.allUserPresentList = allUserPresentList;
}
private String presentId ;
public String getPresentId() {
return presentId;
}
public void setPresentId(String presentId) {
this.presentId = presentId;
}
public void setPresentObj(ActionEvent ev){
Object presentOb = ev.getComponent().getAttributes().get("present");
if(presentOb != null){
this.presentId = (String) presentOb;
}else{
presentId = null ;
}
}
}

You need to use a setPropertyActionListener instead of <f:attribute name="present" value="#{present.presentId}"/> as the f:attribute tag is only evaluated when the component is created (only once) not when the component generates html based on the iterated rows.
So you'll need to instead use:
<f:setPropertyActionListener target="#{presentBean.presentId}" value="#{present.presentId}" />
That will set the value of the presentId in your managed bean, so in your action method you can just access the presentId itself already without having to work it out.
Alternatively if you're using a later version of JSF (using Servlet 3.0 or above), then you could create a method in the managed bean which takes the presentId or even the present object as a parameter
e.g. in your managed bean:
public void myAction(Present p){
//do whatever you want with the Present object
}
and in your .xhtml:
<h:commandLink value="Show present #{present.name} #{present.presentId}" actionListener="#{presentBean.myAction(present)}">
</h:commandLink>

Related

p:datascroller only lazyload one time

We have implement the datascroller from primefaces and extend it with lazy=true this works fine for the first lazy loading. But when I scroll down no event is fired from Frontend. The Backend works as expected.
I test it with changing the chunk size and get a better understanding what is happen in the backend code. We override the load function what primefaces is calling when you reach the end of page. I changed the code to not lazyloading by scrolling, therefor i implement a button to load the next chunk when you click the button. But Button disappear after clicking it once.
Xhtml:
<p:dataScroller value="#{stakeholderOverviewController.model}" var="stakeholder" chunkSize="50" lazy="true" rowIndexVar="test">
<f:facet name="header">
Scroll Down to Load More Cars
</f:facet>
<f:facet name="loader">
<p:commandButton type="button" value="More" icon="pi pi-chevron-circle-down"/>
</f:facet>
<h:panelGrid columns="2" style="width:100%" columnClasses="logo,detail">
<p:outputPanel>
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="Id:" />
<h:outputText value="#{stakeholder.lastname}" style="font-weight: bold"/>
<h:outputText value="Year:" />
<h:outputText value="#{stakeholder.firstname}" style="font-weight: bold"/>
</h:panelGrid>
</p:outputPanel>
</h:panelGrid>
<ui:include rendered="#{empty stakeholder}" src="/WEB-INF/compositions/stakeholderEmptyModel.xhtml" />
</p:dataScroller>
there is the backend code for Controller:
public StakeholderOverviewController() {
model = new LazyDataModel<StakeholderSearchWrapper>() {
#Override
public List<StakeholderSearchWrapper> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map filters) {
List<StakeholderSearchWrapper> execQuery = execQuery(first, pageSize);
return execQuery;
}
};
model.setRowCount(0);
}
....
protected synchronized List<StakeholderSearchWrapper> execQuery(int first, int pageSize) {
if (tmpfirst != first || tmppageSize != pageSize || reExecQuery) {
reExecQuery = false;
tmpfirst = first;
tmppageSize = pageSize;
tmpModel = new LinkedList<>();
// Query for stakeholder
queryresponse = stakeholderService.findByLastnameOrFirstmanOwnerOrShare(getSearchText(), getClientId(),
first, pageSize, selectedFacets, nameSort[getSort()]);
setFacets(queryresponse.getFacetFields());
Set<String> stakeholderIds = new HashSet<String>();
// convert for view
for (SolrDocument details : queryresponse.getResults()) {
StakeholderSearchWrapper stakeholderSearchWrapper = new StakeholderSearchWrapper(details);
tmpModel.add(stakeholderSearchWrapper);
stakeholderIds.add(stakeholderSearchWrapper.getId());
}
historyCount = stakeholderService.countHistoryEntryByStakeholders(stakeholderIds);
notesCount = stakeholderService.countNoteEntriesByStakeholders(stakeholderIds);
assignedProjects = projectService.findByStakeholderIds(stakeholderIds);
for(StakeholderSearchWrapper dao : tmpModel) {
dao.setHistoryCount(getHistoryCount(dao.getId()));
dao.setNoteCount(getNoteEntriesCount(dao.getId()));
dao.setProjects(getAssignedProjects(dao.getId()));
}
SolrDocumentList result = queryresponse.getResults();
int numFound = (int) result.getNumFound();
return tmpModel;
} else {
return tmpModel;
}
}
What i want is that the lazy loading dont fire only once. It should fire as often as needed. I dont know where i have to set some variable to do this. When im debuging the current code the load function is only requested at the first run of the page refresh and than one lazy loading is called but then nothing happens.
I think I realized the trick. Check the line:
model.setRowCount(0);
Instead, set the model row count properly using the max amount of data you want to display:
int totalNumberOfRegisters = this.count(/* relevant paramenters*/);
model.setRowCount(totalNumberOfRegisters);

How to set a converter dynamically for a PrimeFaces component?

I am using p:autoComplete inside column of a data table. And I am setting
converter by using variable assigned to the data table converter="#{fieldVar.possibleValues}"
but, it throws :
converter="#{fieldVar.possibleValues}": java.lang.IllegalArgumentException: Cannot convert userConverter of type class java.lang.String to interface javax.faces.convert.Converter
possibleValues is a string
If this is not possible then how we can change the converter dynamically.
<p:dataTable var="fieldVar" value="#{dynamicReportBean.screenMetadataDTOs}" id="edit_meta_data_datatable">
<p:column headerText="Filter Names">
<h:outputText value="#{fieldVar.filedName}"/>
</p:column>
<p:column headerText="Filter Values">
<p:inputText value ="#{fieldVar.filedValue}"
placeholder="#{fieldVar.filedName}"
rendered="#{dynamicReportBean.canRenderFieldType(fieldVar.fieldId, 'TEXTFIELD')}" style="width: 220px">
</p:inputText>
<p:selectOneMenu value="#{fieldVar.filedValue}"
rendered="#{dynamicReportBean.canRenderFieldType(fieldVar.fieldId, 'DROPDOWN')}" style="width: 220px">
<f:selectItems value="#{dynamicReportBean.retrievePossibleDropDownValues(fieldVar.fieldId, fieldVar.fieldType, fieldVar.possibleValues)}"/>
</p:selectOneMenu>
<p:selectManyMenu value="#{fieldVar.filedValue}"
style="width: 220px"
showCheckbox="true"
rendered="#{dynamicReportBean.canRenderFieldType(fieldVar.fieldId, 'SELECT_MANY_CHECKBOX')}">
<f:selectItems value="#{dynamicReportBean.retrievePossibleDropDownValues(fieldVar.fieldId, fieldVar.fieldType, fieldVar.possibleValues)}"/>
</p:selectManyMenu>
<p:autoComplete value="#{fieldVar.filedValue}"
style="width: 220px"
placeholder="autocomplete"
completeMethod="#{dynamicReportBean.getAutoCompleteMethod}"
rendered="#{dynamicReportBean.canRenderFieldType(fieldVar.fieldId, 'AUTOCOMPLETE')}"
scrollHeight="300"
converter="#{fieldVar.possibleValues}"
size="25">
<f:attribute name="converterName" value="#{fieldVar.possibleValues}" />
<p:ajax event="itemSelect" listener="#{dynamicReportBean.onHandleSelect}"/>
</p:autoComplete>
</p:column>
</p:dataTable>
if I pass converter = "userConverter" It works fine but instead of that I want converter values come dynamically
public class UserConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
UserLOVBean lOVBean = null;
try {
UserService service = new UserServiceImpl();
UserFilterDTO filterDTO = new UserFilterDTO();
UserContext userContext
= (UserContext) context.getExternalContext().getSessionMap().
get("USER_CONTEXT");
filterDTO.setCmpCode(userContext.getCmpCode());
filterDTO.setOrgCode(userContext.getOrgCode());
if (value != null) {
filterDTO.setUserId(value);
}
for (UserLOVDTO lOVDTO : service.retrieveUserForAutoComplete(
filterDTO)) {
if (value.equals(lOVDTO.getUserId())) {
lOVBean = new UserLOVBean();
CopyUtil.copyValues(lOVDTO, lOVBean);
}
}
} catch (Exception ex) {
ex.printStackTrace();
Logger.getLogger(UserConverter.class.getName()).log(Level.SEVERE,
null, ex);
}
return lOVBean;
}
#Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
return String.valueOf(((UserLOVBean) value).getUserId());
}
}
Setting a converter for p:autoComplete (and any other PrimeFaces component) using the converter attribute is documented as:
An EL expression or a literal text that defines a converter for the component. When it's an EL expression, it's resolved to a converter instance. In case it's a static text, it must refer to a converter id.
So, if you want to use an EL expression, it must point to an instance of a converter. In your bean you could simply add:
public UserConverter getUserConverter() {
return new UserConverter();
}
And then, in your XHTML, use:
<p:anyComponent converter="#{myBean.userConverter}"/>

Dynamic images with StreamedContent

I have implemented two StreamedContent beans to dynamic load a graphic image, following the solution found
here
1) With the first one I display images in a contentFlow (EVERYTHING OK)
<p:contentFlow value="#{imageBean.images}" var="image">
<p:graphicImage value="#{imageStreamer.fileContent}" styleClass="content" cache="false">
<f:param name="index" value="#{image.index}"/>
</p:graphicImage>
</p:contentFlow>
2) With the second one I try to display images using a foreach (or repeat):
<c:forEach items="#{imageBean.images}" var="item" varStatus="varStatus">
<p:graphicImage value="#{imageStreamer.fileContent}" cache="false">
<f:param name="index" value="#{varStatus.index}" />
</p:graphicImage>
</c:forEach>
This doesn't work. The check (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) is always true.
If I change the scope of the Bean to RequestScoped than it works! I'm confused... can someone help me?
Managed bean:
#ManagedBean
#ApplicationScoped
public class ImageStreamer{
public ImageStreamer(){}
public StreamedContent getFileContent(){
List<Link> links = this.getLinkItems();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
FacesContext fc = FacesContext.getCurrentInstance();
String linkIndex = externalContext.getRequestParameterMap().get("index");
if(fc.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE){
return new DefaultStreamedContent();
}else{
int parsedIndex = Integer.parseInt(linkIndex);
Link ql = links.get(parsedIndex);
return new DefaultStreamedContent(new ByteArrayInputStream(ql.getBytes()), "image/png");
}
}
}
Since you are using primefaces, try using p:repeat
Repeat is an extension to standard repeat component to provide interoperability between JSF implementations and PrimeFaces components.
https://www.primefaces.org/showcase/ui/data/repeat.xhtml

How to show output text in separate lines

I have two String properties in my managed bean along with corresponding getters and setters.
#ManagedBean
#SessionScoped
public class EditorBean implements Serializable {
private String value="hello how are you";
private String message="hello how are you";
public EditorBean() {
value="hello how are you guys?";
message="dd";
}
// ...
}
I would like to render both strings in separate lines.
<h:outputText value="#{editorBean.message}" />
<h:outputText value="#{editorBean.value}" />
But they are shown in a single line.
ddhello how are you guys?
How is this caused and how can I solve it?
There are no problem with your program i test your program and i get a result like this :
So it show you this because you already change the values in your Constructor :
public EditorBean() {
value="hello how are you guys?";
message="dd";
}
so it should you ddhello how are you guys?
------------------------^-------^
So if you want to show :
private String value="hello how are you";
private String message="hello how are you";
You should not initialize them again in your constructor.
Note
Try this to see what happen exactly :
Message = <h:outputText value="#{editorBean.message}" />
<br/>
Value = <h:outputText value="#{editorBean.value}" />

Why can't I update a p:graphicImage twice after upload a file with p:uploadFile

I have been trying to upload an image with a p:uploadFile and it work fine at first time, but after the first uploaded file it not update the p:graphicImage, but if I reload the page the value of the graphicImage is fine and the image is showed. So, I think that is a problem with the primefaces uploadFile component, but I not sure.
My xhtml is this:
<h:form id="formNuevo" size="150%" enctype="multipart/form-data">
<h:outputLabel value="DiseƱo Neumatico: *" />
<p:fileUpload fileUploadListener="#{serviciosVentanaDiseno.manejarUploadedFile}" mode="advanced" auto="true" sizeLimit="9000000000" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" update="mensajes graficImage"/>
<p:graphicImage id="graficImage" styleClass="disenoNeumatico" value="#{serviciosVentanaDiseno.streamedContentImagen}" ajax="true"/>
</h:form>
and my bean is a #SessionScoped bean, it's here:
public void manejarUploadedFile(FileUploadEvent event) {
UploadedFile uploadedFile = (UploadedFile)event.getFile();
try {
diseno.setImagen(uploadedFile.getContents());
streamedContentImagen = new DefaultStreamedContent(new ByteArrayInputStream(diseno.getImagen()));
} catch (IOException e) {
//log error
}
}
public StreamedContent getStreamedContentImagen() {
return streamedContentImagen;
}
public void setStreamedContentImagen(StreamedContent streamedContentImagen) {
this.streamedContentImagen = streamedContentImagen;
}
Try setting the cache attribute of the graphicImage component to false:
<p:graphicImage cache="false"
change scope #SessionScoped then <p:graphicImage cache="false">