Community

hook_node_prepare calls when form is saved. lots of hooks and none trigger exactly when node edit page loads.

I want to trigger a function when an edit page is loading - basically to set a message.

function mymod_node_prepare($node){
if($node->type == "mytype" && arg(2) == "edit"){
drupal_set_message("Triggered");
}
}
Unfortunately, this and every other hook I've tried brute forcing into submission either don't work on the edit page or trigger again when I save.

Is there any hook I can use that won't double up on me or is there some conditional I've never heard of that can tell whether it's loading the edit form or saving it.

I've tried:

hook_node_load
hook_node_view
hook_node_prepare
hook_form

And more :/

Comments

Form hooks:

hook_form_alter() or hook_form_FORM_ID_alter() (yourmodule_form_node_form_alter()).

If you need the node object, you can find it in $form['#node'].

Nope, it calls when

Nope, it calls when submitting the form too.

0x539

Let me check. This might have

Let me check. This might have something to do with how drupal_set_message() works.

Specifically, if you just

Specifically, if you just echo something then the submit page (*/edit) will reload and the echo won't show at all, you need dsm or file writing or something to keep the message "logged".

Actually submitting the form to the form is probably why it's getting called even if it never actually renders the form (Or maybe it does but doesn't echo it until it's too late and the location header has been sent)

Edit: Off work, back later

0x539

I confirmed

I confirmed that:

  • drupal_set_message() should not be blamed (my apologies to that piece of code),
  • node forms indeed get built twice.

Here's a workaround:

<?php
/**
* Implements hook_form_FORM_ID_alter().
*/
function ourmodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  if (empty(
$form_state['input']) && isset($form['#node']->nid)) {
   
drupal_set_message(t('Triggered.'));
  }
}
?>

Taking advantage of the fact $form_state['input'] is an empty array on the initial build;

$form['#node']->nid is used to tell apart node/add from node/edit - could as well use arg(2) there.

Awesome! I'll be using that,

Awesome! I'll be using that, thanks!

0x539

Turns out that that would

Turns out that that would make it not show on preview pages or edit pages where the user input the wrong info. Instead I'll use hook_node_presave and drupal_get_messages then loop through them and pick the incorrect one out.

0x539