April 13, 2013

Drupal 7 – how to perform an action when a node is set to published

Filed under: Web Content Pages — Tags: , — Webopius @ 8:10 am

One of the minor frustrations of Drupal is that there isn’t an out-of-the-box method for triggering an action when a node is published.

We have just completed a news website for a client built using Drupal 7. Part of the functionality they asked for was to email the client or agency who had submitted the article at the point that article was published. We were also using the excellent scheduler module for Drupal so the publication of a node could occur at any time.

To solve this, we could have used the Rules module for Drupal but as we only wanted one feature, it was easier to extend our existing custom module than add yet another module to our Drupal installation.

Solution for detecting if a Drupal node has been published

Here’s the solution we came up with. Replace ‘YOURMODULE’ below with the name of your module…

/*
 * When a node is published, notify the PR agency or client via email
 */
 
function YOURMODULE_node_presave($node){
    try {
      $notify = false;
      if (isset($node->original->status))
      {
      // It was unpublished and is now published...
      if ($node->original->status == 0 && $node->status == 1)
      {
        $notify = true;
      }
    }
    else
    {
      // It has no status before but is now published...
      $notify = true;
    }
			
    // Got to tell someone...
    if ($notify){
      // Perform the action required hereā€¦
    }
  }
  catch (Exception $e)
  {
    // Respond to an error...
  }
}
  • Tags