1

I need to conditionally add an option to an existing form field in my custom component. The form is defined in models/forms/myview.xml like:

<form>
    <fieldset>
        ...
        <field name="myfield"
            type="list"
            ...
        >
            <option value="none">JNONE</option>
            <option value="one">one</option>
            <option value="two">two</option>
        </field>
        ...

How can I add an additional option "something-else" to myfield in views/myview/view.html.php?

I suppose I need to use $this->form->setFieldAttribute(...), but I cannot get it to work.


Update: (almost there) looks like I can add options with $this->form->getField('myfield')->addOption("foo"), but I cannot set a key-value pair here.

API: https://api.joomla.org/cms-3/classes/JFormFieldList.html#method_addOption

0

1 Answer 1

3

You're already aware of Joomla\CMS\Form\Field\ListField::addOption() method. value is an attribute in the XML so it needs to be passed along with other attributes in the second argument:

$this->form->getField('myfield')->addOption('foo', ['value' => 'bar']);

Word of advice, you should not be modifying the form in the view. This should really be done in the model so the changes are reflected when submitting and validating the form.

2
  • Ah! Thank you very much. Didn't guess that the attributes key needs to be "value"... Works!
    – Marcel
    Commented May 18, 2022 at 15:05
  • and yes, you are right about better not modifying the form in the view also.
    – Marcel
    Commented May 18, 2022 at 15:08

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.