通过索引将输入组件的值绑定到列表项

通过索引将输入组件的值绑定到列表项

本文介绍了通过索引将输入组件的值绑定到列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例:

 <h:outputLabel for="category1" value="Cateogry"/>
 <h:selectOneMenu id ="category1" value="#{articleManageBean.categoryId1}"
   converter="categoryConverter">

     <f:selectItems value="#{articleManageBean.categories}" var="category"
         itemValue="#{category.id}" itemLabel="#{category.name}" />

 </h:selectOneMenu>

这是我拥有的托管bean

and here is the managed bean that I have

@ManagedBean
@SessionScoped
public class ArticleManageBean {

   private Long categoryId1;
   private List<Category> categories;

   //...
}

从db中填充类别列表,并使用转换器使用selectOneMenu填充该列表.

The categories list gets populated from db, and selectOneMenu gets populated with this list using a converter.

我的第一个问题:如果要在jsf页面中创建另一个selectOneMenu,则必须复制粘贴整个内容,然后将selectOneMenu的值更改为categoryId2,从而在托管bean中放置另一个名为categoryId2的属性.那是不切实际的.我想将selectMenu的这些值映射到列表项,例如映射到属性

My First question:If I want to create another selectOneMenu in my jsf page I would have to copy paste the entire thing and just change the value of selectOneMenu to say categoryId2 thus putting another attribute to managed bean called categoryId2. That is not practical. I want to map these values of selectMenu to list items, for instance to an attribute

 List<Long> categoryIds;

如果我使用

 <h:selectOneMenu id ="category1" value="#{articleManageBean.categoryIds.[0]}"  >

我得到一个错误

 javax.el.PropertyNotFoundException: /createArticle.xhtml @47,68 value="#{articleManageBean.categoriesId[0]}": Target Unreachable, 'null' returned null

如果我取消了Araylist,则会遇到此异常

If I nitialize the Araylist then I get this exception

 javax.el.PropertyNotFoundException: /createArticle.xhtml @47,68 value="#{articleManageBean.categoriesId[0]}": null

我的第二个问题:有没有一种方法可以动态地编写selectOneMenu标签,也就是说,我的意思是不复制粘贴整个标签,而是以某种方式创建一个使用categoryId参数并自动写入标签的函数(可能是某种自定义标签?)

My second question:Is there a way to dinamicly write selectOneMenu tags, by that I mean not to copy paste the entire tag, just somehow create a function that take the categoryId parameter and writes automaticaly the tag (somekind of custom tag maybe ?)

希望您能理解我的问题

提前感谢

推荐答案

使用大括号表示法来指定索引.

Use the brace notation instead to specify the index.

<h:selectOneMenu id="category1" value="#{articleManageBean.categoryIds[0]}">

您只需要确保已经准备好#{articleManageBean.categoryIds}后面的值. JSF不会为您这样做.例如

You only need to make sure that you have already prepared the values behind #{articleManageBean.categoryIds}. JSF won't do that for you. E.g.

private List<Long> categoryIds = new ArrayList<Long>();

public ArticleManageBean() {
    categoryIds.add(null);
    categoryIds.add(null);
    categoryIds.add(null);
    // So, now there are 3 items preserved.
}

一种替代方法是使用Long[],这不需要预先填充.

an alternative is to use Long[] instead, this doesn't need to be prefilled.

private Long[] categoryIds = new Long[3]; // So, now there are 3 items preserved.

这篇关于通过索引将输入组件的值绑定到列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:05