Find if a Checkbox Attribute has been added to a page, but is unchecked

Permalink
I'm looking for a way to discover 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
$page->getAttribute('hide_date');

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.

SkyBlueSofa
 
Mnkras replied on at Permalink Reply
Mnkras
if its on a page try using === 0
SkyBlueSofa replied on at Permalink Reply
SkyBlueSofa
When I printed out the value, it returned some sort of empty string ('', null, false, etc.).

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?
benjoe replied on at Permalink Reply
benjoe
if you just want to make sure that $page->getAttribute('hide_date'); is being passed on to something of if it does exist why not just use

<code>
$test_attribute = $page->getAttribute('hide_date');
if (is_object ($test_attribute))
{
//do this if $page->getAttribute('hide_date') passed as object.
}
else {
//not lucky enough..
}
</code>
jordanlev replied on at Permalink Reply
jordanlev
re: why it works that way: the docs for the isset function (http://us3.php.net/isset ) state that it returns TRUE if the variable isn't set *or* if the variable is NULL.

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).

-Jordan