Use app controller to keep static list data

In the past I’ve often kept some data such as a list of states or countries in the DB and used that to populate my forms. After some random thinking I’ve found no good reason to utilize the DB for such a thing. This kind of a list is not very long and the number and names of countries and states is not likely to change very often, so I’ve decided to just move it to an array in my app controller.

So, for example, I’ve created a method called getStateList(), which returns an array of all the states (in the USA, that is).

Now if I need to prepare (set) this array for the view variable. I simply do $this->set(‘stateList’, $this->getStateList()); in my controller. Now I have a $stateList variable available in the view.

To build a drop-down box:
$form->select(‘SomeModel.state’, array($stateList), null, null, false);

Nice and clean and no need to be bothered with DB calls.

I would only recommend this approach if you know that your list data isn’t likely to change, not very large (for example I wouldn’t use this for 42,000+ US zip codes) and has to be accessed by multiple form select elements in various views.

Related Posts

%d bloggers like this: