nortmas
9/27/2017 - 4:02 PM

Field basics

<?php 

// -- Get Values --//

// Simplest way:
$field_value = $node->field_name->value
$field_value = $node->field_name->target_id
$field_value = $node->field_name->get(0)->target_id

# Fetch first element from the field.
$field_value = $node->get('field_name')->get(0)->get('value')->getValue();
// or 
$field_value = $node->field_name->value;
// if it's only single string value:
$node->get('field_name')->getString();

// get referenced entity
$term = $node->get('field_name')->referencedEntities()[0];
// or
$downlad_file->field_name->entity->label();
// or
$term = \Drupal\taxonomy\Entity\Term::load($node->get('field_name')->target_id);

$body_text = $node->body->value;
$body_text = $node->get('body')->value;
$body_array = $node->body->getValue();

// $body_array example: 

array(
  0 => array(
    'value' => '<p>Hello!</p>',
    'summary' => '',
    'format' => 'basic_html',
  ))
  
// -- Field view: -- //

$display_options['settings']['image_style'] = 'even_bigger_thumbnail';
$node->field_name->view($display_options);
// or
$node->field_name->view('teaser');
// or
$node->field_name->view([
  'type' => 'image',
  'label' => 'hidden',
  'settings' => array(
    'image_style' => 'larger_thumbnail',
    'image_link' => 'content',
  ),
]);

// -- Common things -- //
	 
$field_item_list = $entity->get('field_name');
// Array of raw values per field.
$fields_array = $entity->toArray();
 // Array of FieldItemList per field.
$field_item_lists = $entity->getFields();      
$text_format = $node->body->format;
$third_tag_id = $node->field_tags[2]->target_id;
$has_body = $node->hasField('body');
$empty_body = $node->body->isEmpty();
$fields = $node->getTranslatableFields();
$entity->set('title', 'New title');
$field_names = array_keys($node->getFields());
$field_names = array_keys($this->entityFieldManager->getFieldDefinitions('node', 'article'));
$definition = $entity->getFieldDefinition('field_name');
<?php

$vid = $node->field_tags->entity->getVocabularyId();
$uri = $node->field_file->entity->getFileUri();
$name = $node->getOwner()->getDisplayName();
$roles = $node->getOwner()->getRoles();