Blog Sections Open

Looping Through Filled TV Fields Without Hard-Coding Every Attribute

A modeling pattern for product-like resources where only filled TV fields should appear in the output instead of a fixed hard-coded list.

Catalog and spec-driven projects often have many optional attributes. Hard-coding every possible TV in the template quickly becomes unmaintainable, especially when different product categories use different subsets of fields.

The goal

Output only the TVs that are filled for the current resource, instead of rendering a long fixed list with many empty values.

A practical approach

  • group relevant TVs by category or naming convention
  • collect their values in PHP or a helper snippet
  • render only non-empty entries through a loop or chunk
<?php
$fields = ['size', 'weight', 'color', 'material'];
$out = [];
foreach ($fields as $field) {
    $value = $modx->documentObject[$field] ?? '';
    if ($value !== '') {
        $out[] = ['label' => $field, 'value' => $value];
    }
}
?>

Why this is better

The template becomes more flexible, new optional characteristics are easier to add, and each product type can stay lean instead of carrying a large static presentation table.

Newer post

Restoring the Internal Link List in TinyMCE for Evolution CMS

Troubleshoot the missing internal link list in TinyMCE so editors can insert document links from the manager again.

Older post

Accessing Template Placeholders from a Nested Snippet

A parser guide for cases where a snippet is called inside an item template and needs access to placeholders created by the outer listing snippet.