Get Child TV Values

Getting the TV values for children of the current resource in MODX.


In the previous article, we looked at several methods to get the TV value for a particular resource. In this one, we'll see how to get the TV values of children of the current resource.

One method to get the children's TV values would be to get all the children using code like this:

$tvId = 12;
$children = $resource->getMany('Children');
foreach ($children as $child) {
   $tvValue = $child->getTVValue($tvId);
}

The code above is fairly wasteful of both time and memory. It gets the IDs of the children, then gets every child object, even though we don't need the resource objects — we just want the TV values. It also gives us the rendered value of all TVs even if we could use the raw value, which would be faster. It will be significantly faster to get the child IDs ourselves and get their values without bothering to retrieve all the child resource objects. We can do that with the $modx method, getChildIds().

getChildIds()

MODX has a handy function for getting the IDs of children of any resource:

$resourceId = 12;
$childIds = $modx->getChildIds($resourceID);

The code above will set $childIds to an array containing the IDs of all children of resource 12.

Getting the TV Values

Once we have the child IDs, getting the TV values is easy. How we get them will depend on whether we want the raw or processed value of our TV:

$output = "";
$tvId = 12;
$resourceId = $modx->resource->get('id');

$childIds = $modx->getChildIds($resourceId);
$tv = $modx->getObject('modTemplateVar', $tvId);

if ($tv) {
    $tvName = $tv->get('name');
    $output .= "\n<br />TV: " . $tvName;
    foreach ($childIds as $childId) {
        $output .= "\n<br /><br /> --- Value for Resource " . $childId;
        $rawValue = $tv->getValue($childId);
        $renderedValue = $tv->renderOutput($childId);
        $output .= "\n<br /> ------ Raw value: " . $rawValue;
        $output .= "\n<br /> ------ Rendered value: " . $renderedValue;
    }
} else {
    $output = "\n<p>TV not found</p>";
}

return $output;

In the code above, we get the TV's name only to show it in the output. It's not necessary. Of course in a real-life case, you'd want the raw value of the TV or its rendered value, but not both. The code above could help you see whether you really need the rendered value or not, however. If the two are the same, you might as well use the faster raw value.

Notice, too, that although we've set the $resourceId variable to the ID of the current resource, we could set it to the ID of *any* resource to get the TV value for that resource's children. The rest of the code would be the same. If the code were in a snippet, we could pass the desired parent's ID as a property in the snippet tag.



Comments (0)


Please login to comment.

  (Login)