How to apply a default field value to existing content

Recently I wanted to enable Views filtering by newly added checkbox controlling visibility. Sounds simple, but in Drupal 9 it doesn’t works well without some help. There are at least two approaches how to fix this.

It turned out that this new checkbox “Hide this node in the list of …” has in Views Filter Criteria only two options: True or False.

But there is problem, because when you add new field, it will not create any value for already existing nodes. So, this Filter doesn’t work at all. Unfortunately, there is no option “True or Not set”. I found two solutions how to fix it.

33Visibility boolean Views filter

There is Issue related to this problem: Boolean field filtering does not work when no values are set https://www.drupal.org/project/drupal/issues/2862828

I also found this stack exchange page discussing it: Filter on boolean with NULL (unset) value https://drupal.stackexchange.com/questions/288232/filter-on-boolean-wit…

 

Solution #1 – module field_defaults

Thanks to community there is contrib module Field Defaults https://www.drupal.org/project/field_defaults .

First of all, visit settings page (/admin/config/system/field_defaults/settings) and tick the "Retain original entity updated time" checkbox.

33field_defaults configuration

After installation new options will be display on the field definition. Using checkbox “Overwrite existing …” you can set default values for all existing content.

33field_defaults field settings

When you tick “Overwrite existing … ” and hit the Save settings button, batch process will start.

33field_defaults Processing batch

And in your View all content will have now values so the filtering will work.

 

Solution #2 – replace Boolean checkbox

But sometimes solution above is not the best one. In my case, in the View I was listing several content types, but only one of them should have this option to show/hide content in the list. Solution #1 would mean in this case to create this Boolean field even for content types where it doesn’t make sense to have. This means then to hide it in interface, using some hook or css hack.

I solved this using workaround – I replaced Boolean checkbox with text list. It is not so elegant as checkbox, but it works and IMHO it was better solution.

33Visibility select radio options

For this text list now Views filter displays more options, it is simple to set up my filtering there. Nice trick!

33Visibility select radio Views filter

 

Conclusion

In this article I showed to you how to set default values for the fields. And how to solve issue with Boolean field when we would like to use it for Views filtering.