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

Drave Robber’s picture

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'].

jnvsor’s picture

Nope, it calls when submitting the form too.

Drave Robber’s picture

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

jnvsor’s picture

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

Drave Robber’s picture

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:

/**
 * 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.

jnvsor’s picture

Awesome! I'll be using that, thanks!

jnvsor’s picture

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.