Magento 2 Admin Grid – Fixing Edit Form Checkbox Not Checked

adminformcheckboxmagento2

I created magento admin grid form

In my form i am using checkbox
app/code/[vendername]/[modulename]/Block/Adminhtml/Blog/Edit/Tab/Main.php

$fieldset->addField(
        'applies_to_books',
        'checkbox',
        [
            'label' => __('Applies to Books'),
            'name' => 'applies_to_books',
            'data-form-part' => $this->getData('applies_to_books'),
            'onchange'   => 'this.value = this.checked ? 1 : 0;',
        ]
    );
    $fieldset->addField(
        'applies_to_levels',
        'checkbox',
        [
            'label' => __('Applies to Levels'),
            'name' => 'applies_to_levels',
            'data-form-part' => $this->getData('applies_to_levels'),
            'onchange'   => 'this.value = this.checked ? 1 : 0;',
        ]
    );
    $fieldset->addField(
        'applies_to_addons',
        'checkbox',
        [
            'label' => __('Applies to Addons'),
            'name' => 'applies_to_addons',
            'data-form-part' => $this->getData('applies_to_addons'),
            'onchange'   => 'this.value = this.checked ? 1 : 0;',
        ]
    );

While saving values are saved database but it not checked backend admin form
enter image description here

Best Answer

You need to add one parameter 'checked' => true, in your code like below,

$fieldset->addField(
        'applies_to_addons',
        'checkbox',
        [
            'label' => __('Applies to Addons'),
            'name' => 'applies_to_addons',
            'data-form-part' => $this->getData('applies_to_addons'),
            'onchange'   => 'this.value = this.checked ? 1 : 0;',
            'checked' => true //add this line in your each fieldset.
        ]
    );