I have a content type "Articles", this is a multi-language site, by default the content is created in English, and then translated into Spanish. On new article in English, I set a title and a term for the "Category terms" field, this field is an "Entity Reference", and I'm using "Entity Browser" to show terms from a view (they are a lot of terms), when I create a translation from English to Spanish I need to remove any term related to "Category terms" field. I have tried a couple of ways, but this is not working for this field.
Here is the hook code that I'm using.
<?php
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Form state object double check.
if (is_object($form_state) && method_exists($form_state, 'getStorage')) {
$form_storage = $form_state->getStorage();
// Temporal condition to avoid unexpected results while developing
if ($form_id == 'node_articles_form') {
// Check if form is a translation.
if (isset($form_storage['content_translation'])) {
// Hard coded test to override title - This works.
$form['title']['widget'][0]['value']['#default_value'] = 'Forced title text translation';
// Hard coded test to override Meta Search Terms - This doesn't work. Is not applyed
$form['field_category_terms']['widget']['entity_browser']['#default_value'] = [];
// Removing completely the field - This is not a solution, only for test.
// unset($form['field_category_terms']);
// Removing data from "Callback Object"
$build_info = $form_state->getBuildInfo();
// Getting the entity
$entity = $build_info['callback_object']->getEntity();
// Removing terms from entity
$entity->field_category_terms = [];
// Setting the entity
$build_info['callback_object']->setEntity($entity);
// setting a modified callback object to the $form_state
$form_state->setBuildInfo($build_info);
// Removing target_id default value.
unset($form['field_category_terms']['widget']['target_id']['#default_value']);
}
}
}
}