1
votes

I am creating my own plugin in Joomla and I want to add a multiple select list in the article . I also want some options in it to be selected by default. Following is my code.

public function onContentPrepareForm($form, $data)
    {
        if (!($form instanceof JForm))
        {
            $this->_subject->setError('JERROR_NOT_A_FORM');
            return false;
        }
        $id = $data->id;
        $catid = $data->catid;
        $db = JFactory::getDBO();
        $query = "SELECT ID, title FROM #__content WHERE catid = '" . SUBTOPIC_CATEGORY_ID . "'";
        $db->setQuery($query);
        $resultArray = $db->loadAssocList();
        $optionsString = '';
        foreach($resultArray as $result)
        {
            $optionsString .= '<option value="' . $result['ID'] . '"> ' . $result['title'] . '</option>';
        }
        if(isset($id) && isset($catid) && $catid == TOPIC_CATEGORY_ID)
        {
            $query = "SELECT subtopic FROM #__empd_topic WHERE ID = '$id'";
            $db->setQuery($query);
            $subtopicArray = $db->loadRow();
        }
        $xmlText = '<?xml version="1.0" encoding="utf-8"?>
<form>
    <fields name="subtopic" label="subtopic">
        <fieldset name="subtopic" label="subtopic">
            <field
                name="subtopic"
                type="list"
                id="subtopic"
                multiple ="true"
                label = "subtopic"
                message = "Message"
            >' . $optionsString . '</field>
        </fieldset>
    </fields>
</form>';
        $xmlObj = new SimpleXMLElement($xmlText);
        $form->setField($xmlObj);
        return true;
    }

Now there is a default property for the <field> node in xml but it can have only one value and i also tried selected="selected" within <option> node in xml but it doesn't work. You can get a reference on xml list here.

2

2 Answers

0
votes

Try adding default values in a string like this:

default="[\"3\",\"5\",\"7\"]"

The reason I think this is the answer is because that is JSON and I know the data is saved in JSON. And you have to escape the " characters

0
votes
$selected = array("2","3","4");  //selected by default

foreach($resultArray as $result)
        {
            if(in_array($result['ID'],$selected)) {
               $select = "selected=\"selected\"";
            } else {
               $select = "";
             }

            $optionsString .= '<option value="' . $result['ID'] . '" '.$select.' > ' . $result['title'] . '</option>';
        }

xml

<field
 name="subtopic"
 type="list"
 id="subtopic"
 multiple ="true"
 label = "subtopic"
 message = "Message"
 size="5" //add this 
 >