2

I have two fields whose type is List (text). In the allowed values list, i want to join them. I used the following code.

$value = $entity->field_a->value . $entity->field_b->value;
$value = $fields['field_a'][0]['value'] . $fields['field_b'][0]['value'];

I can get the result fine, but the value returns the keys only. How can I get the labels?

image of field content i have the key in english, but the label in arabic

2

To get the allowed values set in your field settings you need to call as follows

$entity->field_my_field->getSetting('allowed_values')[$entity->field_my_field->value];

your code should look like this

$value = $entity->field_a->getSetting('allowed_values')[$entity->field_a->value] . $entity->field_b->getSetting('allowed_values')[$entity->field_b->value];
1
0

Although the question is not very clear to me, but I guess the following could help you,

$key1 = $entity->field_a->value;
$key2 = $entity->field_b->value;
$value1= $fields['field_a']["#options"][$key1];
$value2= $fields['field_b']["#options"][$key2];
$value = $value1 . $value2;
5
  • This returns an empty value. Sep 27 at 5:20
  • lets say I have a list text field with allowed values as key|label: US|United States UK|United Kingdom AU|Australia Now i have a saved record in the database with selected value United States when using $value = $entity->field_a->value; this will return US and not United States I want to get the label United States Sep 27 at 5:33
  • @Al-JasimMohammed, as I mentioned in the solutions the first parameter is key, then it means "UK" is a key. you need to get the label. how can it be possible, you should get it from the form element. tell me where do you want to do this? on form submit? the solution is valid, but you need to just adjust the place you want to get it. if it's form and form submit, then we need to get it from $from instead of $fields. please give more details
    – Yuseferi
    Sep 27 at 11:52
  • I want to get it in a computed list text field, that I added from (admin/structure/types/manage/article/fields) Then I want to display it in a node page Sep 27 at 18:17
  • @Al-JasimMohammed you don't do it only in node view template without engaging the couptation? is there any special reason for that? Also you can do it in the node submit.
    – Yuseferi
    Sep 28 at 14:53

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.