function content_translation_form_alter

Same name and namespace in other branches
  1. 9 core/modules/content_translation/content_translation.module \content_translation_form_alter()
  2. 8.9.x core/modules/content_translation/content_translation.module \content_translation_form_alter()
  3. 10 core/modules/content_translation/content_translation.module \content_translation_form_alter()

Implements hook_form_alter().

File

core/modules/content_translation/content_translation.module, line 386

Code

function content_translation_form_alter(array &$form, FormStateInterface $form_state) {
    $form_object = $form_state->getFormObject();
    if (!$form_object instanceof ContentEntityFormInterface) {
        return;
    }
    $entity = $form_object->getEntity();
    $op = $form_object->getOperation();
    // Let the content translation handler alter the content entity form. This can
    // be the 'add' or 'edit' form. It also tries a 'default' form in case neither
    // of the aforementioned forms are defined.
    if ($entity instanceof ContentEntityInterface && $entity->isTranslatable() && count($entity->getTranslationLanguages()) > 1 && in_array($op, [
        'edit',
        'add',
        'default',
    ], TRUE)) {
        $controller = \Drupal::entityTypeManager()->getHandler($entity->getEntityTypeId(), 'translation');
        $controller->entityFormAlter($form, $form_state, $entity);
        // @todo Move the following lines to the code generating the property form
        //   elements once we have an official #multilingual FAPI key.
        $translations = $entity->getTranslationLanguages();
        $form_langcode = $form_object->getFormLangcode($form_state);
        // Handle fields shared between translations when there is at least one
        // translation available or a new one is being created.
        if (!$entity->isNew() && (!isset($translations[$form_langcode]) || count($translations) > 1)) {
            foreach ($entity->getFieldDefinitions() as $field_name => $definition) {
                // Allow the widget to define if it should be treated as multilingual
                // by respecting an already set #multilingual key.
                if (isset($form[$field_name]) && !isset($form[$field_name]['#multilingual'])) {
                    $form[$field_name]['#multilingual'] = $definition->isTranslatable();
                }
            }
        }
        // The footer region, if defined, may contain multilingual widgets so we
        // need to always display it.
        if (isset($form['footer'])) {
            $form['footer']['#multilingual'] = TRUE;
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.