Event Handlers are methods within your Part's code that handle GET and POST requests directed to that part. They allow your part to react to user events or actions on page refresh. Part Event Handlers are nearly the exact same as
CodeBehind Event Handlers.
To create an Event Handler in your code, simply create a method named "event
Name" in your part. If the variable eID is set in GET or POST (where ID is the id of your part) a matching Event Handler will be called. For example, if your part's ID was 12, setting the variable e12=MyEvent would cause the Event Handler "function EventMyEvent()" to be triggered on page load.
Note that Event Handlers are processed before View Handlers, allowing you to process an event and provide feedback when generating the content to view.
Here's a simple example of an Event Handler used for a mailing list part:
partTime.php
-----------------
<?php
class partMailingList extends part {
//the view that should be shown by default
var $defaultView = "Signup";
/* View Handler - Shows Signup Form */
function viewSignup(){
return $this->fetch("signup.tmpl.php");
}
/* View Handler - Shows Welcome message */
function viewWelcome(){
return $this->fetch("welcome.tmpl.php");
}
/* Event Handler - Accepts Signups */
function eventSignup(){
$email = util::getData("email");
//insert into database, etc.
//...
}
} ?>
signup.tmpl.php
-----------------
Join our mailing list!
<br />
<form action="<?=$PHP_SELF?>?v<?=$id?>=welcome" method="post" >
<input type="hidden" name="e<?=$id?>" value="login" />
Email <input type="text" name="email"><input type="submit" value="Join Now!">
</form>
date.tmpl.php
-----------------
Welcome! You are now signed up for the mailing list.
This could would look something like:
And after the user clicks Signup:
In this example, as soon as the user clicks Signup, the event "EventSignup" will be triggered, then the view handler Welcome will be called.
To trigger the event handler, a hidden form element was used with the name "e<?=$id?>"
<input type="hidden" name="e<?=$id?>" value="login" />
$id is a special template variable that contains the id your of your part. Notice that the action of the form also specifies the desired view handler to show after the form is submitted.
Although not shown here, you could have also put the event handler trigger directly into the action of the form, such as: action="<?=$PHP_SELF?>?v<?=$id?>=welcome&e<?=$id?>=signup"
EventHandlers can return results, noting their success or failure. The result that they set can be automattically access from your view handlers as well as in variables passed to your template.
For example, lets say you wanted to show a error message if the user already signed up in your mailing list, telling the user that they don't need to sign up again.
Event results are the exact same for parts as they are in CodeBehind pages. For details on having your Event Handlers return results, please see
Event Handler Results in the CodeBehind documentation.