0

I have multiple contact forms in my multilingual D8 website:

  • questions or remarks
  • order gift voucher

Those have custom fields (like field_phone, field_amount, ...)

For my custom fields, the form-element-label.html.twig with label is a string, whilst the core "message" field is a TranslatableMarkup object.

How do I provide the translation for field labels of these forms?

2 Answers 2

4

Standard fields of a contact form are predefined in code. Custom fields are in configuration and the translation works differently.

This should work:

  1. Enable the module "Configuration translation"
  2. /admin/structure/contact/manage/feedback/fields
  3. Add field
  4. Enter an english label
  5. Configure the field type
  6. Choose Tab "Translate contact message fields"
  7. Add a translation in another language
  8. Enter a translated label
1
  • 1
    To clarify, "predefined in code" means they use t() and you translate them through standard interface translation. Note that, unlike configurable fields, you can not translatable e.g. "Subject" differently per form or even differently on contact forms and other places where "Subject" is used. If you need that, hide the default field and add your own.
    – Berdir
    Commented Aug 21, 2016 at 19:53
1

A possible (temporary) sollution:

In theme_form_contact_message_form_alter I've put an array with all the fields that need translation. Based on those fields I change the "#title" variables if the "#title" variable is a string. A TranslatableMarkup "#title" doesn't need another translation:

function theme_form_contact_message_form_alter(&$form, 

  \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  // Change items

  $title_items = array(
    'subject',
    'message',
    'name',
    'mail',
    'field_amount' ,
    'field_phone',
    'field_receiver',
  );

  foreach ($title_items as $form_item) {
    if(isset($form[$form_item])) {
      $item = $form[$form_item];
      if($item['#type'] == 'container') {
        if(isset($form[$form_item]['widget'][0]['value']['#title'])) {
          if(is_string($form[$form_item]['widget'][0]['value']['#title'])) {
            $form[$form_item]['widget'][0]['value']['#title'] = $form[$form_item]['widget']['#title'] = t($form[$form_item]['widget'][0]['value']['#title']);
          }
        }
      } elseif ($form[$form_item]['#type'] != 'item') {
        // Make sure the item is not a pre-filled element.
        if(isset($item['#title']) && is_string($item['#title'])) {
          if(is_string($item['#title'])) {
            $form[$form_item]['#title'] = t($form[$form_item]['#title']);
          }
        }
      }
    }
  }
}

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.