Jump to content

set checkbox field value to true by default


fruid
 Share

Recommended Posts

3 hours ago, fruid said:

a checkbox field cannot be checked by default?

Yes it can, but not via the field settings in the GUI. You can put this hook code in site/templates/admin.php above the require($config->paths->core . "admin.php"); line:

// sets field checkbox to checked on new pages with template basic-page
$wire->addHookAfter('Pages::saveReady', function (HookEvent $event) {
    /** @var Page $page */
    $page = $event->arguments(0);
    if ($page->isNew() && $page->template->name == 'basic-page') {
        $page->checkbox = 1;
    }
});

You just need to adjust template and field name.

Everytime a new page with that template is created the checkbox will be checked by default. 

3 hours ago, fruid said:

also: Admin Action "Field Set or Search and Replace" cannot batch set a checkbox field's value?

If you have TracyDebugger installed, you can do this with a one-liner in the Tracy console in the backend:

$pages->find('template=basic-page, include=all')->each(function($p) { $p->setAndSave('checkbox', 1); });

 

  • Like 3
Link to comment
Share on other sites

5 hours ago, gebeer said:
// sets field checkbox to checked on new pages with template basic-page

I need to just set it once for an array of pages because the checkbox field would be new to them. After that the checkbox field would be set upon page creation.

I'll give the Tracy Debugger option a try then.

Thanks @gebeer!

Link to comment
Share on other sites

1 hour ago, fruid said:

just curious, how is a InputfieldCheckbox field different to a FieldtypeOptions field with only one option? 

FieldTypeOptions gives you different UI and stores data in a different way. If you just need a checkbox, I'd go with InputfieldCheckbox. Less overhead.

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...