2

I have a form with a language field with the language select list widget. The options of this field contains an array with a pattern like

['langcode' => t('language')]

Now I want to sort these options in the right order.

The default sorting is on the value but not on the translated one.

e.g. ['de' => t('german')] which I translated into "Deutsch" will now sort under "g" instead of "d".

So I did try to do it in a form alter hook and a preprocess hook but this is not the right place to do it, because the values are still untranslated here.

So my question is how can I sort these options if the values are translated?

2 Answers 2

2

i think it can be done in a hook_form_alter()

if the options are in $form['languages'], you can do something like :

$language_options = $form['languages'];

then manipulate the array $language_options, until it has the order you need then override it in form :

$form['languages'] = $language_options;
2
  • The problem is that the values are untranslated in a form_alter_hook. I could sort it by key but this also doesnt work because the langcode differs from the value.
    – DiDebru
    Commented Nov 13, 2018 at 9:50
  • I need to render the translatablemarkup first than build a new array and sort its values.
    – DiDebru
    Commented Nov 13, 2018 at 10:01
2

Now I did this in a form_alter_hook.

This worked for me.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function arph_profile_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $language_options = $form["field_languages"]["widget"][0]["value"]["#options"];
  $new_language_options = [];
  foreach($language_options as $langcode => $language) {
    /** @var \Drupal\Core\StringTranslation\TranslatableMarkup $language */
    $new_language_options[$langcode] = $language->render();
  }
  asort($new_language_options); // We need to keep the keys here.
  $form["field_languages"]["widget"][0]["value"]["#options"] = $new_language_options;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.