By Miss C on
Hi, I'm new to Drupal and this seems like it should be a stupidly simple task but I just cant seem to get past this.
I'm writing php in a calculated field to combine and format taxonomy terms that are linked to my entity (product) via related entity fields.
So far I can access a taxonomy term label with the following if I stub in an ID:
$term = Term::load(560); $fullvalue = $fullvalue . ' ' . $term->getName(); //full value will later be used to combine values $value = $fullvalue;
I'm having no end of trouble getting the related term ID from my entity however.
$value = $entity->field_sae->value
This is returning nothing and no errors are being reported.
Tips on how to best debug calculated field code would also be helpful
Any pointers will be gladly appreciated
Thanks in advance!
Comments
Assuming field_sae is your
Assuming field_sae is your term reference, I think you want
Although I'm going off memory, so I may be incorrect. You can find out by dumping the field and seeing the values:
That will give you the keys you can use.
Contact me to contract me for D7 -> D10/11 migrations.
Many thanks Jaypan!
Many thanks Jaypan!
ended up being target_id!
For a single-value
For a single-value entityreference field, you may also try using the "entity" magic method, something like:
$entity->field_sae->entity->label();or possibly
$entity->field_sae[0]->entity->label();Thanks John,
Thanks John,
This works a treat! Thanks for taking the time to answer my somewhat silly question ;)
Not a silly question at all.
Not a silly question at all. The "magic" entity method is not well documented.
Note that it may not always work, if the target entity has not already been loaded elsewhere (or something, I am not sure) and then you will have to use more intermediate methods. For some discussion see:
https://drupal.stackexchange.com/questions/186315/how-to-get-instance-of...
John's method is better than
John's method is better than mine. I focused on getting the Term ID, without looking at the bigger picture that getting the Term ID was just a step in getting the Term entity, which is already available.
Contact me to contract me for D7 -> D10/11 migrations.
You can also use referencedEntities()
This should get an array of all referenced entities:
$terms = $entity->get('field_sae')->referencedEntities()