Print

In this article we will describe how to auto-populate a list with items from a MySQL database table of your choice. In order to achieve this you will have to create a new "Dropdown" field, let's say "test".                  When editing the field, in the "Items" area paste the following code:

//<code>
// Prepare the empty array
$items = array();
// Prepare the database connection
$db = JFactory::getDbo();
// Keep this if you'd like a "Please select" option, otherwise comment or remove it
$items[] = "|Please Select[c]";

// Run the SQL query and store it in $results
$db->setQuery("SELECT your_value, your_label FROM #__your_table");
$results = $db->loadObjectList();

// Now, we need to convert the results into a readable RSForm! Pro format.
// The Items field will accept values in this format:
// value-to-be-stored|value-to-be-shown
// Eg. m|M-sized T-shirt
foreach ($results as $result) {
$value = $result->your_value;
$label = $result->your_label;
$items[] = $value.'|'.$label;
}

// Multiple values are separated by new lines, so we need to do this now
$items = implode("\n", $items);

// Now we need to return the value to the field
return $items;
//</code>

===========================================================

This will autopopulate a dropdown list with the names as values and usernames as labels of all the users in the #__users table.

//<code>
$items = "|Please Select[c]\n";
$db =& JFactory::getDBO();
$db->setQuery("SELECT name, username FROM #__users");
$result = $db->loadObjectList();

foreach ($result as $r)
$items .= $r->username . '|' . $r->name . "\n";

//                   return $items;                 //  This will leave a blank line after the last dropdown element
return trim($items);        //  This will NOT leave a blank line after the last dropdown element
// </code>

=====================================

//    try this.....
$db = JFactory::getDBO();
$db->setQuery("SELECT `name`, `email` FROM #__users");
$rez = $db->loadObjectList();
$items = "|Select...\n";
foreach($rez as $r){
$items .= $r->email."|".$r->name."\n";
}
return trim($items);
//

===========================

User Groups IDs are found in the #__usergroups database table. Knowing the Group's exact ID, you can try a similar as the following snippet (usually the Registered user group has ID 2):

//
$userGroupId = 2;
$db = JFactory::getDBO();
$db->setQuery("SELECT u.`name`, u.`email` FROM #__users AS u LEFT JOIN #__user_usergroup_map AS um ON u.`id` = um.`user_id` WHERE um.`group_id`='".$userGroupId."'");
$rez = $db->loadObjectList();
$items = "|Select...\n";
foreach($rez as $r){
$items .= $r->email."|".$r->name."\n";
}
return trim($items);
//
    

So if you want user | email   it would be

//
$db = JFactory::getDBO();
$db->setQuery("SELECT `name`, `email` FROM #__users");
$rez = $db->loadObjectList();
$items = "|Select...\n";
foreach($rez as $r){
$items .= $r->email."|".$r->name." | ".$r->email."\n";
}
return trim($items);
//