0

I am creating a custom field extending JFormFieldList as below

Form field is defined as below

    <field name="reltype_rev_id" 
           multiple="true"
           type="customfield"
           default="0"
           label="Custom Field"
           />

Options (data) for the field is formed as below

public function getOptions($id='') {
    $options = [(object)['key' => '', 'value' => 'Custom Field']];

    $val_1 = new stdClass();
    $val_1->key='1';
    $val_1->value='One';

    $val_2 = new stdClass();
    $val_2->key='2';
    $val_2->value='Two';

    $key_values = array($val_1, $val_2);

    $options = array_merge($options, $key_values);

    $default_values = array(1);

    return JHtml::_('select.options', $options, 'key', 'value', $default_values);
}

How can we mark some of the options as selected while forming the field.

The output comes as below

enter image description here

Update:

Optimized the code based on @zollie and the result is the same as shown in the above screenshot

    $data = array('1' => 'One', '2' => 'Two');
    return JHtmlSelect::options($data, 'value' , 'text', array('1'), false);
0

1 Answer 1

2

If you're extending JFormFieldList then you don't need to use JHtml::_('select...) as well. Instead you just return an array of text/value combinations for the options of the HTML select. You can specify the default values by setting the protected variable $value.

class JFormFieldCustomfield extends JFormFieldList

protected $type = 'Customfield';

public function getOptions() {

    $key_values = array(
        array('value' => 1, 'text' => 'One'),
        array('value' => 2, 'text' => 'Two'),
        array('value' => 3, 'text' => 'Three'),
    );

    // merge with any options from the XML file
    $options = array_merge(parent::getOptions(), $key_values);

    // pre-select values 2 and 3
    $this->value = array(2, 3);

    return $options; 
}

(To allow you to select multiple values, you have to have multiple="true" in the XML file, as you already have). See https://docs.joomla.org/Creating_a_custom_form_field_type

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.