0

I have a content type (let's name it Wheel for an example) that have a field referencing an other content type (which could be Car, Motorbike, Bicycle ...). So a node named WheelMotorbikeBrand whould reference the content type Motorbike. I would like to retrieve the value of this field in a preprocess with something like $node->get('field_wheel-type') but I'm not able to obtain a value. How can I retrieve the value of my field ?

2 Answers 2

3

You get a field value:

$value = $node->field_text->value;

If the field has a property value like fields for texts, numbers or booleans usually have.

A reference field has no value property, but one for target_id. So you get the id of the referenced entity with:

$target_id = $node->field_reference->target_id;

Or the referenced entity already loaded:

$referenced_node = $node->field_reference->entity;

Which you then can use to obtain a field value from the referenced node:

$value = $referenced_node->field_text->value;

The method ->getValue():

$values = $node->field_text->getValue();

gets an array of all properties and field items and so works also if you don't know the properties of a field or how many items it has.

Caveat: You don't find the property entity from the example above in this array, because it is computed and not stored in the database.

1

try :

$value = $node->get('field_wheel-type')->getValue();
2
  • It's working indeed. What is the difference between ->getValue() and ->value ? I thought it was the same. Thanks for the answer.
    – Tibo
    Oct 25, 2018 at 14:05
  • ->value is a protected attribute. ->getValue() is a public method to get that protected attribute.
    – izus
    Oct 25, 2018 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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