Auto-populate a list from a table

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 = Joomla\CMS\Factory::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>
Note: You need to keep the //<code> and //</code> tags in order for the script to trigger!

92 persons found this article helpful.


Was this article helpful?

Yes No
Sorry about that