Showing posts with label select tag. Show all posts
Showing posts with label select tag. Show all posts

Monday, September 6, 2010

Joomla 1.5 Additional select tag values

This continues on my blog post on how to add a select tag through the Joomla! framework. The code that follows will show you how to add to the ObjectList for a Select tag. This is especially useful where you have to use a select tag in a search form.

I normally use a value of 0 to indicate a search of "All Values".

The first thing you do is create a class at the top of your page as follows:

<?php
class MySelectObject{
var $id;
var $name;
}
?>



Then to use it do the following:

<?php
$db = &JFactory::getDBO();
$query = "SELECT `id`,`name` FROM
#__town";

$db->setQuery($query);
$townlist = $db->loadObjectList();

/*Create an instance of MySelectObject*/
$mso = new MySelectObject();

/*Set values*/
$mso->id = 0;
$mso->name = 'Any Town';

/*Create an array for insertion*/
$tmpArr = array(0 => $mso);

/*Merge with array result from query. Add to the front of list*/
$selectList =
array_merge($tmpArr,$townlist);

/*Make MySelectObject the default selected*/
echo
JHTML::_('Select.genericlist',$selectList,'town',"","id","name",0);


?>

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.
<?php
$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:

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