-
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;} -
Copying Values Between Fields on Thousands of Entities
In a nutshell, I had a List (text) field that I needed to convert to a Text field (so that I wasn’t locked in to specific values anymore). Instead of trying to modify the field to convert it from one type to another, I decided to create a new Text field and populate it with the data from the List field (modifying it a bit first). Here’s the script I used to do this. Admittedly it could be cleaner, more efficient, etc. but it’ll show you a few things, and it got the job done for me.
If you choose to run with
drush scr update_nodes.php
you can leave out the top 3 bootstrap lines.