Drupal - Accéder à l'entité créée / modifiée depuis un Form Alter

Voici comment accéder à l'entité (Node par exemple) sur les formulaire de création / modification de contenu via le hook_form_alter

   #[Hook('form_alter')]
  public function formAlter(&$form, FormStateInterface $form_state, $form_id): void {
    if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
      $entity = $form_state->getFormObject()->getEntity();
      if ($entity instanceof \Drupal\node\NodeInterface) { // Il peut-être utile de faire un test sur le type d'entitée
        $entity_type = $entity->bundle();
      }
    }
  }

À noter, j'utilise ici la nouvelle syntaxe des hooks introduite dans drupal 11 (plus d'informations). avec l'ancienne syntaxe ça donnerai ça :

function mon_module_form_alter(&$form, FormStateInterface $form_state, $form_id): void {
  if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
    $entity = $form_state->getFormObject()->getEntity();
    if ($entity instanceof \Drupal\node\NodeInterface) { // Il peut-être utile de faire un test sur le type d'entitée
      $entity_type = $entity->bundle();
    }
  }
}

 

Contenus en rapport

Ajouter un commentaire

Ne sera pas publié
CAPTCHA
Désolé, pour ça, mais c'est le seul moyen pour éviter le spam...