Find if a Checkbox Attribute has been added to a page, but is unchecked
My testing has indicated that this code to get the value of a checkbox attribute
will return 'empty' in 2 cases:
* It has not been added to the page
* It has been added, but remains unchecked
I'd like to be able to differentiate between these two scenarios in order to use a 'sitewide' default for the first case and do something else in the second case.
This is what I ended up with:
$this->hide_date = $page->getAttribute('hide_date'); $this->hide_date = isset($this->hide_date) ? ($this->hide_date ? true : false) : null;
It seems a bit wonky given that the first line should ensure that $this->hide_date is set.
Any ideas why this works the way it does and how I can ensure that it continues to work?
$test_attribute = $page->getAttribute('hide_date');
if (is_object ($test_attribute))
//do this if $page->getAttribute('hide_date') passed as object.
//not lucky enough..
When you call $page->getAttribute('whatever') and the attribute hasn't been set on a page, the function returns NULL.
You could very slightly simplify your code by casting the attribute to a boolean (instead of the ternary operator "... ? ... : ..."), and you could use is_null() function instead of isset() to make it clearer what's going on:
$this->hide_date = $page->getAttribute('hide_date'); $this->hide_date = is_null($this->hide_date) ? null : (bool)$this->hide_date;
...but unfortunately that's still 2 yucky lines of code (it's just the nature of PHP as a language).