create_and_translate-8.x-1.x-dev/create_and_translate.module
create_and_translate.module
<?php
/**
* @file
* The create and translate module file.
*/
use Drupal\Core\Entity\ContentEntityFormInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* @file
* Creates a button on node form that allows to create a node and translate it.
*/
/**
* Implements hook_form_alter().
*/
function create_and_translate_form_alter(&$form, FormStateInterface $form_state) {
$current_path = \Drupal::service('path.current')->getPath();
$url = Url::fromUserInput($current_path);
if (!$url->isRouted()) {
// We only handy routed URLs.
return;
}
$route_name = $url->getRouteName();
// We only handle these routes:
$route_names = [
'node.add',
'entity.node.edit_form',
'entity.node.content_translation_add',
'entity.taxonomy_term.add_form',
'entity.taxonomy_term.edit_form',
];
if (isset($route_name) && in_array($route_name, $route_names)) {
$form_object = $form_state->getFormObject();
if (!($form_object instanceof ContentEntityFormInterface)) {
// We only handle ContentEntityFormInterface.
return;
}
$entity = $form_object->getEntity();
if ($entity instanceof ContentEntityInterface && $entity->isTranslatable()) {
$form['actions']['create_and_translate'] = $form['actions']['submit'];
$form['actions']['create_and_translate']['#value'] = t('Save and translate');
$form['actions']['create_and_translate']['#submit'][] = 'create_and_translate_submit';
}
}
}
/**
* Submit callback to set the redirect.
*
* @param array $form
* The form object.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form_state object.
*/
function create_and_translate_submit(array &$form, FormStateInterface $form_state) {
$trigger = $form_state->getTriggeringElement();
if (isset($trigger['#id']) && $trigger['#id'] == 'edit-create-and-translate') {
if ($form_state->getValue('nid')) {
$nid = $form_state->getValue('nid');
$form_state->setRedirectUrl(Url::fromUri('internal:/node/' . $nid . '/translations'));
}
if ($form_state->getValue('tid')) {
$tid = $form_state->getValue('tid');
$form_state->setRedirectUrl(Url::fromUri('internal:/taxonomy/term/' . $tid . '/translations'));
}
}
}
