Breaking the mold to see the easy solution

Simple little problem, simple little solution - not really worth a full blog post, but since I think it is a little out-of-the-box for most devs accustomed to using framework libraries to make their forms, it might come in handy. If only one person ever benefits, it was worth putting up.

Today I needed to make a dynamic, database driven dropdown for languages. The one unusual bit was that they wanted the more common languages to appear at the top of the list - and also in the normal order.

Impossible! Preposterous!

Everyone knows to make a dropdown, you get an array from your db result and pop it into your form_dropdown() function which magically renders the dropdown to page for you. You can't have an array with same key repeated in the array, so this request of theirs is a non-starter.


Of course not. The solution is simple - flag the languages in your table that you want at the top, get two result sets, and foreach over each array to build out your list of options (and stick it inside your select element). In other words, do something you may not have done in years - create your own html dropdown function.

(I've copied a CodeIgniter version below, in case it saves someone time)

The real problem here is that sometimes we get so stuck in our way of doing things, we don't remember the basics of what we are really doing. These days it's not unusual for me to use sql, php, a framework library, jquery wrapped in backbone.js, javascript templates , and css - all on a single page! To manage all that mentally, and to get things done in a reasonable amount of time, we need to stick to tried and true patterns.

Just don't let it hamstring you.

Here's the code. It relies on Jamie Rumbelow's MY_Model and you'll notice I do the two arrays a little differently - you'll want the idea, not the code.

Contact me