0

I wanted to add the "status" field to an entity that already exists but is not mine, i.e. I cannot edit the php class where this entity is defined.

With the following code I add the field in database, but I don't have access to the "isPublished()" or "setPublished()" methods, because for that the entity should implement the "EntityPublishedTrait" trait.

/**
 * Implements hook_install().
 */
function project_groups_access_install($is_syncing) {
  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $entity_type               = $definition_update_manager->getEntityType('my_entity');

  // Bail out early if a field named 'status' is already installed.
  if ($definition_update_manager->getFieldStorageDefinition('status', 'my_entity')) {
    return t('The publishing status field has <strong>not</strong> been added to my_entity.');
  }

  // Add the 'published' entity key to the my_entity entity type.
  $entity_keys              = $entity_type->getKeys();
  $entity_keys['published'] = 'status';
  $entity_type->set('entity_keys', $entity_keys);
  $definition_update_manager->updateEntityType($entity_type);

  // Add the status field.
  $status = BaseFieldDefinition::create('boolean')
    ->setLabel(t('Published'))
    ->setDescription(t('A boolean indicating the published state.'))
    ->setRevisionable(TRUE)
    ->setTranslatable(TRUE)
    ->setDefaultValue(TRUE)
    ->setDisplayOptions('form', [
      'type'     => 'boolean_checkbox',
      'settings' => [
        'display_label' => TRUE,
        'default_value' => TRUE,
      ],
      'weight'   => 120,
    ])
    ->setDisplayConfigurable('form', TRUE);

  $status->setInitialValue(TRUE);
  $definition_update_manager->installFieldStorageDefinition('status', 'group', 'group', $status);

  return t('The published field has been added to groups.');
}

My question is: how can I make that entity implement the EntityPublishedTrait class to have access to those methods?

2
  • 1
    If you can't edit the php class you have to extend it in your own module. See drupal.stackexchange.com/a/199395/47547
    – 4uk4
    Apr 30, 2021 at 7:58
  • Okay, I understand. I had tried it but with the hook "hook_entity_type_alter". Now it looks better, thank you very much!
    – Javier Rey
    Apr 30, 2021 at 9:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.