Drupal - Getting the node object in hook_form_FORM_ID_alter

PhpStorm doesn't know as the type of form object is dynamic but it's fine.

If you want to make it happy, wrap it in a condition like:

if ($form_state->getFormObject() instanceof EntityForm) {
  ...
}

Either way, it should definitely work if you implement the correct form alter. If you don't, you should end up with a fatal error not just without a node object.

You need to share your exact code if you want a more specific answer, that's all I can tell you.


Though the correct answer has been chosen, I feel there's need to explain some things:

  • The method getFormObject() is only available on forms of type EntityForm.
  • If you're doing hook_form_node_form_alter(), you know that the form is always a node form, so you're safe calling getEntity() on the form object.
  • However, if you're doing a general hook_form_alter() hook, you might want to check for the correct $form_id or check if the form object is actually a NodeForm or an EntityForm. This will prevent PHP errors if the form is not an entity / node form.
  • As for your IDE and code completion, you can tell your IDE that the $form_object you're dealing with is a NodeForm or an EntityForm. This will make it show more appropriate hints.
/** @var \Drupal\Core\Entity\EntityForm $form_object */
$form_object = $form_state->getFormObject();
if ($form_object instanceof EntityForm) {
  $entity = $form_object->getEntity();
  // Do something with the entity.
}

For your IDE to know what the variable type is and what is available to it, you need to type hint your variables.

The type hint is the variable type added before the parameter variable name (in the example below array and FormStateInterFace).

Example:

/**
 * On form submit, do something.
 *
 * @param array
 *   The form array.
 *
 * @param \Drupal\Core\Form\FormStateInterface
 *   The form state array.
 */
function _submit_hook_name(array $form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject();
  // Do something...
}

For submit hooks, you should be using the Drupal\Core\Form\FormStateInterface type... therefore at the top of the file ensure you use that class use Drupal\Core\Form\FormStateInterface;.

Drupal coding standards states that you should type cast as well as explain the type in the docblock. The extra effort helps in future. ;)

Tags:

Forms

8