Server Events and Client Scripts

PHP Report Maker now supports server events and client scripts. You can create your own functionality by writing your own customized server and client side codes. The customized codes are stored in your projects 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.

The steps to create the server events and client scripts are as follows:

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 the Server Events and Client Scripts page at any time.

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 [Reset] button to discard the existing code and reload template code for the server event or client script.

 

Code Repository

PHP Report Maker now 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 class method)
  • Page_Rendering (Global function)
  • Page_Render (Page class method)
  • Page_DataRendering (Page class method)
  • Page_* / Cell_* / Row_* / Chart_* (Page class method)
  • Page_DataRendered (Page class method)
  • Page_Unload (Page/Table class method)
  • Page_Unloaded (Global function)
Notes
  1. From v6, 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, 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. 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 stylesheet.

ewr_AddClientScript("xxx.js"); // Add JavaScript
ewr_AddStylesheet("xxx.css"); // Add CSS stylesheet

Database_Connecting

This event will be fired 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 (ewr_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 auto fulfilled. 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 (CurrentPageID() == "login") {
// login page
        // connect to the common database with the common Advanced Security tables
        $info["host"] = "localhost";
        $info["user"] = "xxx";
        $info["pass"] = "yyy";
        $info["db"] = "common_db";
    }
}

Database_Connected

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

The argument is the connection object, you can use it to execute your own statements.

Example

Call a stored procedure after connection.

function Database_Connected(&$conn) {
    $conn->Execute("CALL MyStoredProcedure");
}

Language_Load

This event will be fired when the language file is loaded. You can use it to change the language phrases if necessary. Note: This event is a language class member.

Example

function Language_Load() {
    $this->setPhrase("MyID", "MyValue"); // Refer to language file for the actual phrase id
    $this->setPhraseClass("MyID", "glyphicon glyphicon-xxx ewIcon");
// Refer to http://getbootstrap.com/components/#glyphicons for icon name
}

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_Rendering

This event will be called by all PHP pages before outputting HTML for the page. 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 v6, 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

Remove the domain name to match the user name in user table (for User ID/Level Security, if enabled) after Windows authentication, if the user table stores the user name without domain name.

function User_CustomValidate(&$usr, &$pwd) {   
    if (IsAuthenticated()) { // Windows authentication
        $ar = explode("\\", $usr);
        if (count($ar) > 1)
            $usr = $ar[1]; // Return the user name only
    }    
}

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", EWR_ALLOW_LIST);
    $this->AddUserPermission("Managers", "orders", EWR_ALLOW_LIST);
}

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 (see below). 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 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, "MyMenuName", "MyMenuText", "MyPage.php", -1, "", IsLoggedIn());
        $Menu->MoveItem("Logout", $Menu->Count() - 1); // Move to last
    }
}

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, "MyMenuName1", "MyMenuText1", "MyPage1.php");
        $Menu->AddMenuItem(2, "MyMenuName2", "MyMenuText2", "MyPage2.php");

    }
}

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"));
}

Chart_Rendering

This event is fired before the chart XML is built. You can still change the chart properties using this event. Note: This event is a chart class member.

The chart object instance contains all the information about the chart to be rendered. It is an instance of the crChart class, refer to ewrfn*.php for members of the object.

Chart_DataRendered

This event is fired after the each value is set for the chart. You can modify label, value, and attributes by this event. Note: This event is a chart class member.

The parameter is:

node - The XML DOMElement of the <set> element in chart XML. If FusionCharts Free, the attributes includes name and value attributes. If FusionCharts, the attributes includes label and value attributes. There are various other attributes. Refer to FusionCharts documentation for the attributes supported by each chart. Refer to PHP 5 DOMElement on how to work with an XML DOMElement, usually you use the getAttribute and setAttribute method to get/set the attribute values.

Example

Specify a color according to value.

function Chart_DataRendered($node) {
    if ($node->getAttribute("value") == "xxx")
// Note that getAttribute() returns string
        $node->setAttribute("color", "FF0000");
// Note: Use hex color codes without "#"
}

Chart_Rendered

This event is fired after the chart XML is built and before the XML is outputted. You can still modify the XML using this event. Note: This event is a chart class member.

The chart object instance contains all the information about the chart to be rendered. It is an instance of the crChart class, refer to ewrfn*.php for members of the object. You can get the XML document by $this->XmlDoc and manipulate it by by PHP 5 DOMDocument, then save it back to the chartxml argument for output. Refer to FusionCharts documentation for chart attributes.

The parameters is:

chartxml - the XML (string) to be outputted. You can also directly manipulate it as string by string functions.

Example

Set chart subcaption by code

function Chart_Rendered(&$chartxml) {
    $doc = $this->XmlDoc; // Get the DOMDocument object
    $doc->documentElement->setAttribute('subCaption', 'My SubCaption'); // Modify the XML
    $chartxml = $doc->saveXML(); // Output the XML to $chartxml
}

Report_Inserting

For use with Generate report by HTTP GET/POST, see Table Setup. When the generated report URL is accessed, the activiity will be logged if a report history table is set up.

This event is fired before the report information is inserted into the report history table. Note: This event is a global function.

If you database does not have a report history table yet, you can create one by clicking Tools -> Create report history table, see Tools.

The parameters is:

$rsnew - an array containing the information to be inserted.

Return TRUE if you want to insert, return FALSE if you want to skip.

Table-Specific -> Report Page (Note: These events are members of the page class)

Page_Load

This event will be called after connecting to the database.

The export links are stored as a crListOptions object, you can manipulate the links in the same way. You can get a link by name using $this->ExportOptions->Item["name"]. The default names of the options are:

  • html
  • excel
  • word
  • pdf
  • email

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

Example

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_Render

This event will be called before outputting HTML for the page. You can use this event to make some last minute changes to the page before it is outputted.

Page_Unload

This event will be called before closing database connection.

Page_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 Page_Selecting(&$filter) {
    ewr_AddFilter($filter, "Field1 = 1234"); // Add your own filter expression    
}

Page_FilterLoad

This event allows you to add custom filter to the popup and extended filter of the fields. (Previously named as Filters_Load or CustomFilter_Load.)

Example 1

Add 'StartsWithA' filter to a string field.

You can use the ewr_RegisterFilter() function to add your custom filter, the parameters of the event are:

  • fld - the field object
  • FilterName - the filter name
  • DisplayName - the display name of the filter to be displayed in the popup filter
  • FunctionName - the PHP function to be called for building the WHERE clause. The function must have one and only one parameter which is the field expression to be used in the WHERE clause. You can put the function in Global Code. (Note: The following example function is already in the template, do not put it in the Global Code again.) This argument is optional, if you use function, you can add your code in Page_Filtering event

function GetStartsWithAFilter($FldExpression) {
    return $FldExpression . " LIKE 'A%'";
}

Then you can enter event code as below:

function Page_FilterLoad() {
    ewr_RegisterFilter($this->MyStringField, 'StartsWithA', 'Starts With A', 'GetStartsWithAFilter'); // Register your custom filter with your function
    ewr_UnregisterFilter($this->MyDateField, 'LastTwoWeeks'); // Unregister the built-in filter "Last two weeks"
}

Example 2

Alternatively, If you don't write a function in Global Code, you can use Page_Filtering server event, e.g.

function Page_FilterLoad() {
    ewr_RegisterFilter($this->MyStringField, 'StartsWithA', 'Starts With A'); // Register your custom filter without function, leave the implementation in Page_Filtering event    
}

Also see the example for Page_Filtering event below.

Page_FilterValidated

This event will be called after the search criteria is assigned to the 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 search criteria, change the SearchValue, SearchOperator, SearchCondition, SearchValue2, SearchOperator2 property of the field object.

Example

function Page_FilterValidated() {
    $this->MyField1->SearchValue = "your search criteria"; // Filter value
}

Page_Filtering

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 filter and/or Extended Filters. You can modify the WHERE clause in this event.

The arguments are:

  • fld - the field object
  • filter - the partial WHERE clause built from the selected filter
  • typ - the type of the filter, possible values are: dropdown (Extended Filter as selection list), extended (Extended Filter as textbox), popup (Popup Filter), or custom (Custom Filter)
  • opr - the current filter operator (for dropdown type or extended type only) or current custom filter ID (for custom type only)
  • val - the filter value (for dropdown type or extended type only)
  • cond - the condition to join the second filter operator and value, either AND or OR (optional, for extended type only)
  • opr2 - the second filter operator (optional, for extended type only)
  • val2 - the second filter value (optional, for extended type only)

Example

If you have registered a custom filter using Page_FilterLoad event (see above), you can implement your filter here, e.g. referring to example 2 for Page_FilterLoad above,

// Page Filtering event
function Page_Filtering(&$fld, &$filter, $typ, $opr = "", $val = "", $cond = "", $opr2 = "", $val2 = "") {
// var_dump($fld); // View the properties of the field
// Note: ALWAYS CHECK THE FILTER TYPE ($typ)!
// if ($typ == "dropdown" && $fld->FldName == "MyField") // Dropdown filter
// $filter = "..."; // Modify the filter
// if ($typ == "extended" && $fld->FldName == "MyField") // Extended filter
// $filter = "..."; // Modify the filter
// if ($typ == "popup" && $fld->FldName == "MyField") // Popup filter
// $filter = "..."; // Modify the filter

   if ($typ == "custom" && $opr == "StartsWithA" && $fld->FldName == "MyStringField")
// Custom filter, $opr is the custom filter ID
       ewr_AddFilter($filter, $fld->FldExpression . " LIKE 'A%'");
// Modify the filter
}

Also see the example for Page_Filtering server event below.

Page_DataRendering

This event will be called before report rendering. You can use this event to add HTML above the report. The parameter is:

header - set your HTML to this parameter.

Page_DataRendered

This event will be called after report rendering. You can use this event to add HTML below the report. The parameter is:

footer - set your HTML to this parameter.

Page_Breaking

This event will be called before inserting HTML page breaks (DIV tag by default) for print/export. You can use this event to change the HTML code. The parameters are:

break - Boolean. Specify to insert code or not

content - HTML code as page break

Row_Rendering

This event will be called before rendering (e.g. applying the View 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 for the table cell and View 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;".

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() {
    
// Use var_dump to view the arguments for development or debugging, e.g.
    //
var_dump($this->RowAttrs, $this->Trademark, $this->Trademark->CellAttrs, this->Trademark->ViewAttrs);

    // Change the row color
    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";
    }
}

Cell_Rendered

This event will be called after rendering a cell.

Note This event is fired before Row_Rendered event, if you set the same setting in the Row_Rendered event, it will be overwritten by the Row_Rendered event.

This is another extremely useful event for conditional formatting. It is especially useful for the dynamic columns for Crosstab reports as there are many dynamic columns for the same Column Field in the report. This event saves you from accessing the arrays for the columns, you can get/set the values passed to the event as arguments directly.

The arguments are:

Field - the field object
CurrentValue - current value of the cell (unformatted)
ViewValue - view value of the cell (formatted)
ViewAttrs - associative array of the View Tag attributes
CellAttrs - associative array of the table cell attributes
HrefValue - href attribute of the hyperlink for the ViewValue
LinkAttrs - associative array of attributes of the hyperlink for the ViewValue

The keys of the CellAttrs, ViewAttrs and LinkAttrs 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;".

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 Cell_Rendered(&$Field, $CurrentValue, &$ViewValue, &$ViewAttrs, &$CellAttrs, &$HrefValue, &$LinkAttrs) {

    // Use var_dump to view the arguments for development or debugging, e.g.
    //var_dump($Field, $CurrentValue, $ViewValue, $ViewAttrs, $CellAttrs, $HrefValue, $LinkAttrs);

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

Email_Sending

This event is fired before the email 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 crEmail class, refer to ewrfn*.php for members of the object.

Args - an array which contains additional information. By default it is empty.

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

Example

Use a field value of the the new record in the email

function Email_Sending(&$Email, &$Args) {
    //var_dump($Email); exit(); // Uncomment to debug
    $Email->Content .= "\nSent by " . CurrentUserName();
    return TRUE;
}

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.

Example

Replace an error message by custom message

// Message Showing event
// $type = ''|'success'|'failure'|'warning'

function Message_Showing(&$msg, $type) {
    //var_dump($msg, $type); // Uncomment to view message and type
    if ($type == 'success') {
        //$msg = "your success message";
    } elseif ($type == 'failure') {
        if (strpos($msg, "Some standard failure message") !== FALSE) // The original failure message contains some keywords you want to replace
            $msg = "My custom failure message";
    } elseif ($type == 'warning') {
        //$msg = "your warning message";
    } else {
        //$msg = "your 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>->SearchValue (e.g. $this->HP->SearchValue). Refer to the generated code for actual variable names.

A parameter CustomError is passed to the event, 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) {
    global $orders;
    if (intval($this->Qty->SearchValue) <= 0) {
        // Return error message in CustomError
        $CustomError = "Quantity must be larger than 0.";
        return FALSE;
    } else {         
        return TRUE;
    }    
}

Lookup_Selecting

For use with Extended Filter and Auto-Suggest (see Field Setup). This event is fired before selecting records from table for Auto-Suggest. You can use this event to change the filter.

Example 1

Modify the lookup table filter when a selection list looks up display values from the table.

function Lookup_Selecting($fld, &$filter) {
    if ($fld->FldName == "MyExtendedFilterField")
        $filter = str_replace("xxx", "yyy", $filter);
}

Example 2

Add additional filter to the filter

function Lookup_Selecting($fld, &$filter) {
    if ($fld->FldName == "MyExtendedFilterField")
        ewr_AddFilter($filter, "MyField = 'xxx'"); // Assume the field is of string type
}

UserID_Filtering

For use with User ID security. (See Security Settings) This event is fired before adding the User ID filter to the WHERE clause of the table. It is possible to modify, replace or add filter so the user can access more or less records that he/she can access by its originally loaded User IDs.

Example

Assume you have 2 User ID fields in the current table and in the user table, and you want to filter by both User ID fields.

function UserID_Filtering(&$filter) {
    ewr_AddFilter($filter, "MyUserIDField2 = " . CurrentUserInfo("MyUserIDField2InUserTable")); // Assume the field is of integer type
}

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.

Message_Showing

Use this event to change the error message to be displayed in the page.

Form_CustomValidate

This event is fired after the normal form validation. You can use this event to do your own custom validation.

A parameter CustomError is passed to the event, add your error message and return False if the form values do not pass your validation.

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.

 

Client Scripts

In general, each page has two blocks of JavaScripts:

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.

Note In the following table, the <fieldname> in code represents the field variable name. In general, if 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 in doubt, always inspect HTML source in your browser to check the actual id, name, and other attributes of the elements.
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 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.

Example

Use jQuery to replace the logo

$("#ewHeaderRow").html('<img src="path/mylogo.png" alt="xxx">');

Global Code

JavaScript code to be included in all pages with header. This may contain your global constants, variables and functions.
Table-Specific -> Report 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 1

Subscribe the "rendertemplate" event for Custom Template.

$(document).on("rendertemplate", function(e, args) {
    //alert(JSON.stringify(args)); // Uncomment to view the arguments
    args.data = [{key1: "value1", key2: "value2"}]; // Pass custom data to the template    
});

Example 2

Subscribe the "updatedone" event for Dynamic Selection Lists. The event fires after options of a child field is updated.

$(document).on("updatedone", function(e, args) {
    //console.log(args); // Uncomment to view the arguments in browser console
    alert($(args.target).data("field") + " has been updated.");
});

Example 3

Subscribe "show.bs.modal" event of Bootstrap Modal to change content of the modal dialog for generating report URL.

$(function() {
    $("#ewrReportUrlDialog").on("shown.bs.modal", function() {
        $("#ewrPageOption").find("option[value=all]").hide(); // Hide the "All" option
        //$("#ewrPageOption").closest(".form-group").hide(); // Or hide the whole setting
    });
});

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.

PHPMaker provides a jQuery plugin .fields() for you to easily get/set the form values in client side events such as Startup Script and Form_CustomValidate (see below)

$row = $(this).fields(); // return an object of all fields, each property is a jQuery object of the input element(s) of a field
$field = $row["<fieldname>"]; // get jQuery object of the input element(s) of a field

You can also get the jQuery object for a field directly,

$field = $(this).fields("<fieldname>"); // return jQuery object of the input element(s) of a field

The jQuery object of the field is the jQuery object of the input element of the field. (Note that if Edit Tag of the field is CHECKBOX or RADIO, the jQuery object may contain more than one elements.)

For example, if the page is an Edit page and the field is named "Field1" and it is a textbox, $(this).fields("Field1") is equivalent to $("#x_Field1"). The advantages of using .fields() plugin is that the returned jQuery object has the following additional methods:

.value([value])

.value() get field value, .value(value) set the field value.

Note This method is NOT the same as jQuery's .val() method. This method takes other features (e.g. AutoSuggest) into consideration.
.visible([value])

.visible() get the visibility of the field, .visible(value) set the visibility of the field. The value should be a boolean value.

Note
  1. This method shows/hides the DIV of the field, NOT just the input element(s) of the field itself in Extended Filter.
  2. The setter is NOT the same as jQuery's .toggle() method.
.readonly(value)

Get/Set the readonly attribute of the input element. The value should be a Boolean value.

Note For <input type="text"> and <textarea> only.
.disabled(value)

Get/Set the disabled attribute of the input element. The value should be a Boolean value.

Note A disabled control's value is NOT submitted with the form. Use this carefully in Extended Filter or the field may be filtered.
.row() Get the jQuery object of the row (<div>) of the field.
.toNumber() Get the input value as a JavaScript Number (by default the input value is string).
.toDate() Get the input value as a moment object (by default the input value is string).
.toJsDate() Get the input value as a JavaScript Date object (by default the input value is string).

Example 1

Add onchange event to the field named "Field1" in Add/Edit page to change other fields by jQuery plugin .fields()

$("#sv_Field1").change(function() { // Assume Field1 is a text input
    if (this.value == "xxx") {

        $(this).fields("FieldA").value("yyy"); // Set value to FieldA
    } else {
        $(this).fields("FieldB").value("zzz"); // Set value to FieldB
    }     
});

Example 2

Add onclick event to a field (checkbox) by jQuery

$("input[name='sv_MyField[]']").click(function() {
    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 sv_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.

Example 3

Subscribe the "rendertemplate" event for Custom Template and pass data from another table by PHP.

$(document).on("rendertemplate", function(e, args) {
    //alert(JSON.stringify(args)); // Uncomment to view the arguments
    args.data = <?php echo ewr_ExecuteJson("SELECT Field1, Field2, ... FROM MyTable WHERE MyPrimaryKeyField = " . $Page->FirstRowData["MyForeignKeyField"]); ?>; // Pass additional data to the template and assume the primary key field is number    
});

The $Page->FirstRowData property contains the data of the first row in the report (as an associative array), but note that report data is not loaded yet when Client Script is fired, so you should subscribe the event by Startup Script. The ewr_ExecuteJson() function executes the SQL and return the first row by default, you can then use the retrieved data in your Custom Template by JsRender Tags (see Custom Template).

Form_CustomValidate

This function is called 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 field can be referred to as fobj.elements["sv_FieldName"]. (The element names may have different names, always refer to the generated code for the actual form element names.) Return false if the form values do not pass your validation. Note: This function is a member of the JavaScript page class.

You can also use the jQuery plugin .fields() in this event.

Example 1

Make sure an integer field value meet a certain requirement

function(fobj) { // DO NOT CHANGE THIS LINE!
    var $qty = $(this).fields("Qty"); // Get a field as jQuery object by field name
    if ($qty.toNumber() % 10 != 0) // Assume Qty is a textbox         
        
return this.OnError($qty, "Order quantity must be multiples of 10."); // Return false if invalid
    return true; // Return true if valid
}

Example 2

Compare 2 date fields

function(fobj) { // DO NOT CHANGE THIS LINE!
    var $row = $(this).fields(); // Get all fields
    if ($row["Start"].toJsDate() > $row["End"].toJsDate()) // Assume Start and End are textboxes        
        
return this.OnError($row["End"], "The End Date must be later than the Start Date."); // Return false if invalid
    return true; // Return true if valid
}

Example 3

Manipulation of date fields

function(fobj) { // DO NOT CHANGE THIS LINE!
    var $start = $(this).fields("Start"), $end = $(this).fields("End"); // Get fields as jQuery objects by field names
    if ($start.toDate().add(7, "days").isAfter($end.toDate())) // Assume Start and End are textboxes        
        
return this.OnError($end, "The End Date must be at least 7 days after the Start Date."); // Return false if invalid
    return true; // Return true if valid
}

Chart_Rendering

This event is fired when the JavaScript chart object has finished loading the XML data and before rendering.

The event arguments are :
chart - This JavaScript chart object
chartid - This ID of the chart

Chart_Rendered

This event is raised when the JavaScript chart object has finished rendering. This call is made only once per loaded chart SWF (even if new data is supplied to it).  It can be used to invoke any further JavaScript methods on chart.

The event arguments are :
chart - This JavaScript chart object
chartid - This ID of the chart

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 function is called 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 PHP Report Maker custom script editor and save it.

 

Objects in PHP Report Maker 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 class "cr<Table>_<PageID>" (e.g. crCars_rpt) and the table class "cr<Table>" in the generated scripts.

Field Object
A <Field> object is generated for each field in a 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 "crField" in the generated file "ewrfn*.php".

Chart Object
A <Chart> object is generated for each chart in a table. For example, the "Chart1" object is generated for the chart named "Chart1" for the table. You can access the object properties using the -> notation (e.g. CurrentPage()->Chart1). For the complete list of methods and properties, please refer to the class "crChart" in the generated file "ewrfn*.php".

Security Object
The Security object is used to store the current Advanced Security settings. Please refer to the class "crAdvancedSecurity" in the generated file "ewrfn*.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 "crEmail" in the generated file "ewrfn*.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 "crMenu" in the generated file "ewrfn*.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 "crMenuItem" in the generated file "ewrfn*.php" for the complete list of methods and properties.

ExportOpions Object
The ExportOptions object contains all information of the export links in the report page, you can access the object by CurrentPage()->ExportOptions. Please refer to the class "crListOptions" in the generated file "ewrfn*.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 "crLanguage" in the generated file "ewrfn*.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 "ewrfn*.php" in the 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:

Notes

  1. In the following table, the argument $dbname or $tablename or $fieldname is the database/table/field variable name. It is case-sensitive. In general, if the name is alphanumeric, the variable name is same as the 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, it will be prepended with an underscore. If you use databases with the same name, check the database variable name in the Add Linked Table form, see Linked Tables.
  2. If MS Access, the $dbname is the file name of the database without the extension. If Oracle, the $dbname is the schema name.
  3. Argument in square brackets means that the argument is optional.
  4. If $dbname is not specified, the database of the project is assumed. If $dbname is specified, the specified database of Linked Tables is used.
Function name Description Example
Conn([$dbname])

Get the global connection object.

If $dbname is not specified, it returns the connection object for the database of the project. If $dbname is specified, it returns the connection object for the specified database of a Linked Table.

$rs = ReportConn()->Execute("SELECT ..."); // execute a SELECT statement and get recordset object

$rs = Conn("MyDbName")->Execute("SELECT ..."); // execute a SELECT statement and get recordset object

Security() Get the global security object Security()->ShowUserLevelInfo(); // Display all the User Level settings (for debug only)
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). $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 "rpt", "summary", "crosstab", etc.

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

CurrentPage() Get current page object.

$page = CurrentPage();

CurrentLanguageID() Get current language ID.

$langid = CurrentLanguageID();

IsLoggedIn() For used with Advanced Security (see Security Settings). Get the login status of the current user. if (IsLoggedIn()) {
    ...your code...
}
IsAdmin() For used with Advanced Security (see Security Settings). Check if the current user is an administrator. if (IsAdmin()) {
    ...your code...
}
ewr_Execute($sql [,$dbname]) Execute UPDATE, INSERT, or DELETE statements. ewr_Execute("UPDATE MyTable SET... WHERE...");
ewr_ExecuteRow($sql [,$dbname]) Executes the query, and returns the first row as an array. $row = ewr_ExecuteRow("SELECT * FROM MyTable WHERE...");
ewr_ExecuteScalar($sql [,$dbname]) Executes the query, and returns the first column of the first row. $value = ewr_ExecuteScalar("SELECT MyField FROM MyTable WHERE...");
ReportDbHelper([$dbname]) Get database helper object of a databse (also see Custom Files). $db = ReportDbHelper();

 

There are many other functions in the generated code, please refer to the source code of the file "ewrfn*.php" in generated scripts.

 ©2007-2017 e.World Technology Ltd. All rights reserved.