Buy Now
Sign in

FAQ search

Event switcher

Details
Published: Saturday, 22 March 2014 14:28

Two CFv4 actions: the Custom ServerSide Validation action and the Custom Event Switcher (and the Event Switcher [GH] action - have been replaced by the Event Switcher action in CFv5.

In each case, the idea is simple, to add some custom PHP code which routes the form processing depending on the string value returned by the code.

By default the Event Switcher has two events 'success' and 'fail', defined by the string 'success,fail' in the Events box of the action. 

Until PHP is added neither of these events will run: as an example. to run the 'success' event every time the form is submitted, we could add this in the Code box:

<?php
return "success";
?>

This isn't very useful - in practice the code is more likely to be like this

<?php
if ( $form->data['aaa'] == 'xxx' ) {
  return 'success';
} else {
  return 'fail';
}
?>

The names 'success' and 'fail' are not always useful and you can change them by adding a list of one or more events in the Events box, then clicking the 'Load Events' button. Note that there should be no spaces between the event names and that the names should, like element names, start with a letter and use only a-z,A-Z,0-9 and underscore e.g. do_this, do_that,do_the_other

Most of the time a 'success' event is not needed as on success events can be placed normally after the Event Switcher. 

Here is an example of sending an email only if the user has checked an 'email_me' box. The Events box has email_me in it, and the Email action is dragged into the email_me event box in the Event Switcher. The code is like this:

<?php
if ( !empty($form->data['email_me']) ) {
  return 'email_me';
}
?>

Serverside validation

To use the Event Switcher for custom serverside validation we need only a 'fail' event with an Evetn Loop action dragged into the event box. The code is similar except that we don't want to return the 'fail' string until all the checks are complete and we want to set error messages.

<?php
$valid = true;
if ( empty($form->data['name']) ) {
  $form->errors['xxx'] = "Please enter your name";
  $valid = false;
} elseif ( $form->data['age'] < 18 ) {
  $form->errors['age'] = 'You are too young';
  $valid = false;
} elseif (. . . ) {
  . . .
}
if ( !$valid ) {
  return 'fail';
}
?>

To check for spam you could use similar code and on fail redirect the user instead of re-loading the form.