Drupal 8从术语实体引用获取字段时出现非对象属性获取错误
Hey there! Let's break down why you're hitting that "Trying to get property of non-object" error when building your Biography XML feed, and walk through how to fix it.
The Root Cause
Most often, this error happens because Term::load() is returning NULL instead of a valid taxonomy term object—but Drupal's rendering system quietly handles empty/invalid entities behind the scenes, which is why your field still renders correctly. Common reasons for the NULL return:
- The entity reference field in your paragraph is empty (no term selected)
- The term ID you're passing to
Term::load()is invalid (e.g., a deleted term, or a malformed ID from incorrect field extraction) - You're not handling multi-value entity reference fields properly
Fixes to Try
1. Add Existence Checks Before Accessing Term Fields
Always validate that the term ID exists and that Term::load() returns a valid object before accessing its properties. Here's how to adjust your code:
// First, get the term ID from your paragraph field (adjust the field name to match yours) $term_id = $paragraph->get('field_your_term_reference')->target_id; // Only proceed if we have a valid term ID and the term loads successfully if (!empty($term_id) && ($term = \Drupal\taxonomy\Entity\Term::load($term_id))) { $term_name = $term->name->value; // Safely use $term_name in your XML feed here } else { // Handle empty/missing terms (e.g., set a default value) $term_name = 'No term specified'; }
2. Handle Multi-Value Entity Reference Fields
If your term reference field allows multiple selections, you can't just grab target_id directly—you need to iterate over the field items:
$terms_field = $paragraph->get('field_your_term_reference'); $term_names = []; foreach ($terms_field as $item) { $term_id = $item->target_id; if ($term = \Drupal\taxonomy\Entity\Term::load($term_id)) { $term_names[] = $term->name->value; } } // Now you can implode or loop through $term_names for your XML
3. Use Bulk Loading for Efficiency (Optional)
If you're dealing with multiple terms across multiple paragraphs, bulk loading is more efficient than loading terms one by one:
$term_ids = []; // Collect all valid term IDs from your paragraph foreach ($paragraph->get('field_your_term_reference') as $item) { if (!empty($item->target_id)) { $term_ids[] = $item->target_id; } } // Load all terms at once if (!empty($term_ids)) { $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadMultiple($term_ids); foreach ($terms as $term) { $term_name = $term->name->value; // Use the term data in your feed } }
Key Takeaway
Drupal's renderer automatically swallows errors from missing entities, but your custom code doesn't—so always validate that the term exists before accessing its properties. This small check will eliminate that frustrating error while making your feed more robust to empty or deleted terms.
内容的提问来源于stack exchange,提问作者jwnardini

