Question

In Drupal 8/9, when you create a new term, the default status message is:

Created new term %term.

%term contains the term name, which is linked to the term page.

I want to override this and remove the link (I want to show the term name, but I do not want to link the term name to the term page).

I thought I could do this in a custom submit handler:

function MYMODULE_term_create_form_submit(array &$form, FormStateInterface &$form_state) {
  \Drupal::messenger()->deleteByType('status');
  \Drupal::messenger()->addMessage(t('The group @group-name has been added.', ['@group-name' => NULL]));
}

However, I don't know how to get the term's name from $form. I searched the $form object with kint() and I could not find the form name.

Then I looked at core, which does this:

  public function save(array $form, FormStateInterface $form_state) {
    $term = $this->entity;

    $result = $term->save();

    $edit_link = $term->toLink($this->t('Edit'), 'edit-form')->toString();
    $view_link = $term->toLink()->toString();
    switch ($result) {
      case SAVED_NEW:
        $this->messenger()->addStatus($this->t('Created new term %term.', ['%term' => $view_link]));
        $this->logger('taxonomy')->notice('Created new term %term.', ['%term' => $term->getName(), 'link' => $edit_link]);
        break;

But, I don't have access to the term object in the submit handler.

What's the simplest way to do this without doing a quick-and-dirty patch to core?

Was it helpful?

Solution

In a submit handler you can find the form object in $form_state:

$term = $form_state->getFormObject()->getEntity();
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top