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

jaypan’s picture

Assuming field_sae is your term reference, I think you want

$term_id = $entity->field_sae->entity_id

Although I'm going off memory, so  I may be incorrect. You can find out by dumping the field and seeing the values:

die('<pre>' . print_r($entity->field_sae->getValue(), TRUE) . '</pre>');

That will give you the keys you can use.

Contact me to contract me for D7 -> D10/11 migrations.

Miss C’s picture

Many thanks Jaypan!

$term_id = $entity->field_sae[0]->target_id

ended up being target_id!

johnpitcairn’s picture

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();

Miss C’s picture

Thanks John,

This works a treat! Thanks for taking the time to answer my somewhat silly question ;)

johnpitcairn’s picture

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...

jaypan’s picture

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.

imclean’s picture

This should get an array of all referenced entities:

$terms = $entity->get('field_sae')->referencedEntities()