Jump to main content Jump to doc navigation

Accessing Template Variable Values via the API

Like just about everything in the MODX GUI, you can access Template Variables and their values via the MODX API. This relies on the xPDO method getObject and related functions, but we demonstrate some examples here because it relates directly to Template Variables.

getTVValue

string|null getTVValue (str|integer $tv_name OR ID of TV)

See core/model/modx/modresource.class.php

getTVValue Usage

Let's say we have a TV named 'bio', and we're going to retrieve page id 123 that uses this TV. Here's what our Snippet might look like:

$page = $modx->getObject('modResource', 123);
return $page->getTVValue('bio');

getTVValue fetches values from the resource cache when available. These caches are normally cleared when saving a resource, however if you are updating TV values using the setTVValue method below, these values will not be reflected directly because of the cache. If you absolutely need the latest data, you could bypass the cache by going straight for the data and using getObject to get the TV value record.

$tvr = $modx->getObject('modTemplateVarResource', array(
  'tmplvarid' => $tvId,
  'contentid' => $resourceId
));
if ($tvr) {
  return $tvr->get('value');
}
else {
  $tv = $modx->getObject('modTemplateVar', $tvId);
  if ($tv) return $tv->get('default_text');
}
return '';

setTVValue

Use setTVValue to save a new value to a TV. Unlike some other xPDO API methods, this method stores values to the database immediately, so you do not need to invoke a separate call to a save() method. This method does not clear the resource cache.

boolean setTVValue (str|integer $tv_name OR ID of TV, string $value)

Note that when using setTVValue, it is possible for an immediate getTVValue to return a cached value.

setTVValue Usage

$page = $modx->getObject('modResource', 123);
if (!$page->setTVValue('bio', 'This is my new bio...')) {
    $modx->log(xPDO::LOG_LEVEL_ERROR, 'There was a problem saving your TV...');
}

See Also

Support the team building MODX with a monthly donation.

The budget raised through OpenCollective is transparent, including payouts, and any contributor can apply to be paid for their work on MODX.

Backers

  • modmore
  • STERC
  • Digital Penguin
  • Jens Wittmann – Gestaltung & Entwicklung
  • Fabian Christen
  • Dannevang Digital
  • Sepia River Studios
  • CrewMark
  • Chris Fickling
  • deJaya
  • eydolan
  • Lefthandmedia
  • Murray Wood
  • Following Sea
  • Anton Tarasov
  • Stéphane Jäggi
  • Raffy
  • Snow Creative
  • A. Moreno
  • Nick Clark
  • JT Skaggs
  • Helen
  • YJ
  • krisznet
  • Richard
  • Yanni

Budget

$306 per month—let's make that $500!

Learn more