1

I'm new to JSF, I read the JSF life cycle but couldn't understand how to achieve this?

I've a controller say "Cities" and other controller "Countries". Now I'm going to create a new page, where I will provide search functionality. I showed two dropdowns on that page (One for countries and other for cities), I want the first drop down to be populated on page load. Please tell me which controller to use? Cities/Countries? or create a new one? and How to load data on page load?

Thanks!

wasimbhalli
  • 5,122
  • 8
  • 45
  • 63

4 Answers4

4

Everyone is correct, you need to use <f:selectItems/>

Example:

.Xhtml

<h:selectOneMenu>
    <f:selectItems value="#{myController.listItems}"/>
</h:selectOneMenu>

Bean

public class MyController{
    //The list with the items
    private List<SelectItem> listItems = null;

    public MyController {
        loadCombo();
    }

    (...)

    //Loading the items
    private void loadCombo() {
        listItems = new ArrayList<SelectItem>();

        //You can do with BD data using a for. How to add a new item:
        //listItems.add(new SelectItem("itemValue", "itemLabel"));

        listItems.add(new SelectItem("1", "Item 1"));
        listItems.add(new SelectItem("2", "Item 2"));
        listItems.add(new SelectItem("3", "Item 3"));
        listItems.add(new SelectItem("4", "Item 4"));
    }

    (...)

    //Getters and setters
}

Do not populate the list in a "get" method, because JSF will call it more than once and it will kill your performance.

Renan
  • 741
  • 4
  • 7
2

It is preferable to use one controller for the page which will hold collections of Countries and Cities. To load the countries on page load you should create a method annotated with @Postconstruct. In this method you do your initialization. i.e.

@PostConstruct
public void init(){
     //do your initialization
}
Benchik
  • 2,057
  • 5
  • 26
  • 44
1

Countries is most likely a static collection, so you can just create an application scoped bean with a static Map that holds the countries (key country name, value country code).

Then simply bind your <f:selectItems> in every view that needs a country drop-down to that.

(credits to BalusC btw for this solution ;))

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
0

In your controller you need getter public List<SelectItem> getFirmaTyp() and then in your view you should have something like next.

<h:selectOneMenu value="#{yourController.firma.typ.id}">
   <f:selectItems value="#{yourController.firmaTyp}" />
</h:selectOneMenu>

Getters are called everytime the page is displayed. In my example On postback the id for dropDown is set to entity firm type and id like yourController.firma.typ.id

Eduard
  • 3,176
  • 3
  • 21
  • 31