Drupal 8: Getting an Entity ID from $form_state

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();
}

Add new comment

The content of this field is kept private and will not be shown publicly.