One of the projects I’ve been working on recently presents the user with a comprehensive set of options. As usual, the options take the form of a variety of different elements:
- and more.
In most cases, you should be familiar with initializing default values for all of these element types. Radio buttons may be the exception. And if they are, then you’ve no doubt run into a PHP notice when saving empty radio button values.
And having PHP notices is no good, right?
Regardless of if you’re using the WordPress Settings API or some custom serialization code, these notices can still show up. If you use Query Monitor, then you’ve likely seen this show up in your menu. Similarly, if you use the Console (or another application) to monitor your PHP logs, you’ve probably seen the error as well.
One place in which this can be tricky to deal with is when you’re working with radio buttons without an initial value.
Saving Empty Radio Button Values
That is, a user may be presented with a screen but may not select an option during the time they’re on it. Thus, they are left saving empty radio button values.
When the page reloads, and you’re trying to retrieve the value of the radio button from the array of options (or however you’ve opted to store it), you’re going to get a warning because the index of that particular value will not exist.
And though some may argue this is too strict, I’m no fan of shipping production-level code that generates any warnings. Assuming that you don’t want to initialize the group of button buttons with a default value, what’s the resolution to this problem?
First, it’s not terribly uncommon to see code that checks to see if the value is set and then, if if’s not, will provide a default value. This is something that can work, but it makes the code a bit weird to understand. That is, you’re taking the collection of options, checking for the presence of the value, and then setting a value after you’ve already retrieved it.
I’d rather work in the other direction.
That is, I’d like to have a value that’s set and then when the user clicks save, I want to save the default value. This way, I don’t have to do any condition checking to mess with the collection of options just to make sure I’m silencing a PHP warning. Here’s one approach I’ve found useful: