2

I am attempting to populate a select input on my settings page for a plugin I am working on.

_settings.html

forms.selectField({
    'label': "myLabel",
    'instructions': "My Instructions"|t,
    'required': true,
    'id': 'myInput',
    'name': 'myInput',
    'options': craft.myPlugin.settings.getOptions
})

I am getting the select to render, but it's just not getting any values.

craft.myPlugin.settings.getOptions links to my variable file for my plugin.

MyPluginVariable.php

public function getOptions()
{
    error_log(__FUNCTION__);  // Never gets executed
}

I thought maybe I could just return a name|value array in my getOptions method.

return array('one'=>'one', 'two' =>'two');

The value(s) that this select will have are literally that easy and will never change. That's why I was going this route vs. a db lookup.

I get errors that the value needs to be a string, so I know I can't just have an array right in the settings file. Not exactly sure where to go from here.

Thank you!

EDIT

Well, I may have a solution, i'm curious if there is a better way though.

MyPlugin.php

public function getSettingsHtml()
{
    $options = array(
        '' => 'Select',
        '1' => '1',
        '2' => '2',
        '3' => '3',
        '4' => '4',
        '5' => '5',
        '6' => '6',
        '7' => '7',
        '8' => '8',
    );

    return craft()->templates->render( 'myPlugin/_settings', array(
            'settings' => $this->getSettings(),
            'options' => $options
        ) );
    }

_settings.html

forms.selectField({
    'label': "myLabel",
    'instructions': "My Instructions"|t,
    'required': true,
    'id': 'myInput',
    'name': 'myInput',
    'options': options
})
Damon
  • 4,706
  • 1
  • 20
  • 36

1 Answers1

2

If your first attempt – using a variable method – failed, it was probably because you had the "path" to that variable method wrong. If your variable method is called getOptions() and resides in a variable class called MyPluginVariable, the path should be

craft.myPlugin.getOptions

not

craft.myPlugin.settings.getOptions

Anyway, your current solution is fine. The ideal, "Craft-y" way to do stuff like this would probably be to keep the input options in a plugin config file and use a service + variable method to expose the data to the template – but for such a simple case there's really no need to over-engineer things. If you have more fields/options later, or need the data to be dynamic or stored in a database, deal with it then. Don't optimize too early.

Personally, I'd consider just hard coding the options in the template:

forms.selectField({
    'label': "myLabel",
    'instructions': "My Instructions"|t,
    'required': true,
    'id': 'myInput',
    'name': 'myInput',
    'options': {
        '' : 'Select',
        1 : '1',
        2 : '2',
        ...
    }
})
Mats Mikkel Rummelhoff
  • 22,361
  • 3
  • 38
  • 69