1

I have a content type named film.

Original language of a film is FR.

Let say I have 2 translatable fields on a total of 10 fields in film.

I am using this code to alter the add/edit form of film:

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'node_film_edit_form': // edit
    case 'node_film_form': // Add
      alter_film($form, $form_state, $form_id);
      break;
    ...
  }
}

In the alter_film function, I would like to add a custom submit only if the edited form is for French (Original language)

function alter_film(&$form, FormStateInterface $form_state, $form_id) {
  ...
  //HERE IS MY PROBLEM:
  //HOW TO KNOW IF IT IS TRANSLATED FILM
  if (! $is_translated_film){  
    $form['actions']['submit']['#submit'][] = "submit_film";
  }
  ...
}

The question is: what check could be made to know which form is edited: the original language form (10 fields) or the translated language form (2 fields)

As a side question, I don't understand why there is no difference in the dpm($form); output if I execute one in the French form and the other one in the English form. I am asking this, because in /admin/config/regional/content-language, I have checked Hide non translatable fields on translation forms. And I would expect to have 10 fields in the french form array and only 2 (translatable) fields in the translated form array.

In the translated form, only 2 fields are displayed as expected, but I am wondering why the 10 fields are included in the array.... I ask that just out of curiosity

1
  • 1
    All fields are included because it is decided later when the form is processed and rendered which fields are displayed. You can use the same tactics for your custom submit. Attach it in any case and then check when the custom submit is called whether you have an original or translated entity in $form_state (with the code from your own answer).
    – 4uk4
    Mar 29, 2018 at 16:15

1 Answer 1

1

I could answer myself for the first question. The following line will give me the edited language.

$form_state->getFormObject()->getEntity()->get('langcode')->value;

But, maybe, the following is better:

$is_original_language = $form_state->getFormObject()->getEntity()->get('default_langcode')->value;

It is better, because original language could vary. In this case on the Add/Edit Node, Add new translation and Edit translations the return value can be parsed directly. Add Node or add new translation returns a Boolean while the edit forms return an int (1/0).

1
  • This was a life saver for me just now. Cheers. :)
    – Gold
    Aug 8, 2019 at 2:57

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.