In the last article, we saw a solution to the "Call to Member Function get on null" error in MODX. In this one, we'll add an error message to let us know when a resource has an invalid parent field.
In the code from the previous article, we checked the $parentId variable to make sure it's not empty, and we checked the $parentObject variable to make sure it's not null:
$docs = $modx->getCollection('modResource');
foreach ($docs as $doc) {
$parentId = $doc->get('parent');
$parentObject = null;
if (!empty($parentId)) {
$parentObject = $modx->getObject('modResource',
$parentId);
// or $parentObject = $doc->getOne('Parent');
}
if ($parentObject !== null) {
$output .= '<li>' .
$parentObject->get('pagetitle') .
'</li>';
} else {
/* No parent -- do something else */
}
}
return $output;
Adding an Error Message
As we said in the previous article, it's a good practice to make sure that your code won't crash with a PHP error, no matter what happens. That means "sanity checks" before you call any method of an object. In production code, though, it would be wise to add the following lines inside the else block in the code above:
if ( (!empty($parentId)) && $parentObject === null) {
$msg = 'Resource: ' . $doc->get('pagetitle') .
' has an invalid parent field (' . $parentId . ')';
$modx->log(modX::LOG_LEVEL_ERROR, $msg);
}
That will put a message in the MODX Error Log telling us about the invalid parent field.
Here's the full code with that error message added:
$docs = $modx->getCollection('modResource');
foreach ($docs as $doc) {
$parentId = $doc->get('parent');
$parentObject = null;
if (!empty($parentId)) {
$parentObject = $modx->getObject('modResource',
$parentId);
// or $parentObject = $doc->getOne('Parent');
}
if ($parentObject !== null) {
$output .= '<li>' .
$parentObject->get('pagetitle') .
'</li>';
} else {
/* No parent -- do something else */
/* Report invalid parent fields */
if ( (!empty($parentId)) &&
$parentObject === null) {
$msg = 'Resource: ' .
$doc->get('pagetitle') .
' has an invalid parent field (' . $parentId . ')';
$modx->log(modX::LOG_LEVEL_ERROR, $msg);
}
}
}
return $output;
Coming Up
In the next article, we'll look at how to stop Google Chrome from caching your code.
Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at Hosting.com (formerly A2 Hosting). (More information in the box below.)

Comments (0)
Please login to comment.