I'm trying to pre-select several options in a custom form field. I created a new JFormField which extends JFormFieldList and gets its values from my database. This is my current code:

protected function getOptions()
    $app   = JFactory::getApplication();
    $cid   = $app->input->get('cid' , null);
    $db    = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select('cs.id, cs.name');
    $query->from($db->quoteName('#__asdasd', 'cs'));
    $db->setQuery((string) $query);
    $results = $db->loadObjectList();

    $options  = array();
    if ($results)
        foreach ($results as $result)
            $options[] = JHtmlSelect::Option($result->id, $result->name);

    // Merge any additional options in the XML definition.
    $options = array_merge(parent::getOptions(), $options);

    return $options;

This works perfectly, however I can't figure out how to preselect some of the entries. Basically, I just want to add "selected=selected" to some of the options.

Any clue how I can get this to work? I already read the API Documentation, however I find it to be confusing (https://api.joomla.org/cms-3/classes/JHtmlSelect.html#method_option). Is $optKey the Argument I'm looking for? If this is the case, what attributes do I have to pass in order for it to work?

1 Answer 1


I had to do the same thing. I copied the list form field code and changed it accordingly, so I have 2 functions:

  • getInput()
  • getOptions() which you have

In the getInput function, that's what actually creates the list. You'll see a line like the following (the genericlist is also stated in the page you linked to):

$html[] = JHtml::_('select.genericlist', $options, $this->name, trim($attr), 'value', 'text', $selected, $this->id);

The important argument here is $selected. $selected is an array populated from a query I perform finding all the values that are selected depending on the item selected.

So, $selected should be an array you pass to the genericlist generation to tell it which values should be selected.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.