Drupal 8: Getting an Entity ID from $form_state

Published September 22, 2018

I ran across a situation the other day that had me a bit frustrated for a few minutes until Ted Bowman nudged me in the right direction. I was working on a small custom module for a client - one that involved altering a node form using hook_form_alter() - where I needed to know the value of the node ID being edited.

I had spent more than a few minutes digging into both the $form array and $form_state object desperately looking for the node ID, to no avail. I had pinged Ted on Slack about something else and I asked him if he knew how to find what I was looking for - he told me "maybe the form object is better".

That's all I needed to get unstuck, a few minutes and a Google search or two later, I stumbled upon the following:

$form_state->getformObject()->getEntity()->id()

Not only would this return the node id, it will actually return the id for any type of entity.

Just to be safe, I went ahead and wrapped it in a if-statement to make sure that the form object returned is actually an entity form:

if ($form_state->getFormObject() instanceOf EntityFormInterface) {
  $nid = $form_state->getformObject()->getEntity()->id();
}

Comments

I am using the hook_form_alter() to alter an exposed view filter. The method getEntity() is not found on the $form_state object. Is an exposed filter's $form_state/$form object any different from any regular form?

Submitted by Emad (not verified) on Sun, 03/31/2019 - 09:34

Author comment

@emad - the reason it isn't working for you is because a Views exposed filter form isn't an entity form, so there's no entity to get the ID of...

Submitted by ultimike on Sun, 03/31/2019 - 10:46

Sign up to receive email notifications of whenever we publish a new blog post or quicktip!

Name
CAPTCHA