5

I want to know whether form is add/edit in hook_form_alter. In Drupal 7 we can get all these in hook_form_alter.

I tried like this in D7:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check pages(s) , don't use $_GET.
    if (strpos($form['#action'], '/add/') !== FALSE) {
      $page = 'add';
    }
    if (strpos($form['#action'], '/edit') !== FALSE) {
      $page = 'edit';
    }
}

Here I am getting add/edit in D7. Whereas in D8 I am not getting any it in $form['#actions']. And i don't want to use $_GET. Is there any way to check add/edit page in hook_form_alter.

4 Answers 4

9

In D8 you can get the operation of an entity form with the form object:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_state->getFormObject()->getOperation() == 'edit') {
    $page = 'edit';
  }
}
4
  • This Code is working fine, except for taxonomy edit page. Will figure out that.. Thanks for your answer
    – Ajay Reddy
    Aug 5, 2016 at 7:18
  • 4
    names of the form operations are not standardized, not all use add/edit, taxonomy terms afaik only use default. If you want to know if it is a new or existing entity, you can get that information with getEntity()->isNew()
    – Berdir
    Aug 5, 2016 at 18:51
  • Thanks @Berdir, I don't change the answer, because Maouna has already the code in his answer, so we keep both alternatives, +1 from me.
    – 4uk4
    Aug 5, 2016 at 19:14
  • ->isNew() is needed for comments as well Oct 31, 2018 at 11:59
10

If you want to check for being on 'add' form, it is also possible to check that the entity is new, i.e.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_state->getFormObject() instanceof EntityForm) {
    $entity = $form_state->getFormObject()->getEntity()
    if ($entity->isNew()) {
      //your code
    }
  }
}
1

AFAIK you should always check the form_id and not using $form['#action'].

function MODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    // your code
  }
}

I'm not sure of the node edit/add form ids, you can use dpm($form_id) if you devel module or just use print_r($form_id) to find the form_id.

0

You can also tell by the $form_id which is already present in the hook_form_alter.

$form_ids for nodes usually look like this:

  • node add = node_NODE_TYPE_form
  • node edit = node_NODE_TYPE_edit_form

So just use conditional logic for what you need and this is faster then using other methods listed in this.

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.