3

I'm making a plugin where I'd like a user to be able to add values to a list, then have that list saved as an array. Are there any smart ways of doing this? My current solution is to have a textarea, then make values out of each line but that's not ideal at all. Does Craft already have a built-in UI pattern for this?

Thank you!

0

1 Answer 1

7

You can use the EditableTable template component (i.e. the same UI component that Table fields use).

Note that this will only work inside the Control Panel – not on the front end. The title of this question says "Plugin settings", so I'm assuming that's your actual use case.

Here's how:

{% import "_includes/forms" as forms %}

{{ forms.editableTableField({
    label: 'Some setting',
    instructions: 'Some instructions here',
    id: 'someSetting',
    name: 'someSetting',
    cols: [
        {
            heading : 'Some column',
            type: 'select',
            options: [{label: 'Foo', value: 'foo'}, {label: 'Bar', value: 'bar'}]
        },
        {
            heading : 'Some other column',
            type: 'singleline'
         },
    ],
    rows: settings['someSetting']
}) }}

As long as the setting you use with the table (someSetting in the example above) has AttributeType::Mixed, Craft will automatically handle serialization for you (the rows you input in the table will be stored as a simple JSON object in the database, just like Table fields are stored).

Note that each column entry can have a type of singleline, multiline, number, select or checkbox. If you don't declare a type, the column will render as a PlainText field.

Also note that the variable settings (which is passed to the rows parameter) refers to an array of your plugin's current settings – meaning you'll need to pass those to your settings.html template like this (the following method should go in your plugin's primary class):

public function getSettingsHtml ()
{
    return craft()->templates->render('yourpluginhandle/settings', array(
        'settings' => $this->getSettings(),
    ));
}

Of course, you can pass additional variables to the settings template – such as a pre-populated array of label/value pairs to use for any dropdown (select) fields inside the table.

If you're unfamiliar with Twig macros, I recommend taking a look at the official docs on the subject (if only to understand the syntax used, and the import statement).

Also, here's the source for the editableTableField macro, which could prove useful.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.