Monday, June 15, 2009

Don't use afterXXX triggers for redirects

I have noticed a number of developers doing this so I thought I would make a note on it.  If you want to redirect the user to a custom page after inserting a new record, do NOT place your redirect inside your beforeXXX or afterXXX triggers.   These triggers are called every time a record is saved/inserted/updated which may occur multiple times per request, and in many different contexts - not just the 'new' action.

Here is an example.  Suppose we want to direct a user to a custom thankyou.html page after they insert a new record into the submissions table.  You might be tempted to do something like this:
function afterInsert(&$record){
    header("Location: thankyou.html");
    exit;
}
This is wrong, so don't do it.
The correct way is to use the after_action_new trigger which is only called after the 'new' action has successfully inserted a new record - just before it redirects to the success page.  This trigger gives you the opportunity to redirect the user to whereever you like:
function after_action_new($params){
    $record =& $params['record'];  // get the record that was just inserted.
    header("Location: thankyou.html");
}

 

No comments:

Post a Comment