Getting a Field from an Entity in Drupal 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
// @see https://drupal.stackexchange.com/a/99711/28091 // Using magic methods we can check if a specific property of the first item // in the field has a value. $entity->field_name is equivalent to // $entity->__get('field_name')). This may not be as safe as using // ->get('field_name') but is useful. Read on... // For simple text fields, booleans, etc. we can ask for ->value, for an // entity reference we'd look at ->target_id. ->uri and ->title for a link. // ->format and ->value for a long text field. Etc. // Due to how __get('field_name') works, if the field doesn't exist on the // entity, an InvalidArgumentException will not be thrown. If instead you // use get('field_name') an exception would be thrown if field_name didn't // exist on the entity. You would want to, in this case, check if the // entity has a field with $entity->hasField('field_name'); // So, to see if a field exists and has a value, here are a few examples: // Example 1 (top level entity already loaded): if (isset($entity->field_name->target_id)) { do_something(); } // Example 2 (in a DSField plugin, load an entity then traverse it): if (!isset($this->entity()->field_fullcalendar_subtitle->value)) { do_something(); } // If we need to loop through multiple items/values in a field (even if // there is only one), you can either ask for an array using ->getValue(), // or you can foreach the field using // foreach ($entity->field_name as $field_item) {}. If you use this approach // the items are objects. This is convenient for field types that have more // methods. For example, you can get to the referenced taxonomy term via // $field_item->entity->name->value, $field_item->entity->tid->value, etc. // Example 3: foreach ($entity->field_location as $field_item) { $location_name = $field_item->entity->name->value; } // Here are some additional examples: // Example 4: $myentity->field_myref->entity->title->value // Example 5: $myentity->field_myref->referencedEntities()[0]->title->value // Example 6: foreach ($myentity->field_myref->referencedEntities() as $entity) { $body_format = $entity->field_body->format; $body_value = $entity->field_body->value; } |