Server Events and Client Scripts

You can implement your own business logic by writing your own server events and client scipts. Your code is stored in the project so you can migrate your project to other templates or future versions easily. This feature reduces the need of template customization and create maximum possibilities for you to customize and create more advanced features for your projects.

After loading the database, the database objects (tables, views, custom views and reports) will be shown in the left pane (the database pane). Click on any table to go to the Field Setup Page and then select the Code tab (which contains Server Events, Client Scripts and Custom Templates).

Note: For simplicity, we use "table" in the following description to refer to any of database object in the project. A database object can be either a table, a view, a custom view or a report.


The treeview shows the available server events and client scripts that you can add to your project:

Server Events Server-side PHP procedures

Global

The events are applicable to all PHP pages

Table-Specific

The set of events are table-specific, the events are applicable to the selected table only

Other

The events are applicable to some common pages in the project only
Client Scripts Client-side JavaScript

Global

The JavaScript are included in all pages with header and footer

Table-Specific

The JavaScript are table-specific, they are included to pages for the selected table only

Other

The JavaScript are included in some common pages in the project only

To add your custom scripts to the server events or client scripts, select an item in the treeview, then enter your code in the editor.

The editor supports Find and Replace. Press Ctrl-F to open the Find dialog and press Ctrl-H to open the Replace dialog.

You can click the [Clear] button to discard the existing code and reset template code for the server event or client script.

 

Code Repository

PHPMaker provides a Code Repository for easy reuse of your code across projects and sharing with other users. Click the [Code Repository] button to open it, categorized reusable code will be displayed:

You can add the code to the editor by clicking the [Add to Editor] button, or by double-clicking the item, or simply drag the item to the editor. The reusable code is stored in XML files which reside in s subfolder name "code" under the installation folder. The format of the XML files is simple, there are 3 parts:

  1. description - description of the reusable code
  2. code - code to be inserted to editor
  3. globalcode - common code to be inserted to Global Code (see below), this code will only be inserted once into the project. For example , if your code is used several times in your project and your code calls a helper function, it is unnecessary to include the helper function several times. In this case you put your helper function in the globalcode section, then the function will only be included one time.

There are a few example files in the "code" folder, you can copy and modify for your own code and then save them under the "code" folder for reuse.

 

Server Events

In general, server events are fired in the following order:

  • Page_Loading (Global function)
  • Page_Load (Page/Table class method)
  • <Page>.RecordSet_* / Row_* (Page/Table class method)
  • Page_Unload (Page/Table class method)
  • Page_Unloaded (Global function)

Notes:

  1. From v9, the page class inherit from the table class, so you can use $this in the page class methods to access table class members. For backward compatibility, the table object is kept and it is an alias of the page object, so you can also use $this in the table class methods to access page class members.

  2. The Page_Unload and Page_Unloaded are server side events to be fired every time the page is accessed and before the HTML is outputted to the browser on the client side. They are NOT events to be fired before you leave the page and reload the page or go to another page. For example, if you submit a form in the page, usually it submits to the page itself, you are actually reloading the page, all server events will be fired again. For another example, if you click a hyperlink which links to another page, the page on the server side is not even accessed again and no server events for the page will be fired.

  3. If a server event is a global function, there is NO "$this" in the function context. If you want to refer to the current page object, you can use the global function CurrentPage().

  4. In the following table, the <fieldname> in code, e.g. in $this-><fieldname>-><property> or x_<fieldname>, represents the field variable name. In general, i the field name is alphanumeric, field variable name is same as the field name. Otherwise, spaces are replaced by underscores, and other non alphanumeric characters are replaced by their hexadecimal string representation of their unicode value. If the variable is a reserved word or starts with a digit, it will be prepended with an underscore. If you are not sure, drag a field from the database pane to the editor instead of typing the field variable name. However, note that if the field name is quoted, e.g. as a key in $rs['<fieldname>'], <fieldname> is the actual field name as in the database, not the field variable name.

  5. Server events are functions or class methods, if you need to use global variables in the events, note the PHP variable scope, you must use the global keyword or $GLOBALS.

Available server events are:

Global -> All Pages

Page_Head

The code you entered in this event will be placed in the header.php before closing the <head> section. You can use this event to can add your code in head section. Note: This is a global function.

Example

Include custom JavaScript and CSS styesheet.

ew_AddClientScript("xxx.js"); // Add JavaScript
ew_AddStylesheet("xxx.css"); // Add CSS stylesheet

Database_Connecting

This event will be called by all PHP pages before connecting to the database. Note: This is a global function.

If MySQL/PostgreSQL, the argument is an array with the following keys: host, port, user, pass, db. If Access/MSSQL, the argument is the connection string for ADO. You can use this event to change the connection string (e.g. changing connection info with server, or even connect to other databases).

Example 1

// MySQL/PostgreSQL
function Database_Connecting(&$info) {
    
//var_dump($info);
    // assume the scripts are generated with connection info for local PC
    if (ew_CurrentUserIP() <> "127.0.0.1") {
// not connecting to local PC
        // connect to the production database

        $info["host"] = "localhost";
        $info["user"] = "xxx";
        $info["pass"] = "yyy";
        $info["db"] = "production_db";
    }
}

Example 2

It is possible to use single login and common Dynamic User Levels for multiple projects provided that ALL projects use the same project name and same Advanced Security tables (i.e. User Table, User Level Table and User Level Permission Table). If all projects uses the same database and same Advanced Security tables, then the latter condition is autifulfilled. However, if the projects use different databases, you can use this event to change the connection info so the user can get the Dynamic User Levels from the common Advanced Security tables correctly during login, e.g.

// MySQL/PostgreSQL
function Database_Connecting(&$info) {
    
//var_dump($info);
    if (preg_match('/login|userpriv/', CurrentPageID()) {
// login.php or userpriv.php
        // connect to the common database with the common Advanced Security tables
        $info["host"] = "localhost";
        $info["user"] = "xxx";
        $info["pass"] = "yyy";
        $info["db"] = "common_db";
    }
}

Page_Loading

This event will be called by all PHP pages at the beginning of the page. If the pages involves database connection, it will be called after connecting to the database and before the Page_Load event. Note: This is a global function, NOT page class member.

Page_Unloaded

This event will be called by all PHP pages at the end of the page. If the pages involves database connection, it will be called before closing database connection and after the Page_Unload event. Note: This is a global function, NOT page class member.

Global Code

Code to be included in all PHP pages. This may contain your constants, variables and functions.

User_CustomValidate

For use with security. (See Security Settings) This event is fired before default user validation. You can use this event to validate the user yourself. The arguments are the user name and password the user entered. Return TRUE if the username and password pass your custom validation. Note: This event is a security class member.

Note: From v9, default validation will continue after this event is fired. If you return TRUE, the user will always pass the default validation and get the User ID and User Level, if any. If you return FALSE, the default validation proceeds as normal. If you use Advanced Security, you still need the user table to store user information such as User ID and User Level, although the password field value can be empty or any value if you return TRUE.

Example 1

Login user by Windows user name.

// Note: This event is a Security class member, so you can refer to other members of the Security class directly
function User_CustomValidate(&$usr, &$pwd) {
    // e.g. Simple Windows authentication
    if (ew_ServerVar("LOGON_USER") <> "") {
        $usr = ew_ServerVar("LOGON_USER");
        return TRUE;
    }    
}

Example 2

Login user by LDAP. (The following example code can be found in Code Repository.)

// Note: This event is a Security class member, so you can refer to other members of the Security class directly
function User_CustomValidate(&$usr, &$pwd) {
    // e.g. LDAP authentication example for User_CustomValidate server event
    if (!function_exists("ldap_connect"))
        die("LDAP extension not installed.");
    $ldapconn = ldap_connect("ldap.example.com", 389) or die("Could not connect to LDAP server."); // Note: Replace the host name and port
    if ($ldapconn && ldap_bind($ldapconn, $usr, $pwd)) {
        $this->setCurrentUserName($usr); // Set the current user name
        return TRUE;
    }
    
}

User_Validated

For use with security. (See Security Settings) This event is fired after successful user login. The user info is passed to the event as an array (see note), you can get more info of the user and use it as you need. Note: This event is a security class member.

Notes:

  1. This event is not fired for the hard-coded administrator.

  2. In previous version, the argument $rs was an object, so you needed to get a field value by $rs->fields('<fieldname>'). For consistency with other events, the argument has been changed to array so you can get a field value by $rs['<fieldname>'].

Example

Add current user's country to session variable

// Note: This event is a Security class member, so you can refer to other members of the Security class directly
function User_Validated(&$rs) {
    $_SESSION["UserCountry"] = $rs['Country'];
}

UserLevel_Loaded

For use with User Level security. (See Security Settings) This event is fired after successful user login and after the User Level settings are loaded. It is possible to do actions such as changing or adding User Level permissions. Note: This event is a security class member.

Example

Change the permissions of an User Level for a table

// Note: This event is a Security class member, so you can refer to other members of the Security class directly
function UserLevel_Loaded() {
    $this->DeleteUserPermission("Sales", "orders", EW_ALLOW_ADD);
    $this->AddUserPermission("Sales", "orders", EW_ALLOW_EDIT);
}

MenuItem_Adding

This event is fired for custom menu items before it is added to the menu. The menu item info is passed to the event as an instance of the cMenuItem object, refer to phpfn*.php for members of the object. Return FALSE if you don't want to show the menu item. If you return TRUE, the menu item will be added to the menu, but it does not mean that it will be always displayed. A menu item will be displayed only if its Allowed property is TRUE. When the menu item is passed to this event, the Allowed property is set based on the User Level Security of the project, you can however change it by setting $Item->Allowed as TRUE or FALSE as needed. Note: This is a global function.

Example

Only show a menu item after the user has logged in

function MenuItem_Adding(&$Item) {
    //var_dump($Item);
    // Return False if menu item not allowed

    if ($Item->Text == "Download") {
        return Security()->IsLoggedIn();
    } else {
        return TRUE;
    }
}

Menu_Rendering

This event is fired before the menu is rendered. You can manipulate the menu items in this event. The argument is the menu object. (See Menu Object below.) Note: This is a global function.

Example 1

Add an additional menu item to the menu for logged in users only.

function Menu_Rendering(&$Menu) {
    
if ($Menu->IsRoot) { // Root menu
        $Menu->AddMenuItem(10000, "MyMenuText", "MyPage.php", -1, "", IsLoggedIn());
    }
}

Example 2

Remove all the default menu items and use your own menu items.

function Menu_Rendering(&$Menu) {
    
if ($Menu->IsRoot) { // Root menu
        $Menu->Clear();
        $Menu->AddMenuItem(1, "MyMenuText1", "MyPage1.php", -1);
        $Menu->AddMenuItem(2, "MyMenuText2", "MyPage2.php", -1);

    }
}

TablePermission_Loading

For use with User Level security. (See Security Settings) This event is fired before the user permission for the table of the current page is loaded. It is possible to do actions such as changing or adding more User Level permissions to the current user. Note: This event is a security class member.

Note: This is an event fired for the current table only. If you change the permissions of the other tables in this event, there will be no effect. Use the UserLevel_Loaded event if you need to change permissions of other tables.

Example

Grant another User Level to the user and let the user have permissions of more than one User Level for the current table.

// Note: This event is a Security class member, so you can refer to other members of the Security class directly
function TablePermission_Loading() {
    if (CurrentUserName() == "nancy")
        $this->AddUserLevel("Manager");
}

TablePermission_Loaded

For use with User Level security. (See Security Settings) This event is fired after the user permission for the table of the current page is loaded. It is possible to to change the permission by using the setCanXXX methods of the Security class. Note: This event is a security class member.

Note: This is an event fired for the current table only. If you change the permissions of the other tables in this event, there will be no effect. Use the UserLevel_Loaded event if you need to change permissions of other tables.

Example

Grant more permissions to the user and let the user have more permissions than his/her User Level allows for the current table.

// Note: This event is a Security class member, so you can refer to other members of the Security class directly
function TablePermission_Loaded() {
    if (CurrentUserName() == "nancy")
        $this->setCanEdit(TRUE);
}

UserID_Loading

For use with User ID security. (See Security Settings) This event is fired after successful user login and before loading the User ID and its child User IDs of the current user. These User IDs determine which records the current user can access. It is possible to do actions such as changing the User ID of the current user so the user can access records that he/she can access by its original User ID. Note: This event is a security class member.

Example

Change the user's User ID to his parent user's user ID and let the user access more records (accessible by the parent user).

// Note: This event is a Security class member, so you can refer to other members of the Security class directly
function UserID_Loading() {
    if (CurrentParentUserID() <> "")
        $this->CurrentUserID = CurrentParentUserID();
}

UserID_Loaded

For use with User ID security. (See Security Settings) This event is fired after loading the User ID and its child User IDs of the current user. These User IDs determine which records the current user can access. It is possible to do actions such as adding or deleting the loaded User IDs for the current user so the user can access more or less records that he/she can access by its originally loaded User IDs. Note: This event is a security class member.

Example

Add more User IDs to the user and let the user access more records

// Note: This event is a Security class member, so you can refer to other members of the Security class directly
function UserID_Loaded() {
    if (CurrentUserName() == "nancy")
        $this->AddUserID($this->GetUserIDByUserName("janet"));
}

User_PasswordExpired

This event will be called if the user password is already expired. User information is passed to the event as argument, you can get user information by $rs["<fieldname>"] where <fieldname> is a field name of the user table. Note: This event is a security class member.
Table-Specific -> Common (Note: These events are members of the page class)

Recordset_Selecting

This event will be called before selecting records. The argument of the event is the filter (part of the WHERE clause of the SQL) for selecting records, you can customize the filter to change the records to be selected.

Example

Add your own filter. Note that the $filter may have value, append your filter to it, not replace it.

function Recordset_Selecting(&$filter) {
    ew_AddFilter($filter, "(Field1 = 1234)"); // Add your own filter expression    
}

Recordset_Selected

This event will be called after selecting records. Note: The argument is the recordset object (not array).

Recordset_SearchValidated

This event will be called after the Form_CustomValidate event and the search criteria is assigned to the table/field objects. You can modify the search criteria in this event.

This event is a member of the table class. There is no arguments for this event. To change the Quick Search criteria, change the BasicSearchKeyword and BasicSearchType property of the table object. To change the Advanced Search criteria, change the AdvancedSearch property (which is an object of the cAdvancedSearch class) of the field object.

Example

function Recordset_SearchValidated() {
    $this->MyField1->AdvancedSearch->SearchValue = "your search criteria"; // Search value
}

Recordset_Searching

This event will be called before the search criteria is saved for the session. The argument of the event is the part of WHERE clause built from the Quick/Extended Quick/Advanced search criteria. You can modify the WHERE clause in this event.

Row_Deleting

This event will be called before deleting a record. The argument of the event is the record to be deleted as an array.

Row_Deleted

This event will be called after deleting a record. The argument of the event is the record deleted as an array.

Example

Delete detail records from the detail table after the master record is deleted.

function Row_Deleted(&$rs) {
    // Assume ForeignKeyField is of integer type
    ew_Execute("DELETE * FROM DetailTable WHERE ForeignKeyField=" . $rs["PrimaryKeyField"]);
}

Row_Inserting

This event will be called before inserting a record. The arguments of the event are the arrays of the old (if copying record) and new record to be inserted. You can change the values in the $rsnew.

Example

Make sure a field value is valid.

function Row_Inserting(&$rsold, &$rsnew) {
    if ($rsnew["Percentage"] > 100)
        $rsnew["Percentage"] = 100;
    // To cancel, set return value to False
    return TRUE;
}

Row_Inserted

This event will be called after inserting a record. The arguments of the event are the arrays of the old (if copying record) and new record just inserted.

Example

Get the ID (autoincrement field) of the just inserted record

function Row_Inserted(&$rsold, &$rsnew) {
    $this->setSuccessMessage("Record Inserted. The ID of the new record is " . $rsnew["ID"]);    
}

Row_Rendering

This event will be called before rendering (applying the View/Edit Tag settings) a record.

Row_Rendered

This event will be called after rendering a record.

This is an extremely useful event for conditional formatting, you can do a lot of things with this event, such as changing font color, font styles, row background color, cell background color, etc. by changing the table or field class properties in the event according to field values.

The table class has a RowAttrs property which is an associative array of HTML attributes for the table row. The field class has CellAttrs, ViewAttrs and EditAttrs for the table cell, View Tag and Edit Tag of the field respectively. The keys of these arrays must be valid HTML attributes for the HTML tag, always use lowercase for the keys. The attribute values will be outputted as double quoted attributes, so if you have double quotes in your values, try to use single quotes if possible, or use "&quot;".

To view the properties of the field class for development or debugging, you can use the PHP's var_dump function in the server event, e.g.

var_dump($this->RowAttrs);
var_dump($this->Trademark);
var_dump($this->Trademark->CellAttrs);
var_dump($this->Trademark->EditAttrs);
var_dump($this->Trademark->ViewAttrs);

Example

Click "Cars" node on the database panel, select [Server Events/Client Scripts], and click [Table Specific] - > [Common] - > [Row_Rendered] server event. The default Row_Rendered event code is shown. Change as follow:

function Row_Rendered() {
    // Change the row color in List page
    if ($this->Trademark->ViewValue == "BMW") {
        $this->RowAttrs["style"] = "color: red; background-color: #ccffcc";
    }

    // Change the cell color
    if ($this->Cyl->CurrentValue == 4) {
        $this->Cyl->CellAttrs["style"] = "background-color: #ffcccc";
    } elseif ($this->Cyl->CurrentValue == 6) {
        $this->Cyl->CellAttrs["style"] = "background-color: #ffcc99";
    } elseif ($this->Cyl->CurrentValue == 8) {
        $this->Cyl->CellAttrs["style"] = "background-color: #ffccff";
    }

    // Change text style
    if ($this->Category->CurrentValue == "SPORTS") {
        $this->Category->ViewAttrs["style"] = "color: #00cc00; font-weight: bold; background-color: #ffff99";
    }
}

 

Row_Selecting

This event will be called before selecting a record. The argument of the event is the filter (part of the WHERE clause of the SQL) for selecting the record, you can customize the filter to change the record to be selected.

Row_Selected

This event will be called after selecting a record. The argument is the record selected as an array.

Row_UpdateConflict

This event will be called if conflicts is found before updating a record (if Check Conflicts is enabled, see Table Setup). The arguments of the event are the old record (as array) and new record (as array) to be updated.

You can use this event to resolve the conflicts according to your own criteria. If you want to ignore conflicts or you have resolved the conflicts in the event (by setting new values to the argument rsnew) and want to continue update, return FALSE. Otherwise, return TRUE. By default the event returns TRUE.

Row_Updating

This event will be called before updating a record. The arguments of the event are the arrays of the old and new record to be updated.

Example

Make sure a field value is not changed

function Row_Updating(&$rsold, &$rsnew) {
    if ($rsnew["Qty"] < $rsold["Qty"]) {
        // To cancel, set return value to False
        $this->CancelMessage = "The new quantity must be larger than the old quantity.";
        return FALSE;
    } else {         
        return TRUE;
    }
}

Row_Updated

This event will be called after updating a record. The arguments of the event are the arrays of the old and new record updated.

Email_Sending

This event is fired before the email notification is sent. You can customize the email content using this event. Email_Sending event has the following parameters:

Email - the email object instance which contain all the information about the email to be sent. It is an instance of the cEmail class, refer to phpfn*.php for members of the object.

Args - an array which contains additional information.

If Add, the new record in the format of array can be access by $Args["rsnew"]. If Copy, the old record in the format of array can be access by $Args["rsold"]. If Edit/Update, the old data of the records in the format of array can be access by $Args["rsold"], the new data of the records in the format of array can be access by $Args["rsnew"]. You can get a field value by, e.g.

$rsnew = $Args["rsnew"];
$MyValue = $rsnew["MyField"];

or

$MyValue = $Args["rsnew"]["MyField"];

Return FALSE in the event if you want to cancel the email sending.

If Grid-Add/Edit, there are more than one records, the arguments are array of array.

Example

Assume there is an email field in the record, and you want to change the recipient to the value of that field.

function Email_Sending(&$Email, &$Args) {
    //var_dump($Email);
    //var_dump($Args);
    //exit();
    if (CurrentPageID() == "add") { // If Add page
        $Email->Recipient = $Args["rsnew"]["MyEmailField"]; // Change recipient to a field value in the new record
        $Email->Subject = "My New Subject"; // Change subject
        $Email->Content .= "\nAdded by " . CurrentUserName(); // Append additional content
    }
    return TRUE;
}


Table-Specific -> Add/Copy page

Page_Load

This event will be called after connecting to the database.

Page_Unload

This event will be called before closing database connection.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. The argument is the URL to be redirected to.

By default after inserting a record user is redirected back to the List page. You can change that by using Return Page (see Table Setup). However, If you want to change by code, you can also use this event.

Message_Showing

This event is fired before the message stored in the session variable is shown.

The first argument $msg is the message to be shown, the second argument $type is the type of the message, possible values of type are: "" (empty string), "success", "failure", and "warning".

Example

Replace an error message by custom message

if ($type == "failure") { // If a failure/error message
    if (strpos($msg, "some standard message") !== FALSE)) // The original message contains some keywords you want to replace
        $msg = "My custom message";
}

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. In general, the form data can be accessed by $this-><Field>->FormValue (e.g. $this->HP->FormValue). Alternatively, you can get all the form values in an array first, e.g.

$rs = $this->GetFieldValues("FormValue");

An argument $CustomError is passed to the event, you can add your error message and return FALSE if the form values do not pass your validation.

Example

Make sure an integer field value meet a certain requirement

function Form_CustomValidate(&$CustomError) {
    $rs = $this->GetFieldValues("FormValue"); // Get the form values as array
    if (intval($rs["Qty"]) % 10 <> 0) {
        // Return error message in $CustomError
        $CustomError = "Order quantity must be multiples of 10.";
        return FALSE;
    } else {         
        return TRUE;
    }    
}

Table-Specific -> Delete Page

Page_Load

This event will be called after connecting to the database.

Page_Unload

This event will be called before closing database connection.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

By default after deleting record(s) user is redirected back to the List page. You can change that using this event.

Table-Specific -> Edit Page

Page_Load

This event will be called after connecting to the database.

Page_Unload

This event will be called before closing database connection.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

By default after updating a record user is redirected back to the List page. You can change that by using Return Page (see Table Setup). However, If you want to change by code, you can use this event.

Table-Specific -> List Page

Page_Load

This event will be called after connecting to the database.

Example

From v8, the export links are stored as a cListOptions object (also see ListOptions_Load and ListOptions_Rendered event below), you can manipulate the links in the same way. The defaut names of the options are:

  • print
  • html
  • excel
  • word
  • xml
  • csv
  • pdf
  • email

Note that the names are case-sensitive. They are in lowercase.

This example hides the export to PDF link in List page:

function Page_Load() {
    $item = @$this->ExportOptions->Items["pdf"];
    if ($item)   
        $item->Visible = FALSE;  
}

Page_Unload

This event will be called before closing database connection.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. See description of Form_CustomValidate for Add/Copy page above.

ListOptions_Load

This event will be called before the main table is rendered. Use this event to modify the non data columns of the main table (i.e. the links and the checkbox for each record). You can modify these columns or add your own columns using this event. You can get a column by name using $this->ListOptions->Item["name"], the following predefined names are reserved, do not use them for your own columns. Note that the names are case-sensitive. They are in lowercase except for the detail table names.

  • checkbox
  • view
  • copy
  • delete
  • edit
  • details - for use with PreviewRow extension (for registered users) only, or
  • detail_<DetailTable> - NOT for use with PreviewRow extension (for registered users)

Example 1

Add a new column.

function ListOptions_Load() {
    $item = &$this->ListOptions->Add("new");
    $item->Header = "MyCaption"; // Set the column header (for List page)
    $item->OnLeft = TRUE; // Link on left
    $item->MoveTo(0); // Move the column to the specified index
}

Example 2

Hide a column.

function ListOptions_Load() {
    $this->ListOptions->Items["new"]->Visible = FALSE;     
}

ListOptions_Rendered

This event will be called before a record is rendered. Use this event to modify content of the non data columns for the record. To access field object of the current row, you can use $this-><Field>-><Property> (e.g. $this->HP->CurrentValue).

Note: Do NOT try to show/hide a column dynamically by setting the Visible property of the list option in this event. If the column is visible in one row but invisible in another, the table will be malformed. If you want to hide the content dynamically, you can set the Body property as empty string.

Example 1

Set the content of the new column dynamically based on a field value.

function ListOptions_Rendered() {
    if ($this->MyField->CurrentValue == "xxx") {
        $this->ListOptions->Items["new"]->Body = "yyy";
    } else {
        $this->ListOptions->Items["new"]->Body = "";
    }
}

Example 2

Merge options into the one and hide the others. The first argument of the Merge method is a regular expression pattern to match the option names that you want to merge, e.g. '/view|copy|delete|edit/'. The first matched option will remain visible, the others will be hidden. The second argument is the separator between the options. The return value is the merged (the first matched) otpion. The following example merge the columns for detail table links into one.

function ListOptions_Rendered() {
    $item = &$this->ListOptions->Merge('/^detail_/', '<br>');
}

 

Table-Specific -> Multi-Update Page

Page_Load

This event will be called after connecting to the database.

Page_Unload

This event will be called before closing database connection.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

By default after updating records user is redirected back to the List page. You can change that by using this event.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. See description of Form_CustomValidate for Add/Copy page above.

Table-Specific -> Report Page

Page_Load

This event will be called after connecting to the database.

Page_Unload

This event will be called before closing database connection.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Table-Specific -> Search Page

Page_Load

This event will be called after connecting to the database.

Page_Unload

This event will be called before closing database connection.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

By default user is redirected to the List page after the search criteria is processed. You can change that by using this event.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. See description of Form_CustomValidate for Add/Copy page above.

Table-Specific -> View Page

Page_Load

This event will be called after connecting to the database.

Page_Unload

This event will be called before closing database connection.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Table-Specific -> Preview Page

Page_Load

This event will be called after connecting to the database.

Page_Unload

This event will be called before closing database connection.

Page_DataRendering

This event will be called before the page content is outputted. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called after the page content is outputted. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Other -> Login Page

Page_Load

This event will be called at the beginning of the page.

Page_Unload

This event will be called at the end of the page.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

By default user is redirected to the default page (e.g. index.php) after successful login. You can change that by using this event.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

User_LoggingIn

This event will be called before validating the username and password.

User_LoggedIn

This event will be called after the user login.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. Inspect the HTML source of the page in your browser to view the form element names.

An argument $CustomError is passed to the event, you can add your error message and return FALSE if the form values do not pass your validation.

User_LoginError

This event will be called if the user fail to login.
Other -> Logout Page

Page_Load

This event will be called at the beginning of the page.

Page_Unload

This event will be called at the end of the page.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

By default user is redirected to the default page (e.g. index.php) after successful login. You can change that by using this event.

User_LoggingOut

This event will be called before user logout.

User_LoggedOut

This event will be called after user logout.

Other -> Registration Page

Page_Load

This event will be called at the beginning of the page.

Page_Unload

This event will be called at the end of the page.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

By default user is redirected to the default page (e.g. index.php) after successful login. You can change that by using this event.

Email_Sending

This event is fired before the email notification is sent. You can customize the email content using this event. Email_Sending event has the following parameters:

Email - the email object instance which contain all the information about the email to be sent. It is an instance of the cEmail class, refer to phpfn*.php for members of the object.

Args - an array which contains additional information. For registration page, the new record in the data type of a recordset can be accessed by $Args["rs"].

Return FALSE in the event if you want to cancel the email sending.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. See description of Form_CustomValidate for Add/Copy page above.

User_Registered

This event is fired after successful registration of a new user. Argument is a recordset of the new record in the user table.

User_Activated

This event is fired after activating a new user (if user activation is required, see Security Settings). Argument is a recordset of the new record in the user table.

Other -> Change Password Page

Page_Load

This event will be called at the beginning of the page.

Page_Unload

This event will be called at the end of the page.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

By default user is redirected to the default page (e.g. index.php) after successful login. You can change that by using this event.

Email_Sending

This event is fired before the email notification is sent. You can customize the email content using this event. Email_Sending event has the following parameters:

Email - the email object instance which contain all the information about the email to be sent. It is an instance of the cEmail class, refer to phpfn*.php for members of the object.

Args - an array containing additional information. For Change Password page, the old data of the records in the data type of recordset can be accessed by $Args["rsold"], the new data of the records in the data type of recordset can be accessed by $Args["rsnew"].

Return FALSE in the event if you want to cancel the email sending.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. Inspect the HTML source of the page in your browser to view the form element names.

An argument $CustomError is passed to the event, you can add your error message and return FALSE if the form values do not pass your validation.

Other -> Password Recovery Page

Page_Load

This event will be called at the beginning of the page.

Page_Unload

This event will be called at the end of the page.

Page_DataRendering

This event will be called after the header.php is included. You can use this event to add content at the top of page content.

Page_DataRendered

This event will be called before the footer.php is included. You can use this event to add content at the bottom of page content.

Page_Redirecting

This event will be called before redirecting to other page. Event argument is the URL to be redirected to.

By default user is redirected to the login page after successful login. You can change that by using this event.

Email_Sending

This event is fired before the email notification is sent. You can customize the email content using this event. Email_Sending event has the following parameters:

Email - the email object instance which contain all the information about the email to be sent. It is an instance of the cEmail class, refer to phpfn*.php for members of the object.

Args - an array containing additional information. For Password Recovery Page, the old data of the records in the data type of recordset can be accessed by $Args["rs"].

Return FALSE in the event if you want to cancel the email sending.

Message_Showing

This event is fired before the message stored in the session variable is shown. You can use this event to change the message which is passed to the event as argument.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. Inspect the HTML source of the page in your browser to view the form element names.

An argument $CustomError is passed to the event, you can add your error message and return FALSE if the form values do not pass your validation.

User_RecoverPassword

This event is fired after the password is recovered. Argument is a recordset of the user's record in the user table.

 

Client Scripts

In general, each page has two blocks of JavaScript:

Client Script - the first block of JavaScript to be included at the beginning of the page, you can put your JavaScript variables and functions there. The View Tag (for display) and Edit Tag (for input) of the fields supports Custom Attributes (See Field Setup) so you can add your own attributes to work with your own JavaScript included here.

Startup Script - the second block of JavaScript to be included at the end of the page, you can put code here to "start up" your JavaScript.

Global -> Pages with header/footer

Client Script

The script will be placed in the header and therefore included in all pages with header.

Note: This event is NOT related to the No header/footer setting in the Generate form (see Generate Settings). Even if No header/footer is enabled, this event will also be fired.

Startup Script

The script will be placed in the footer and therefore included in all pages with footer. This is a very useful event which is fired fired for all pages with footer, you can almost do everything by changing the document DOM of those pages.

Note: This event is NOT related to the No header/footer setting in the Generate form (see Generate Settings). Even if No header/footer is enabled, this event will also be fired.

Global Code

JavaScript code to be included in all pages with header. This may contain your global constants, variables and functions.
Table-Specific -> Add/Copy page

Client Script

The script will be placed after the header. This may contain your JavaScript variables and functions for the page. You can also use this event to subscribe a custom event.

Example

Subscribe the "RenderTemplate" custom event for Custom Templates.

ewRenderTemplateEvent.subscribe(function(type, args) {
    //alert(ewJson.stringify(args[0])); // Uncomment to view the arguments
    args[0].enabled = false; // Disable the Custom Template
    ew_ShowTemplates(args[0].template.substr(4)); // Show the templates with the specified class name
});

Startup Script

The script will be placed before the footer. This is a very useful event which you can almost do everything by changing the document DOM.

Example 1

Add onchange event to a field (textbox)

ewEvent.on("x_Field1", "change", function(e) {
    var form = this.form; // Get the HTML form element
    var el2 = form.elements["x_Field2"]; // Get the form element for field #2
    el2.value = "xxx"; // Set value to field #2 (assume el2 is a textbox)
});

Example 2

Add onclick event to a field (checkbox)

ewEvent.on("x_MyField[]", "click", function(e) {
    var form = this.form; // Get the HTML form element
    if (this.checked) { // Checkbox is checked
        // Do something
    } else { // Not checked
        // Do something else
    }
});

In general, the HTML form element for the field is named as "x_FieldName", inspect the element in your browser to check the actual name. In the event handler, "this" is the form element which fired the event. ewEvent is a shortcut to YAHOO.util.Event, read YUI 2: Event Utility for more information on how to use it.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. The HTML form object can be accessed by the parameter fobj. In general, the HTML form element for the field can be referred to as fobj.elements["x_FieldName"].

Return false if the form values do not pass your validation.

Note: This function is a member of the JavaScript page class.

Example

Make sure an integer field value meet a certain requirement

function(fobj) { // DO NOT CHANGE THIS LINE!
    var qty = parseInt(fobj.elements["x_Qty"].value); // Assume x_Qty is a textbox
    if (qty % 10 != 0)         
        
return ew_OnError(this, fobj.elements["x_Qty"], "Order quantity must be multiples of 10."); // Return false if invalid
    return true;
}

Table-Specific -> Delete Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.
Table-Specific -> Edit Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. The form object can be accessed by the parameter fobj. Return false if the form values do not pass your validation.

Table-Specific -> List Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. The form object can be accessed by the parameter fobj. In general, the HTML form element for the field can be referred to as fobj.elements["x_FieldName"].

Note: The form element names are different in Inline-Add/Copy/Edit or Grid-Add/Edit mode of List page. They are named as "x0_FieldName" in Inline-Add/Copy/Edit mode, and as "x1_FieldName", "x2_FieldName", etc. in Grid-Add/Edit since there are multiple rows. Inspect the elements in your browser to check the actual form element names. For simplicity, the form elements of the current row will also be added to the fobj.row property (an array of the HTML form elements) before this event is fired. So you can always use fobj.row["x_FieldName"] to get the HTML form element of the field of the current row in the List page. For other pages, you should use fobj.elements["x_FieldName"] directly.

Return false if the form values do not pass your validation.

Table-Specific -> Multi-Update Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. The form object can be accessed by the parameter fobj. Return false if the form values do not pass your validation.

Table-Specific -> Report Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.
Table-Specific -> Search Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. The form object can be accessed by the parameter fobj. Return false if the form values do not pass your validation.

Table-Specific -> View Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.
Other -> Login Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. The form object can be accessed by the parameter fobj. Return false if the form values do not pass your validation.

Other -> Registration Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. The form object can be accessed by the parameter fobj. Return false if the form values do not pass your validation.

Other -> Change Password Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. The form object can be accessed by the parameter fobj. Return false if the form values do not pass your validation.

Other -> Password Recovery Page

Client Script

The script will be placed after the header.

Startup Script

The script will be placed before the footer.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation. The form object can be accessed by the parameter fobj. Return false if the form values do not pass your validation.

Note: It is recommended that you develop your server event and client scripts in the generated script so you can edit and test it immediately. When you finish your custom script, copy it to PHPMaker custom script editor and save it.

 

Objects in PHPMaker Generated Code

The following objects are available in the generated code and you can use them in the Server Events to add more power to the code. The most important objects are:

Page Object
The Page object is generated for most pages. You can access the object properties using the -> notation (e.g. CurrentPage()->PageID). The page class inherits from the table class generated for each table. The methods and properties of the page class varies with page, for the complete list of methods and properties, please refer to the generated page class in the generated scripts and the class "c<Table>" (e.g. cCars) in the generated file "<Table>info.php".

Field Object
A <Field> object is generated for each field in a table. For example, the "Trademark" object is generated for the "Trademark" field in the "Cars" table. You can access the object properties using the -> notation (e.g. CurrentPage()->Trademark->CurrentValue). For the complete list of methods and properties, please refer to the class "cField" in the generated file "phpfn*.php".

Security Object
The Security object is used to store the current Advanced Security settings. Please refer to the class "cAdvancedSecurity" in the generated file "phpfn*.php" for the complete list of methods and properties.

Email Object
The Email object contains the required information of the email to be sent, the instance of the object will be passed to the Email_Sending events as argument and let you modify the email. Please refer to the class "cEmail" in the generated file "phpfn*.php" for the complete list of methods and properties.

Menu Object
The Menu object contains all information of a menu, the instance of the menu will be passed to the Menu_Rendering events as argument and let you work with the menu. Please refer to the class "cMenu" in the generated file "ewshared*.php" for the complete list of methods and properties.

MenuItem Object
The MenuItem object contains all information of the menu item, the instance of the menu item will be passed to the MenuItem_Adding events as argument and let you work with the menu item. Please refer to the class "cMenuItem" in the generated file "ewshared*.php" for the complete list of methods and properties.

ListOpions Object
The ListOptions object contains all information of the non data columns in the main table of the List page. Please refer to the class "cListOptions" in the generated file "phpfn*.php" for the complete list of methods and properties.

Language Object
The language Object lets you retrieve a phrase of the active language during runtime. The phrase can be retrieved in the generated scripts using methods such as Phrase, TablePhrase and FieldPhrase. Please refer to the class "cLanguage" in the generated file "ewshared*.php" for the complete list of methods and properties.

There are a few other objects in the generated code, please refer to the source code of the file "phpfn*.php" and "ewshared*.php" in template or generated scripts.

 

Some Global Functions

The following are some useful global function available in the generated code for you to get information easier in server events:

Function name Arguments Description Example
Conn - Get the global connection object $rs = Conn()->Execute("SELECT ..."); // execute a SELECT statement and get recordset object
Security - Get the global security object if (Security()->CanEdit()) { // check if current user has Edit permission for the current table (for use with User Level Security
    ...your code...
}
Language - Get the global language object Language()->setPhrase("AddLink", "xxx"); // change the wording for the "Add" link
CurrentUserName - Get current user name. $username = CurrentUserName();
CurrentUserID - For used with User ID Security (see Security Settings). Get current User ID. $userid = CurrentUserID();
CurrentUserLevel - For used with User Level Security (see Security Settings). Get current user's User Level ID (integer). (Note: NOT current user's permission as integer.) $levelid = CurrentUserLevel();
CurrentUserInfo fieldname For used with Advanced Security (see Security Settings). Get current user's info from the user table. The argument is the field name in the user table. $email = CurrentUserInfo("email");
CurrentPageID - Get current page ID. A page ID identifies the page type, it can be "list", "view", "add", "edit", "delete", "search", etc.

if (CurrentPageID() == "add") {
    ...your code...
}

CurrentPage - Get current page object.

$rowindex = CurrentPage()->RowCnt;

CurrentTable - Get current page object. Alias of CurrentPage.

$value = CurrentTable()->MyField->CurrentValue;

IsLoggedIn - For used with Advanced Security (see Security Settings). Get the login status of the current user. if (IsLoggedIn()) {
    ...your code...
}
ew_Execute SQL Execute UPDATE, INSERT, or DELETE statements. ew_Execute("UPDATE MyTable SET... WHERE...");
ew_ExecuteRow SQL Executes the query, and returns the first row as an array. $row = ew_ExecuteRow("SELECT * FROM MyTable WHERE...");
ew_ExecuteScalar SQL Executes the query, and returns the first column of the first row. $value = ew_ExecuteScalar("SELECT MyField FROM MyTable WHERE...");

There are many other useful functions in the generated code, please refer to the source code of the file "phpfn*.php" and "ewshared*.php" in template or generated scripts.

 

 

 

 

 

 

 

 
 ©2002-2012 e.World Technology Ltd. All rights reserved.