I am in the early stages of developing a plugin for Craft 3. In its settings it should have a checkbox for each section the user has defined that enables the admin to select or unselect each section from processing.

I am struggling with saving the state of the checkboxes when these are created with a loop.

When I create the checkboxes individually it works:


class SettingsModel extends Model {
    public $sectionArticles = '';
    public $sectionResources = '';
    public $sectionMultimedia = '';


{{ forms.checkbox({
    label: 'Articles',
    name: 'sectionArticles',
    checked: settings.sectionArticles,
}) }}
{{ forms.checkbox({
    label: 'Resources',
    name: 'sectionResources',
    checked: settings.sectionResources,
}) }}
{{ forms.checkbox({
    label: 'Multimedia',
    name: 'sectionMultimedia',
    checked: settings.sectionMultimedia,
}) }}

As one would expect, Craft successfully saves and retrieves the settings.

But when I create the checkboxes dynamically, saving their values fails:


class SettingsModel extends Model {
    public $sectionOptions = [];


{% for option in settings.sectionOptions %}

    {{ forms.checkbox({
        label: option.label,
        name: option.name,
        id: option.id,
        checked: option.checked,
    }) }}

{% endfor %}

And the main plugin code that retrieves the settings and creates an array entry for each Craft section:

public function init() {
    $settings = $this->getSettings();

    // Set settings for sections
    $settings->sectionOptions = $this->setSectionOptions();

protected function setSectionOptions() {
    $settings = [];
    $sectionConfig = $this->getSectionConfig();

    foreach ($sectionConfig as $key => $value) {
        array_push($settings, [
            'label' => $value['label'],
            'name' => $value['handle'],
            'id' => $value['id'],
            'checked' => false,
    return $settings;

protected function getSectionConfig() {
    // Get all sections that are channels
    $sections = \Craft::$app->sections->getSectionsByType(Section::TYPE_CHANNEL);
    $sectionConfig = [];

    foreach ($sections as &$section) {
        array_push($sectionConfig, [
            'label'=> $section['name'],
            'handle' => $section['handle'],
            'id'  => $section['id'],
    return $sectionConfig;

I have studied the docs and reviewed other plugins but was unable to find this use case.

What am I missing?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.