Last active
September 3, 2019 09:43
-
-
Save eaton/b2a12ae4a03ba77d0d7e9ce0bd18c956 to your computer and use it in GitHub Desktop.
Drupal 8 field wrangling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Check whether a node's bundle has a particular field | |
if ($node->hasField('field_might_be_missing')) { ... } | |
// Check field-type-specific empty/not empty logic | |
if ($node->field_name->isEmpty()) { ... } | |
// Iterate over individual instances in a field. field_name isn't an actual | |
// array, but a special iteratable class, so it won't die if the field is empty. | |
foreach ($node->field_name as $delta => $field_instance) { ... } | |
// Return an array containing the raw property values for the field. | |
// If a delta is specified, only that field delta's values are returned. | |
$node->field_name->getValue(); // [ 0 => ['value' => 'foo', 'format' => 'basic_html']] | |
$node->field_name[0]->getValue(); // ['value' => 'foo', 'format' => 'basic_html'] | |
// Retrieve one particular property from a field instance. | |
// If no delta is specified for a multi-value field, delta 0 is assumed. | |
$node->field_name->format; // 'basic_html' | |
$node->field_name[0]->format; // 'basic_html' | |
// Working with Entity Reference fields | |
$node->field_related->target_id; // Raw entity ID | |
$node->field_related->entity; // Fully loaded entity | |
$node->field_related->entity->field_remote; // Field instance on the loaded entity | |
// Generate a render array for a given field. If no display mode is | |
// passed in, 'default' is assumed. | |
$node->field_name->view('default'); | |
// Fancier tricks! In a preprocess hook, pull a field from a referenced node | |
$variables['content']['field_remote'] = $node->field_related->entity->field_remote->view('default')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment