drupal-code-generator icon indicating copy to clipboard operation
drupal-code-generator copied to clipboard

Generated content entity forms will break if Content Moderation is enabled

Open kevinquillen opened this issue 9 months ago • 1 comments

At the root of this is this core issue: https://www.drupal.org/project/drupal/issues/2509360

In short, the generated form throws an exception incorrectly in some cases when a custom entity is hooked up for Content Moderation as SAVED_UPDATED is not always returned (thus the issue).

Instead, it is likely preferable to generate something closer to what core does in this case:

final class MyCustomContentEntityForm extends ContentEntityForm {

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $result = parent::save($form, $form_state);

    $message_args = ['%label' => $this->entity->toLink()->toString()];
    $logger_args = [
      '%label' => $this->entity->label(),
      'link' => $this->entity->toLink($this->t('View'))->toString(),
    ];

    switch ($result) {
      case SAVED_NEW:
        $this->messenger()->addStatus($this->t('New myentity %label has been created.', $message_args));
        $this->logger('mymodule')->notice('New myentity %label has been created.', $logger_args);
        break;

      default:
        $this->messenger()->addStatus($this->t('The myentity %label has been updated.', $message_args));
        $this->logger('mymodule')->notice('The myentity %label has been updated.', $logger_args);
        break;

    }

    $form_state->setRedirectUrl($this->entity->toUrl());
    return $result;
  }

}

This was an otherwise very hard bug to trace back to core.

kevinquillen avatar Feb 26 '25 14:02 kevinquillen

Related: #199

kevinquillen avatar Feb 26 '25 14:02 kevinquillen