1

Where does the value of entity come from in a field of a content type?

I am trying to understand how the property (if it is a property) entity is related to the field.

This question is more informative, I describe my case below.

I have a type of content News, in this I added field of type image called "field_image" with a limit of a single value.

Type of content: News Field: field_image

Debuggin:

I programmatically load the node:

// Return Drupal\node\Entity\Node;
$node = $this->entityTypeManager->getStorage("node")->load(1);

// {\Drupal\file\Plugin\Field\FieldType\FileFieldItemList}
kint($node->field_image);

// {Drupal\file\Entity\File}
kint($node->field_image->entity); // from where comes from entity?

From the last example I show above ($node->field_image->entity), where does the property entity appear, how can field_image access it and know that it is a file type field?

I'm just trying to understand these internal Drupal relationships. Thank you very much for helping me understand this. regards

1

It's literally magic (well, PHP magic methods anyway).

FieldItemBase implements __get(), which will respond to any property on the object (existing or not):

public function __get($name) {
  // There is either a property object or a plain value - possibly for a
  // not-defined property. If we have a plain value, directly return it.
  if (isset($this->properties[$name])) {
    return $this->properties[$name]->getValue();
  }
  elseif (isset($this->values[$name])) {
    return $this->values[$name];
  }
}

And the image field type extends the entity reference field type, which maintains an entity property (see EntityReferenceItem::propertyDefinitions).

So when you request the non-existent entity property on the field class, FieldItemBase hooks it up for you via the $properties array, and you get an entity back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.