4

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.

6

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';
  }
}
  • This Code is working fine, except for taxonomy edit page. Will figure out that.. Thanks for your answer – Ajay Reddy Aug 5 '16 at 7:18
  • 1
    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 '16 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. – 4k4 Aug 5 '16 at 19:14
  • ->isNew() is needed for comments as well – William Turrell Oct 31 '18 at 11:59
6

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
    }
  }
}
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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