Getting TV Values from Another Context

Here's a trick for getting the TV values for a resource that's in another context


In this article, we'll look at a method for getting a TV value for a TV connected to a resource in another context.

MODX logo

The Problem

MODX can be very cranky about getting the value of a TV that's connected to a resource in a context different from the one set in the context_key field of the current resource. There may be a way to set user permissions so that this works, though I've never found one.

Suppose that you have a getResources or pdoResources call that gets resources from multiple contexts. In the Tpl chunk, there is a tag for a TV that holds the path to the image. The resource fields are displayed normally, but the image tag leads to a 403 forbidden error.


The Solution

You could spend some time trying to use permissions to solve this, but here's a cheat using a simple custom snippet that should produce the image.

In the Tpl chunk, where the image should appear, put this tag:

[[!getImage? &docId=`[[+id]]` ]]

Then create a snippet called getImage with this code:

$tvId = 12; // replace 12 with the id of the image TV
$docId = $modx->getOption('docId', $scriptProperties);

if (empty($docId)) {
    $output = 'NO DOC ID';
} else {
    $c = array(
        'tmplvarid' => $tvId,
        'contentid' => $docId
    );
    $tvr = $modx->getObject('modTemplateVarResource', $c);
    if ($tvr !== null) {
        $output = $tvr->get('value');
    } else {
        $output = 'Could not get TemplateVarResource';
    }
}

return $output;

This code bypasses the permission system and gets the value of the TV directly from the modTemplateVarResource record. You should be aware that if the TV is set to its default value, there will be no modTemplateVarResource for it and the code will fail. It may also fail (though it's less likely) if the default value of the TV is @INHERIT. As long as neither of those exceptions applies, and you can use the raw value of the TV, it should work fine.


Processed Value

If you need the processed value of the TV because one of the exceptions above applies, or the TV requires processing (e.g., an image-type TV or a list TV). You can try this code instead. I've never tested it, but I'm pretty sure it will work:

$tvId = 12; // replace 12 with the id of the image TV
$docId = $modx->getOption('docId', $scriptProperties);

if (empty($docId)) {
    $output = 'NO DOC ID';
} else {
    $tv = $modx->getObject('modTemplateVar', $tvId );
    if (! $tv) {
        $output = 'Could not get TV Object with ID: ' . $tvId';
    } else {
        $output = $tv->renderOutput($docId);
    }
}

return $output;

Coming Up

In the next article, we'll look at how to rearrange the items in the MODX Top Menu.


Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)



Comments (0)


Please login to comment.

  (Login)