Skip to content

Instantly share code, notes, and snippets.

@vever001
Created February 23, 2024 12:17
Show Gist options
  • Save vever001/0bfb1216600cb56341e3735701745af8 to your computer and use it in GitHub Desktop.
Save vever001/0bfb1216600cb56341e3735701745af8 to your computer and use it in GitHub Desktop.
<?php
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Implements hook_entity_update().
*/
function my_module_entity_presave(EntityInterface $entity) {
/** @var \Drupal\content_moderation\ModerationInformationInterface $moderation_info */
$moderation_info = Drupal::service('content_moderation.moderation_information');
// Abort if this doesn't apply to this entity.
if (!isset($entity->original)
|| !$moderation_info->isModeratedEntity($entity)
|| $entity->isSyncing()
|| $entity->get('moderation_state')->isEmpty()) {
return;
}
// Flag all translations as affected upon moderation state change.
$moderation_state_old = $entity->original->get('moderation_state')->value;
$moderation_state_new = $entity->get('moderation_state')->value;
if ($moderation_state_new !== $moderation_state_old) {
$translation_languages = $entity->getTranslationLanguages();
foreach ($translation_languages as $langcode => $language) {
$translation = $entity->getTranslation($langcode);
$translation->setRevisionTranslationAffected(TRUE);
}
}
}
/**
* Implements hook_entity_base_field_info_alter().
*/
function my_module_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
/** @var \Drupal\Core\Field\FieldDefinitionInterface[] $fields */
// Force moderation_state as untranslatable for content_moderation_state.
if (isset($fields['moderation_state']) && $entity_type->id() === 'content_moderation_state') {
$fields['moderation_state']->setTranslatable(FALSE);
}
// Force moderation_state and published (if applicable) fields as
// untranslatable for all moderated entities.
/** @var \Drupal\content_moderation\ModerationInformationInterface $moderation_info */
$moderation_info = Drupal::service('content_moderation.moderation_information');
if (isset($fields['moderation_state']) && $moderation_info->isModeratedEntityType($entity_type)) {
$fields['moderation_state']->setTranslatable(FALSE);
$published_field = $entity_type->getKey('published');
if ($published_field && isset($fields[$published_field])) {
$fields[$published_field]->setTranslatable(FALSE);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment