1

I have a taxonomy reference field field_location_type with terms: Term A, Term B.

Inside of my custom module, I'm setting up a presave function that will set a hidden field value depending on the term selected in field_location_type.

I'm trying to log the current value of the field just to confirm i'm getting the right one, but there are no values displaying, like ...

function general_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
    \Drupal::logger('general')->notice('here: ' . $entity->field_location_type->value);
}

How do i get the value of the select field field_location_type?

1

Update as @berdir suggested in the comments, the best way to get a field value is:

$node->get('field_location_type')->target_id

In addition, you could also use Field::getValue method if you want an array representation. Something like:

$entity->field_location_type->getValue()[0]['target_id']);

In addition if you need the term name (Option A ) from the id you can do this:

  $tid = $entity->get('field_location_type')->target_id;
  $term = \Drupal\taxonomy\Entity\Term::load($tid);
  // $name should have 'option A' or 'option b'
  $name = $term->getName();

Update: one way to figure out what methods are available to you is to use xdebug in PhpStorm. If you set a break point after $field = $entity->field_location_type; you can then type $field-> and then hit ctrl and space the editor will provide suggestions based on the type of $field Here is a screen shot: enter image description here

  • Unfortunately thats brining back an empty value. Note, 'Option A' is the expected value. – erier May 16 '18 at 19:34
  • sorry you are using taxonomy term, you need to use target_id, updated answer. I will update it on how you can get the name from it. – awm May 16 '18 at 19:38
  • You rock @awm! How did you know to use getValue()[0]['target_id']? I want to be able to figure that out without you next time. – erier May 16 '18 at 19:53
  • I usually check the type of the object returned then proceed to open the appropriate api. If you use xdebug you can see the type of the object returned on the entity. – awm May 16 '18 at 20:00
  • 2
    I don't understand why everyone uses getValue(). Don't do that unless you really want an array representation of the values. Just use $node->get('field_location_type')->target_id for the first delta. [1]->target_id for other deltas. Like this, you can also access ->entity on reference fields and you have the loaded entity. See wizzlern.nl/drupal/drupal-8-entity-cheat-sheet – Berdir May 17 '18 at 5:55

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.