Skip to main content

Drupal ^8: How to get list item text programmatically

//Check if the field value is set and not empty
  if ($entity->hasField('field_custom') && !$entity->get('field_custom')->isEmpty()) {
    $entity->get('field_custom')->getValue(); //returns the array key value e.g ['alpha'=>'Alpha letter', 'beta' => 'beta letter'] will return alpha or beta 
    $entity->field_custom->getSetting('allowed_values'); // returns the whole list text array e.g. ['alpha'=>'Alpha letter', 'beta' => 'beta letter' ]
    $entity->field_custom->getSetting('allowed_values')[$entity->field_custom->value]; //Returns the array selected value - name not the array key so for example if the value is beta then it will return beta letter for the array ['alpha'=>'Alpha letter', 'beta' => 'beta letter'] and the beta as the selected value
  }

 

entity