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.
The code for that follows.
<?phpOk now that I have a list of towns I simply have to use JHTMLSelect.genericlist() to output the HTML code for my select.
$db =& JFactory::getDBO();
$query = 'SELECT `id`,`name` FROM #__town';
$db->setQuery( $query );
$townlist = $db->loadObjectList();
?>
The code to do that follows:
<?php
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.
<?php
$selectedId = JRequest::getVar( 'id',0);
echo JHTML::_('Select.genericlist',$townlist,"town","","id","name",$selectedId);
?>