0

In the baseFieldDefinitions of Comment Entity, the subject field is set to be translatable, but I can not find such a translation in User interface translation(admin/config/regional/translate) that can make it take effect when comment on a content.

$fields['subject'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Subject'))
  ->setTranslatable(TRUE)
  ->setSetting('max_length', 64)
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    // Default comment body field has weight 20.
    'weight' => 10,
  ])
  ->setDisplayConfigurable('form', TRUE);

I now use the code to translate it in my module:

function mymodule_preprocess_form_element(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical') {
    if($variables['label']['#title'] == 'Subject') $variables['label']['#title'] = t('Subject');
  }
}

I don't think it's a good way since the translation is already defined.(And I've defined Hook_Comment_presave, this two function seems will effect each other,which I don’t want it happen either.)

Is there a better way to do that?

2
  • The label "Subject" (starting with a capital letter) is present in User interface translation out of the box, try this on a fresh install. – 4k4 Jan 26 '19 at 16:50
  • There is "Subject" item in User interface translation, but it it has no effect on a reply comment(may function for a new comment). I use phpstorm/xdebug to trace baseFieldDefinitions of comment Entity, it's not triggered at all (mymodule_preprocess_form_element is triggered). How can I found out which core function really handle this translation then? – xibinke Feb 5 '19 at 16:04
0

I finally found a solution to enforce translation of 'Subject' label in hook_form_alter which can make code more clear:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if($form_id == 'comment_comment_forum_form') {
    $form['subject']['widget'][0]['value']['#title'] = t('Subject');

  }

}

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.