In a previous article, we looked at a very fast and efficient xPDO method for getting the value of a single field from a MODX object using the getValue
method of the xPDO object. For example, this code will get the introtext
field from a resource with the pagetitle
"Products":
$query = $modx->newQuery('modResource', array( 'pagetitle' => 'Products', )); $query->select('introtext'); $intro = $modx->getValue($query->prepare());
In this article, we'll look at using it with boolean (Yes/No) fields like published
, and isfolder
.
The main code of our method is the same, but you need to be a little careful in detecting errors because if the field is set to No
, the method will return '0'
, and PHP needs a little help in distinguishing that from an error return (false
). You also need to remember that the return value will always be a string, even if the field contains an integer and is designated as an integer field. Even when you get the raw value of a time/date field, you'll get a string like this one: "1362455548"
The trick is to use three equal signs (===
) to detect the error condition. Here's an example using
published
:
$query = $modx->newQuery('modResource', array( 'pagetitle' => 'Products', )); $query->select('published'); $isPublished = $modx->getValue($query->prepare()); if ($isPublished === false) { /* Oops, an error. Probably the resource wasn't found */ } else { return $isPublished; }
When using ===
, the code in the if
statement will only execute if $isPublished
is an actual boolean false
. The string '0'
won't pass this test. Passing the ===
test requires that both variables be of the same type. When using ==
(two equal signs), PHP will do a "loose" comparison that disregards the types of the variables.
Be careful in interpreting the non-error return. If you know PHP, this is probably not news to you, but you have to be careful in converting a string containing a 1
or 0
to a true/false value. For example, if you want to do something in the code above if the resource is published, this code *won't* work:
if ($isPublished === 1) { /* Do something */ }
Because we used three equal signs, PHP won't find '1'
equal to 1
because they are different types. $isPublished
is a string, and 1
is an integer.
Any of the following will work, though:
if ($isPublished === '1') if ($isPublished == 1) if ($isPublished)
The first one compares $isFolder
to the string '1'
. Since they are both strings, it works. The second compares the two with ==
, which doesn't care about the types of the variables. The third one is the most commonly used. It works because PHP converts the variable to a boolean (true/false/ value and it considers '1'
to be true and '0'
to be false.
Comments (0)
Please login to comment.