Tuesday, December 16, 2008

Joomla! 1.5 How to create a Select tag through the Joomla Framework

Today I needed to display a list of towns from a database table. Nowhere on the Joomla! documentation could I find an example on how to achieve that, so I had to go figure it out once again.

I have a database table that contains all my towns. First I had to create a query to retrieve the towns and put them in an object list.

The code for that follows.
$db =& JFactory::getDBO();

$query = 'SELECT `id`,`name` FROM #__town';
$db->setQuery( $query );
$townlist = $db->loadObjectList();

Ok now that I have a list of towns I simply have to use JHTMLSelect.genericlist() to output the HTML code for my select.

The code to do that follows:

echo JHTML::_('Select.genericlist',$townlist,"town","","id","name",1);

In the code I am simply creating a select from the town list with the options values set as id and the texts set as name (as per the query) . The 1 at the end indicates the selected option. 
If I for example get the selected option from a post/get request, the code will look as follows.

$selectedId = JRequest::getVar( 'id',0);
echo JHTML::_('Select.genericlist',$townlist,"town","","id","name",$selectedId);