How to prefill a dropdown using scala template and play framework

♀尐吖头ヾ 提交于 2019-12-05 07:42:01

问题


I am using scala template and Play 2.0 framework for my project. Let's say I have a user form with fields like name (textfield), age (dropdown). While creating the user I filled name as dave and selected age as 25.

Now on my edit screen, I want my values to be prefilled, i know how to do it with textfield (i.e. set value as userForm('name')) but what about the dropdown? how to do it.


回答1:


Thanks Shawn Downs and biesior.

Well, we can use @select scala helper class to show the pre-filled result. like.

 @select(userForm("age"),models.Age.values().toList.map(v => (v.getDisplayName(), v.getDisplayName())),'id->"age")

To show other options I have used an enum of possible values of age.




回答2:


In your model there will be 2 fields

Model code

Class User{
   public String name;
   public int age;
}

Controller code

.
.
.
Form<User> userForm = Form.form(User.class);
User user = new User();
user.name = "Albert";
user.age = 19;

userForm.fill(user);
.
.
.

Util code

package utils;

import java.util.HashMap;
import java.util.LinkedHashMap;

public class DropdownUtils {

    public static HashMap<String, String> getAgeList(int ageLimit){
        LinkedHashMap<String, String> ageList = new LinkedHashMap<>();

        for(Integer i=0; i<=ageLimit; i++){
            ageList.put(i.toString(), i.toString());
        }

        return ageList;
    }
}

View code

.
.
.
<form>
@helper.inputText(userForm("name"))
@helper.select(userForm("age"),
                helper.options(utils.DropdownUtils.getAgeList(25)))
</form>
.
.
.


来源:https://stackoverflow.com/questions/29389201/how-to-prefill-a-dropdown-using-scala-template-and-play-framework

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