-
Getting a Field from an Entity in Drupal 8
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455// @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;} -
Adding Fields to Inline Entity Form Table
Inline Entity Form is a useful module for reference entities and being able to edit them in place.
Here’s what the edit form looks like out of the box for an unlimited value entity reference:
Often it’s helpful to provide additional information to your editors.
If you have a look at inline_entity_form.module you will find a function called theme_inline_entity_form_entity_table(). Within this you will see how this table is built, and how you can manipulate the form to add additional columns of information.