从查询结果在play框架中创建optgroup

时间:2013-07-21 20:16:01

标签: playframework-1.x

例如,如果我从数据库中检索到以下数据:

--------------------------
|  id | name | department|
--------------------------
|  1  | john | HR        |
--------------------------
|  2  | peter| accounting|     
--------------------------
|  3  | adam | secretary |     
--------------------------

如何创建optgroup标记以在optgroup中显示此结果以具有以下内容:

 <select >              
            <optgroup label='HR'>
              <option value='1'>john</option>
            </optgroup>
            <optgroup label='accounting'>
              <option value='2'>peter</option>
            </optgroup>
            <optgroup label='secretary'>
              <option value='3'>adam</option>
            </optgroup>
 </select>

1 个答案:

答案 0 :(得分:1)

这可能不是最佳方式,但您可以将部门视为模型,并以这种方式执行:

用户模型:

public class User extends Model {

    public String name;

    @ManyToOne
    public Department department;


}

部门模型:

public class Department extends Model {

    public String name;

    public List<User> getUsers() {
        List<User> users = new Arraylist<User>();
        if (this.id != null) {
            users = User.find("department.id is ?", this.id).fetch();
        }
        return users;
    }

}

然后在您的视图中,您可以通过这种方式生成选择框列表

<select>
    #{list departments, as : 'department'}
        <optgroup label="${department.name}"">
            #{list department.users, as : 'user'}
                <option value="${user.id}">${user.name}</option>
            #{/list}
        </optgroup>
    #{/list}
</select>

就像我说的,也许有更好的方法,(也许使用原始的SQL查询......)