Dynamically add the component in JSF?

好久不见. 提交于 2020-01-30 11:41:04

问题


In my application the component has to change dynamically. I am having a Datatable in that i am having two column, first is a <h:selectoneMenu> in the menu i am having two data(the data are 1 and 2) if 1 is selected then a <h:inputText> should appear and if 2 is selected <h:selectoneMenu> should appear. Need help to do this?

My JSF

   <h:selectOneMenu id="menu" value="#{sample.data}" rendered="true" valueChangeListener="#{sample.change}">
    <f:selectItem itemLabel="Data" itemValue=""/>
    <f:selectItems value="#{sample.list1}"/>
            <a4j:support event="onchange" reRender="text" />
</h:selectOneMenu>
<h:inputText id="text" value="#{sample.input}" rendered="#{sample.status}" />

My Manged Bean Class

public class Sample {
private Boolean status;          //Getter & Setter
private List<SelectItem> list1;  //Setter
private String input;            //Getter & Setter
private String data;             //Getter & Setter

public void change(ValueChangeEvent event){
System.out.println((String)event.getNewValue());
if(((String)event.getNewValue()).equals("value1")){
    status=true;
}
else if(((String)event.getNewValue()).equals("value2")){
    status=false;
}
}
public Boolean getStatus(){
if(status==null){
    status=true;
}
return status;
}
public List<SelectItem> getList1() {
if(list1==null) {
list1 = new ArrayList<SelectItem>();
list1.add(new SelectItem("value1", "label1"));
list1.add(new SelectItem("value2", "label2"));
}
return list1;
}
}

回答1:


My advice would be: do not add/remove component dynamically. Solve your problem another way:

  • Toggle visibility of components
  • Rebind the data belonging to a component

Adding/removing component dynamically is always a source of trouble and chances are that you can do it another way much simpler.

In your case, playing with the visibility using rendered attribute should be enough.




回答2:


Let's say you have something like this

<h:selectoneMenu id="selectOne" rendered="#{myBean.selectOneRendered}">
<h:inputText id="input" rendered="#{!myBean.selectOneRendered}">

You have both the components in your jsp page. Once you reload the jsp the rendered prorpertie will be checked.

in your myBean you must to have something like this

public boolean isSelectOneRendered(){
 boolean rendered;
 //Do something here
 return rendered;
}

if the result is true then the selectOne will be rendered and the input will not and the other way round.



来源:https://stackoverflow.com/questions/2295856/dynamically-add-the-component-in-jsf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!