Chaitanya Kumar Ch
Chaitanya Kumar Ch

Reputation: 309

How to store the data's selected in a selectManyCheckbox into different objects?

In my view I am using StudentModelBean to store the data entered in the form. Consider this part of my form:

<h:selectManyCheckbox value="#{}">
<f:selectItem itemLabel="English" itemValue="English" />
    <f:selectItem itemLabel="Hindi" itemValue="Hindi" />
    <f:selectItem itemLabel="Telugu" itemValue="Telugu" />
</h:selectManyCheckbox>

My requirement is that I need to store each selected item value into the languageName property of each Languages object. At the end I need to get them in the List object. How can I achieve this?

Upvotes: 3

Views: 6398

Answers (1)

BalusC
BalusC

Reputation: 1108632

You'd need to provide the whole Language objects as both the available items and the selected items. You also need to create a Converter which converts between the Language object and String, this is mandatory because HTML output and HTTP request parameters are one and all String.

Assuming that your Language object has two properties code and name and that you've an application scoped bean which look like this:

@ManagedBean
@ApplicationScoped
public class Data {

    private List<Language> languages;

    @PostConstruct
    public void init() {
        languages= new ArrayList<Language>();
        languages.add(new Language("en", "English"));
        languages.add(new Language("hi", "Hindi"));
        languages.add(new Language("te", "Telugu"));
        // ...
    }

    public List<Language> getLanguages() {
        return languages;
    }

}

Then you can use it as follows:

<h:selectManyCheckbox value="#{bean.selectedLanguages}" converter="languageConverter">
    <f:selectItems value="#{data.languages}" var="language"
        itemValue="#{language}" itemLabel="#{language.name}" />
</h:selectManyCheckbox>

with this bean

@ManagedBean
@ViewScoped
public class Bean {

    private List<Language> selectedLanguages;

    // ...
}

and this converter

@FacesConverter("languageConverter")
public class LanguageConverter implements Converter {

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object object) {
        return ((Language) object).getCode();
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        List<Language> languages = (List<Language>) context.getApplication().evaluateExpressionGet(context.getELContext(), "#{data.languages}", List.class);

        for (Language language : languages) {
            if (language.getCode().equals(submittedValue)) {
                return language;
            }
        }

        return null;
    }

}

Upvotes: 9

Related Questions