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.
<?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:
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);