Multiple select option in list form filed type not

2019-04-17 13:08发布

问题:

I am facing strange problem with Joomla form field I have added a field set type as list and set attribute to multiple="true". Here the code:

<field name="optional"
            type="list"
            label="Optional"
            description="Optional endorsements"
            class="inputbox"
            size="5"
            multiple="true"
         >

         <option value="Water">
                Water</option>
        <option value="Foundation">
            Foundation</option>
</field>

Now when I save the form then only one value get saved when select the multiple values. I don't know what's the problem, if someone have any solution for that please help me.

回答1:

You don't get value, because you're not getting and saving it right. This is what you need to do: In your jTable bind() method you need to add following lines:

if (isset($array['optional']) && is_array($array['optional'])) {
  $registry = new JRegistry;
  $registry->loadArray($array['optional']);
  $array['optional'] = (string) $registry;
}

This will convert your multiple select array into string, which will be saved in database.

And then in your model's method getItem you need to add following lines:

if ($item = parent::getItem($pk)) {
  $registry = new JRegistry;
  $registry->loadString($item->optional);
  $item->optional = $registry->toArray();
}

This will convert databse string back to array and pass it to your jForm.



回答2:

First, @di3sel is totally correct. I am just adding something that could not fit in a comment.

It is also fine if you add the second code to jTable:load method instead of the jModel::getItem. But the code will then change a little. Please note we have to use $this in place of $item in that case.

parent::load($pk);

$registry = new JRegistry;
$registry->loadString($this->optional);
$this->optional = $registry->toArray();

This is also good in the view that only one class-file needs to be modified. Hope this helps at least someone.