Default Selected State in Boolean Custom Fields

Table of Content

Unfortunately there aren’t any special options in the custom field editor to determine whether the custom field will be selected by default or not (especially for the boolean custom fields). This also applies to the option fields. By default, it is the first option will be selected as how the native select box HTML works.

However, there are some workarounds to address this limitation. Let’s say you have been practicing this tutorial and now you want the check box becomes selected by default.

A boolean value basically can be expressed as anything except for values such as false, null and undefined. For example, here you have written down the value of the boolean custom field as true:

true

That’s good, but the check box still cannot be checked by default.

<input name="fields[allow_comments][value]" value="true">

So now, how can you check the check box field by default?

Method 1: Force the Guardian

Basically, the system will only act in a way to check whether the allow_comments key is present or not in the fields array. If it’s present, then the system will automatically add a checked attribute to the associated check box. By using a hook, you can load the Guardian::memorize() data with your desired custom fields key to the fields array. We’re talking about allow_comments, so:

Method 2: Use the Opposite Way

As stated in the tutorial, you can declare the boolean custom field in reverse. So, instead of writing allow_comments, you can write it as disable_comments. This way, you can make the comments become inactive if the check box is checked by the user.

For select boxes, just re-order the options sequence. Put the default value you want to select as the first option in the select box. This way is much simpler. Use the previous method only if you really feel that the name of the field you have created and the order of the option elements was very important and cannot be changed.