Answers:
不知道是否有更好的方法,但是我先获取了允许的值来获取值。
$allowed_values = $state->getFieldDefinition('field_state')->getFieldStorageDefinition()->getSetting('allowed_values');
$state_value = $state->get('field_state')->value;
$info['state_name'] = $allowed_values[$state_value];
正确的方法是使用options_allowed_values()函数。由于该字段可能没有“ allowed_values”设置,因此可以通过“ allowed_values_function”提供选项。
现场示例:
情况1:您有一个实体对象,并希望获得带有选项的字段值标签。
$field_name = 'field_state';
/** @var \Drupal\Core\Field\FieldStorageDefinitionInterface $field_definition */
$field_definition = $entity->{$field_name}->getFieldDefinition();
// This is a list (array) of options for the field definition:
// [{option1_key} => {option1_value}, {option2_key} => {option2_value}, ...]
$field_allowed_options = options_allowed_values($field_definition, $entity);
// If the field is NOT multiple.
/** @var string|\Drupal\Component\Render\MarkupInterface $field_value_label */
$field_value_label = $field_allowed_options[$entity->{$field_name}->value];
// If the field is multiple.
$field_value = array_column($entity->{$field_name}->getValue(), 'value', 'value');
/** @var string[]|\Drupal\Component\Render\MarkupInterface[] $field_value_labels */
$field_value_labels = array_intersect_key($field_allowed_options, $field_value);
情况2:您没有实体对象,但想获取该实体字段的所有允许选项的列表。
$entity_type_id = 'node';
$field_name = 'field_state';
$entity_fields_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($entity_type_id);
/** @var \Drupal\Core\Field\FieldStorageDefinitionInterface $field_definition */
$field_definition = $entity_fields_definitions[$field_name];
$field_allowed_options = options_allowed_values($field_definition);
$allowed_options
?
drupal 7种方式:
$jid = $row->job_id_181;
if($jid)
{
$jobNode = node_load($params['jid']);
$key = $jobNode->field_job_location['und'][0]['value'];//2
if($key)
{
$field = field_info_field('field_job_location');
$label = $field['settings']['allowed_values'][$key];
echo $label;
}
}
希望它对将来的人有所帮助。
这可能也有帮助:
$node->field_state->getFieldDefinition()->getSetting('allowed_values');