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 ?
$value = $node->get('field_wheel-type')->getValue();
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;
$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.