Blog Sections Open

Counting How Many TV Fields Actually Contain Data

If a resource has several image TVs, count only the filled ones before you decide how to build the gallery or slider output.

Projects often store a small gallery across several separate TV fields. Before rendering a slider, thumbnail list, or conditional gallery block, it helps to know how many of those TVs actually contain values.

Simple PHP approach

$tvs = array('image1', 'image2', 'image3', 'image4');
$count = 0;
foreach ($tvs as $tv) {
    if (trim($modx->documentObject[$tv]) !== '') {
        $count++;
    }
}
return $count;

Why count first

  • skip empty gallery wrappers
  • switch layout when there is only one image
  • avoid placeholder output for missing files

Recommendation

Once a gallery starts growing beyond a few TVs, move to a more scalable structure such as MultiTV or another repeatable field pattern. But for a fixed small set of TVs, counting filled values first is perfectly reasonable.

Newer post

Linking Images from assets/images in TinyMCE with KCFinder

If KCFinder opens the wrong folder for links, fix the browser path setup instead of copying files around and breaking your media workflow.

Older post

Outputting a TV Label and Value Only When the TV Is Filled

If a TV may be empty, wrap the whole row or list item in a condition so that the label and the value disappear together.