logo-radria.gif
   
Blog Download Documentation Forum Tasks Home
Blog Download Documentation Forum Tasks Home
barside-right.gif
barside-left.gif
logo-sql.gif





 

Events

Its an object to attach a user action to one or more script or method.

Like a Form submit or a link click.

So we have an Event object and we add to it EventActions that are reference to scripts or object methods. The Event Object will be added to a Form or an href link. When the user click on the links or submit the forms the Event Action are then executed.

Simple Event

Here is the most simple event and event action you can create.

Event Object:

<?php
  $e_Logout = new Event("webide.logout") ;
  $e_Logout->addParam("iduser", $iduser) ;
?>
<?php echo $e_Logout->getLink("Log Out")?>

It display an html link: Log Out

When clicked by the user it will execute the event action script called webide.logout in the events folder.

events/webide.logout

<?php
 
  $iduser = $this->getParam("iduser");
  unset($_SESSION[$iduser]);  
  $this->setDisplayNext(new Display("signed-out.php"));
 
?>

The $this object is the EventControler object that contains and process the executions of all the EventActions set by the Event Object.

Event with Objects

Since Radria 0.8 its possible to create methods in an object as Event Action and have them added to an Event.

Here is an example of a simple Like recording:

 
  $e_like = new Event("Article->eventRecordLike");
  $e_like->addParam("idarticle", 5);
 
  $e_like->addEventAction("mydb.gotoPage", 500);
  $e_like->addParam("goto", "result.php")
 
  echo $e_like->getLink("Like");

This will display a like link. When click it will execute the method: EventRecordLike on the object Article. We have added a builtin EventAction: mydb.gotoPage that creates a Display object and redirect to the page in the goto variable.

The Article Object looks like:

 
class Article extends DataObject {
  public $table = "article";
  public $primary_key = "idarticle";
 
// --- more methods
 
  public function eventRecordLike(EventControler $evctl) {
     $this->getId($evctl->idarticle);
     $this->likes++;
     $this->update();
  }
 
// ---- more methods

For you method to be able to be triggered by an Event you need to have the EventControler as parameter. We usually prefix them with event but its optional.

In this we assume we have a variable likes on the Article data (db table) so we increment it and update() the object in the Database table (storage). See the DataObject for more information on the data manipulations.

In this example you can see that the Event is calling a method on the class directly. This may have some limitation, specially if we chain multiple events.

Event with Persistent Object

In this example we will see how to trigger an Event on an Instantiated object.

Lets improve our “Like” recording:

 
  $do_article = new Article();
  $do_article->sessionPeristent("do_article", "signed-out.php", 36000);
  $_SESSION['do_article']->getId(5);
 
  //-- More code do display article 5
 
  $e_like = new Event("do_article->eventRecordLike");
  $e_like->setLevel(400);
  $e_like->addEventAction("do_article->eventSendPing", 450);
  $e_like->addEventAction("mydb.gotoPage", 500);
  $e_like->addParam("goto", "result.php")
 
  echo $e_like->getLink("Like");
}

3 things have changed from the previous example. first we instantiated an object Article with the article number 5 and made it persistent (so the object is in the session). Then we added a new event Event Action eventSendPing and set the events to different level of exections. The eventcontroler will execute the lowest level first.

We have not added the idarticle 5 to the event parameters. The object is already instantiated with →getId(5)
The levels: 400, 450, 500 are important, make sure they all have a different level. its a common error to give 2 event action the same level resulting in only one of them being executed.

Our Article class now looks like this:

/** 
 *  Article class
 *  variable in the DB: 
 *  -> idarticle
 *  -> title
 *  -> content
 *  -> likes
 *  -> author_email
 */
 
 
class Article extends DataObject {
  public $table = "article";
  public $primary_key = "idarticle";
 
// --- more methods
 
  public function eventRecordLike(EventControler $evctl) {
     $this->likes++;
     $this->update();
  }
 
  public function eventSendPing(EventControler $evctl) {
 
     mail($this->author_email, "You got a like", "On article ".$this->title." you have now ".$this->likes." likes.");
 
  }
 
// --- move methods
}

Event as Form

Often we need user input when processing the Event Actions. So here is an example on how to create a form with Events.

<?php
  $do_article = new Article();
  $do_article->sessionPeristent("do_article", "signed-out.php", 36000);
  $_SESSION['do_article']->getId(5);
 
  //-- More code do display article 5
 
  $e_rate = new Event("do_article->eventRecordRating");
  $e_rate->setLevel(400);
  $e_rate->addEventAction("do_article->eventSendPing", 450);
  $e_rate->addParam("errorpage", $_SERVER['PHP_SELF']);
  $e_rate->addEventAction("mydb.gotoPage", 500);
  $e_rate->addParam("goto", "result.php");
 
  echo $e_rate->getFormHeader();
  echo $e_rate->getFormEvent();
?>
-<input type="radio" name="article_rating" value="0">0
-<input type="radio" name="article_rating" value="1">1
-<input type="radio" name="article_rating" value="2">2
-<input type="radio" name="article_rating" value="3">3
-<input type="radio" name="article_rating" value="4">4
<?php
    echo $e_payments->getFormFooter("Save");
?>

This display 5 radio button for the user to pick how he liked the article. Here instead of using →getLink() from the other methods we used →getFormHeader(), →getFormEvent(), →getFormFooter() to generate all the elements for a form.

Our Article class now looks like

/** 
 *  Article class
 *  variable in the DB: 
 *  -> idarticle
 *  -> title
 *  -> content
 *  -> likes
 *  -> author_email
 */
 
 
class Article extends DataObject {
  public $table = "article";
  public $primary_key = "idarticle";
 
// --- more methods
 
  public function eventRecordLike(EventControler $evctl) {
     $this->likes++;
     $this->update();
  }
 
  public function eventSendPing(EventControler $evctl) {   
     $do_rating = this->getChildArticleRating();
     $total_rating = 0; $number_of_rating = 1;
     while($do_rating->next()) {
        $number_of_rating++;
        $total_rating += $do_rating->rating;
     }  
     mail($this->author_email, "You got a like or rating", "On article ".$this->title." you have now ".$this->likes." likes with an average rating of ".$total_rating/number_of_rating);
 
  }
  public function eventRecordRating(EventControler $evctl) {
      $do_rating = new ArticleRating();
      $do_rating->idarticle = $this->idarticle;
      $do_rating->date = date();
      $do_rating->rating = $evctl->article_rating;
      $do_rating->add();
  }
 
// --- move methods
}
 
/** ArticleRating class
 *  variable in the DB: 
 *  ->idarticle_rating
 *  ->idarticle
 *  ->date
 *  ->rating
 */
 
class ArticleRating extends DataObject {
  public $table = "article_rating";
  public $primary_key = "idarticle_rating";
 
}

The user selected rating is stored in the $evctl→article_rating .

Here we use the current article object to add the rating. We also have customized the eventSendPing to great an an average rating. This is just an example of event, the rating part and logic can be improved. So we added an ArticleRating object to manage and store the ratings.

Older examples

Those examples still works but they do not take advantage of the new Radria 0.8 Object Oriented features.

Event Object

Every Form and most links in PAS are Event Objects. The Event Object appears in the user interface in the form of an HTML Link or an HTML Form. It contains the list of parameters and EventActions that will be sent to the EventController for execution.

You create an Event Object on WebPages, Forms or Reports. An Event can be a link or a form. A link is used when your EventAction doesn't require user input. The form allows you to create additional fields that allow the user to enter information that is be sent to the EventAction.

The eventLogout will call the EventAction “webide.logout” and send the parameter (or variable) “userid”. The method getLink(“link lable”, “link params”) returns a correctly formatted link with a url that points to the event controller. The “link param” can be any param accepted by the <a> tag. The Event Object can call multiple EventActions and defines the order in which the EventActions will be executed.

Sample 2 : Event Object calling 2 EventActions.

<?php
  $e_register = new Event("myapp.RegisterNewUser") ;
  $e_register->setLevel(20) ;
  $e_register->addParam("username", $username) ;
  $e_register->addEventAction("myapp.checkIfUserExists", 10) ;
?>
<A href="<?php=$e_register->getUrl();?>">Register User</A>

We want to register a new user who's entered a username. But before we want to make sure that user is not already registered. We set the first event action at level 20 and the second one at 10 so its executed first.

If 2 different event actions in the same event have the same level only one of them will be executed. Make sure, when building your event that you have a unique level for each different event action.

The method getUrl() returns a correctly formatted url that can be inserted as a link or sent to the HTTP header as a new location.

When you need data input from the users you display the Event as a Form.

<?php
    $e_payments = new Event("morgage.calculateMonthlyPayments");
    $e_payments->setLevel(400);
    $e_payments->addParam("errorpage", $_SERVER['PHP_SELF']);
    $e_payments->addEventAction("mydb.gotoPage", 500);
    $e_payments->addParam("goto", "result.php");
    $e_payments->addParam("idbrooker", "45");
 
    echo $e_payments->getFormHeader();
    echo $e_payments->getFormEvent();
?>
<table>
 <tr>
   <td>Loan Amount</td>
   <td><input type="text" name="loan_amount" size="6"></td>
 </tr>
 <tr>
   <td>Interest rate</td>
   <td><input type="text" name="interest_rate" size="5"></td>
 </tr>
   <td>Number of months</td>
   <td><input type="text" name="number_of_months" size="5"></td>
 </tr>
</table>
<?php
    echo $e_payments->getFormFooter("Calculate");
?>

This event will execute the event Actions morage.calculateMonthlyPayments and then the mydb.gotoPage to redirect the user to the result.php page. Both events will receive all the parameters from addParam() methods as well as the content of the fields load_amount, interest_rate, number_of_months. Instead of using the getLink() or getUrl() methods we use the getFormHeader() to display the opening form tag, the getFormEvent() to display the Event Actions and the parameters, the getFormFooter to display the submit button and close the form tag.

Event Action

The event actions are pieces of code that are executed by the EventController when called by an Event Object.

We suggest you name your events starting with the name of your application or package. This keeps the events organized when your application size grows. For example: mydb.updateRecord or myapps.calculatePayroll. The EventAction is executed inside the EventController.

Here is a sample of a simple event action : faq.recordView

     $idfaq = $this->getParam("idfaq");
     if ($idfaq>0) {
        $q_incView = new sqlQuery($this->getDbCon()) ;
        $q_incView->query("update faq set views=views+1 where idfaq=".$idfaq);
        $q_incView->free();
     }

This event records each time a user clicks on an FAQ question. It uses the $this→getParam() method from the EventController to grab a parameter from the event that triggered it. Additionally it gets the database connection used by the EventController with : $this→getDbCon(). This event action assumes that another event action will set the next display. If none of the event actions set the $this→setDisplayNext(displayobject) then the user will get an infinite redirection error from the EventController. This is an example of how to set a display next :

    $disp = new Display("index.php") ;
    $disp->addParam("message", "Welcome Back to the home page") ;
    $this->setDisplayNext($disp) ;

We suggest that all messages used in the events to be stored in a string on top of the event action script.

To enable errors and logs you can use the event controller log methods.

$this->setLogRun(true); 
$this->setLog("\n This is a log message");

See the BaseObject for more information on Errors and Logs.

Redirection & Output

In general after the Event was triggered by the user a redirection to a web page is done. But sometime, like for ajax request, it make more sens to just output the result.

The default eventcontroler.php redirects and requires a display object.

Redirect

That Display object is passed to the EventControler with the method:

$disp = new Display("pagename.php");
$disp->addParam("message", "eventaction has been executed");
$this->setDisplayNext($disp).

The EventController will redirect after the EventActions of the Event are executed.

Output

Advanced Event Features

Session Persistence Events

You can make your event data live through a session. Session events are an important part of PAS applications. The are the most used way to store information to be reused in forms, reports, saved querys and web pages. For example, you have 3 pages. You want your event to be executed after page one but you want the data stored in that event to be available until the user arrives on page 3, no matter what is executed in between.

<?php 
  $e_mclient = new Event("myapp.moreclient") ; 
  $e_mclient->addParam("idclient", $idclient) ; 
  $e_mclient->addParam("name", $name) ; 
  $e_mclient->requestSave("moreClientInfoForm", "formpage5.php") ; 
?>
  <a href="<?php=$e_mclient->getUrl()?>">Edit Client information</A>

In this example we have an event object that calls the “myapp.moreclient” event action. It uses the method requestSave to store this event into an object called “moreClientInfoForm”; this object will be available until the user reaches the page “formpage5.php”. On the page formpage2.php the event will release all of its params as global variables and the “moreClientInfoForm” object will be set to be destroyed on the next page. Until the user has reached the formpage5.php you can access and modify the the parameters of that event in Events or Web Pages using:

<?php
    $idclient = $moreClientInfoForm->getParam("idclient");
    $lastname =  "Doe";
    $moreClientInfoForm->addParam(“lastname”, $lastname);
?>

The values of parameters in session events can also be retrieved in Saved queries and as Default values of fields in forms in the registry. (See Parameters in Saved Query chapter and function call for default value in Registry chapter for more information). Get the param of a session event in a SQL statement of a Saved query:

SELECT * FROM category_product AS cp LEFT JOIN products AS p ON (cp.idproducts=p.idproducts)  WHERE cp.idclient='[getParam:moreClientInfoForm:iclient]'

Get Param of a session event as a default form value in a registry:

<rfield name="idclient">
    <rdata type="label">idclient</rdata>
    <rdata type="readonly">1</rdata>
    <rdata type="default">[getparam;moreClientInfoForm;idclient]</rdata>
    <rdata type="fieldtype">strFBFieldTypeInt</rdata>
  </rfield>

Note the “;” instead of “:”, this is specific to the registry function calls.

Secured Events

By default event objects are in secure mode.

The “Secured” is too much, but it helps by hiding the parameters of links and forms in the session.

This means that none of the parameters you set in your event object are visible in the web page. Instead those events are stored in the Session and will be recalled when the Event Object will be triggered by the user. To turn off the secure event mode uncomment the line:

  //define("RADRIA_EVENT_SECURE", false);

in your config.php file.

<?php
    $e_sel_lic = new Event("reseller.select_licenses");
    $e_sel_lic->setLevel(1100);
    $e_sel_lic->setSecure(true);
    $e_sel_lic->addParam("errorpage", $_SERVER['PHP_SELF']);
    $e_sel_lic->addEvent("mydb.gotoPage", 500);
    $e_sel_lic->addParam("goto", "thankyou.php");
 
    $e_sel_lic->addParam("idreseller", "345", "no_secure_hidden");
 
    $e_sel_lic->addParamToSave("simple_users");
 
    $e_sel_lic->requestSave("eSelLic", "reseller_panel.php");
 
    echo $e_sel_lic->getFormHeader();
    echo $e_sel_lic->getFormEvent();
?>
 
<input type="text" name="simple_users" size="5" maxsize="20" value="10">
 
<?php
    echo $e_sel_lic->getFormFooter("Submit");
?>

You can individually set an event insecure or secure using the setSecure(bool) method. You can display individual parameters using the “no_secure_hidden” as the third parameter of the addParam() method. “no_secure_hidden” is usefull to display selected parameters for users to view or to be used by Javascript Scripts.

If you want to store a param in the session event but its value is set later in the script you need to declare it using addParamToSave before the requestSave() method call.

Event Controller

This is an object inside a php file. Usually it is the page: eventcontroler.php. that comes with the default application structure. You can create your own event controller by creating an instance of the EventController Object inside a PHP page.

The EventController looks for events triggered by the user. Each time a user clicks on a link or submits a form that was created with an Event Object, a list of Event Actions and parameters will be sent to the Event Controller.

The event controller will then order the event actions and create a secure environment with the parameters and global variables. Once the environment is set, and referrer verified, it includes the requested Event Action files from the pas/events or ./events directory. After all of the events have been executed it will check if a display object as been set and redirect the user to that display.

The event controller provides the event actions with all of the session variables and get/post/cookie variables. They can be accessed within an event action using the following syntax :

 $firstname = $this->getParam("firstname");
 $username = $this->getSession("username");

The event controller also allows the different event actions to share information. This is done by sharing an Array in the event controller. Event Actions can access that Array using the $this→setParam() and $this→getParam() methods.

Built in event action

The event actions are pieces of code that are executed by the Event Controller when called by an EventObject.

Below you will find a list of all the event actions in pas/events/. The EventAction can use all of the methods of the EventController object that was called. mydb.addParamToDisplayNext : will add all of the parameters of your event to the display so they will be displayed in the url after the event is executed.

Following is a short description of the Event actions. For a detailed description of the built-in Event Actions see Appendix D. Event actions to manage records in a database :

mydb.addRecord: uses the fields array and table parameters to add a record to a table.

mydb.manageRecord: used by the recordevent to manage records in a table.

mydb.tableorder: Used by the reportTable object to manage the variables for ordering and next - previous tabs.

mydb.updateRecord: Update a record in a table using the primary key, fields array and table name.

Event actions to validate and format values from forms : The Event actions below are called by the Registry. When a form is displayed the registry checks each field for when events will need to be executed on the server side to validate that field.

mydb.checkEmail: Checks if the domain of the email address exists

mydb.checkRequired: Checks if a field set as require contains something

mydb.checkUsernamePassword: Checks that the two passwords are identical

mydb.formatDateField: Convert a date to a unix time stamp

mydb.formatDateSQLField: Convert a date to an sql data format

mydb.formatPictureField: Manage the file upload

mydb.formatTimeField: Format a time field

Event actions to manipulate variables and page redirection:

mydb.addVariablesToSession : Save a variable to the session

mydb.callDisplay : Call a default page to display a form or a report

mydb.delVariablesFromSession : Remove a variable from the session

mydb.fieldsToArray : Convert all of the fields : fields_fieldname to fields[fieldname]

mydb.gotoPage: Create a display event and use the goto parameter to redirect to the page defined by goto

mydb.loadParamsFromSession: Load the paramaters of an event when events are in secure mode

mydb.registerGlobalEvent: Used to register an event in the session

mydb.SaveForm: Totally depreciated

mydb.stripslashes.Fields: Check the PHP addslashes policy and stripslashes if needed

Event actions to synchronize databases :

mydb.synchronise.db.Data: Synchronize the data using backupsync.data.sql

mydb.synchronise.db.Structure: Synchronize the structure using backupsync.struct.sql

 
core/events.txt · Last modified: 2011/03/05 17:12 by admin
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki