3

hook_add_form() gets $entity_type and $entity as parameters, but hook_form_alter() does not have any of those parameters.

How do I get the entity type and the entity object in hook_form_alter()in Drupal 7?

2 Answers 2

8

I think that it should be possible to do something like this.

if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
  $entity = $form_state->getFormObject()->getEntity();
  $entity_type = $entity->bundle();
}   

UPDATE: In Drupal 7 it should be done like this:

$node = $form['#entity_type']; // E.g this could be, (#node, #user etc.)

Take a look at this site, drupal discussion.

10
  • You may also want an if like in this answer to make sure you're operating on an entity form before making these calls.
    – sonfd
    Commented Apr 30, 2018 at 12:54
  • Oh sorry guys I am working with Drupal 7 and forgot to mention in hurry :(. Any way similar functions work with D7? Thanks a lot!
    – Lub
    Commented Apr 30, 2018 at 13:15
  • Try to take a look at the updated answer.
    – user72672
    Commented Apr 30, 2018 at 13:23
  • Yes this will work! Thank you a lot!!! Saved me a ton of time.
    – Lub
    Commented Apr 30, 2018 at 13:24
  • 1
    This isn't right - nodes are just one type of entity, you'll never find any other type of entity in $form['node']
    – Clive
    Commented Apr 30, 2018 at 13:26
1

Entity types each implemented their own form in D7, there wasn't a generic one. You're at the mercy of what the author of each bit of code decided at the time.

For example you can find consistency with some of the core entity types:

  • node -> $form['#node']
  • user -> $form['#user']
  • comment -> $form['#comment']

But not all the way through:

  • taxonomy_term -> $form['#term']

You might find it easier to target the specific types of entity you're interested in, determine what the correct array key is for each, and store them in a map somewhere for later access.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.