Вам, вероятно, тоже не нужно зацикливаться. Вот простой способ переключения:
function toggleDiv(divId) {
const div = document.getElementById(divId);
const visible = div.style.display === "block";
div.style.display = visible ? "none" : "block";
}
<table style="margin-left: auto; margin-right: auto;" border="0" cellpadding="10">
<tbody>
<tr>
<td><button onclick="toggleDiv('Div1');">Div1</button></td>
<td><button onclick="toggleDiv('Div2');">Div2</button></td>
<td><button onclick="toggleDiv('Div3');">Div3</button></td>
</tr>
</tbody>
</table>
<table>
<div id="Div1">
Div1 Content
</div>
<div id="Div2" style="display: none;">
Div2 Content
</div>
<div id="Div3" style="display: none;">
Div3 Content
</div>
</table>
После исследования о том, как написать собственный конвертер, вот решение.
1. создать класс Java, который реализует javax.faces.convert.Converter;
public class ProjectConverter implements Converter{
@EJB
DocumentSBean sBean;
public ProjectConverter(){
}
public Object getAsObject(FacesContext context, UIComponent component, String value){
return sBean.getProjectById(value);
//If u look below, I convert the object into a unique string, which is its id.
//Therefore, I just need to write a method that query the object back from the
//database if given a id. getProjectById, is a method inside my Session Bean that
//does what I just described
}
public String getAsString(FacesContext context, UIComponent component, Object value)
{
return ((Project) value).getId().toString(); //--> convert to a unique string.
}
}
2. Зарегистрируйте свой конвертер в faces-config.xml
<converter>
<converter-id>projectConverter</converter-id>
<converter-class>org.xdrawing.converter.ProjectConverter</converter-class>
</converter>
3. Так что теперь внутри компонента Primefaces, вы просто делаете converter="projectConverter"
. Обратите внимание, что projectConverter
- это <convert-id>
, который я только что создал. Итак, чтобы решить мою проблему выше, я делаю это:
<p:pickList converter="projectConverter" value="#{bean.projects}" var="project"
itemLabel="#{project.name}" itemValue="#{project}">
Эта проблема не связана с простыми гранями, просто связана с JSF.
Зачем вам снова попадать в базу данных? Ваш bean-компонент уже содержит список объектов, которые вы хотите отобразить в компоненте, или он находится в области запроса?
Если вы получаете доступ к окончательному списку через свойство get в вашем бине или вложенное в конвертере, это ваш выбор.
public class SuperPojo
{
protected Integer id;
//constructor & getter
}
public class PojoTest extends SuperPojo
{
private String label = null;
//constructor & getter
}
public class SuperPojoConverter<T extends SuperPojo> implements Converter
{
private Collection<T> superPojos;
public IdEntityConverter(Collection<T> superPojos)
{
this.superPojos = superPojos;
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
//catch exceptions and empty or null value!
final int intValue = Integer.parseInt(value);
for(SuperPojo superPojo : this.superPojos)
if(superPojo.getId().intValue() == intValue)
return superPojo;
return null;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
//catch null and instanceof
return String.valueOf(((SuperPojo)value).getId().intValue());
}
public Collection<T> getSuperPojos()
{
return this.superPojos;
}
}
public class Bean
{
private SuperPojoConverter<PojoTest> pojoTestConverter = null;
public Bean()
{
final List<PojoTest> pojoTests = //get list from hibernate
this.pojoTestConverter = new SuperPojoConverter<PojoTest>(pojoTests);
}
public SuperPojoConverter<PojoTest> getPojoTestConverter()
{
return this.pojoTestConverter;
}
}
<h:selectOneMenu value="#{selPojoTest}" converter="#{bean.getPojoTestConverter}">
<f:selectItems value="#{bean.getPojoTestConverter.getSuperPojos}" var="varPojoTest" itemLabel="#{varPojoTest.label}" itemValue="#{varPojoTest}"/>
</h:selectOneMenu>
Да, это возможно:
public class DocumentSBean sBean implements Serializable{
private List<Document> projects;
// projects methods...
// ...
public Converter getDocumentConverter(){
return docConverter;
}
private Converter docConverter = new Converter() {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
return projects.stream().filter(p -> p.getName().equals(value)).findFirst().orElse(null);
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return (value != null)
? ((Document) value).toString()
: null;
}
};
}
<p:pickList converter="#{sBean.documentConverter}" value="#...