Yap (Yet Another Pager) version 2.1.0
20/01/2007

Index


Description

Yap (Yet Another Pager) is 'another' pager with features of row editing and interactive search pattern.

Feature:

For more information see the Yap page at www.andrioli.com/en/yap.html (www.andrioli.com/it/yap.html italian version).

More details

Return to index

Installation

The class requires PHP 4.3.x/4.4.x or PHP 5

Note about PHP 5

In order to use this module with PHP 5, you must enable compatibility mode with Zend Engine 1 (PHP 4.x), by setting
zend.ze1_compatibility_mode = on
in your php.ini

Return to index

Migration from rel. 1.x.x

The new event driven coding has changed the behaviour from the previous release.

If call Yap 1.x without any POST/GET parameter, it tries to establish if it is the first time the script run. If YAP finds its session data, it resumes the previous status. If it doesn't find anything, Yap assumes to be the first run.

Yap 2.x has changed his behaviour. If you run the script without any POST/GET parameter YAP, always, assumes to be the first run and remove all data (if any) from previous run. If you want resume the previous status you must use ev=YAP_DRAWCURRENT (i.e. http://mysite/myscript.php?ev=YAP_DRAWCURRENT).

Return to index

How it works

The module has two public method: the constructor and showpage. The constructor asks 5 array containing all the information required by Yap to work.

Here a quick example how to use Yap.

 

<?php
/*
* test1.php
* Module yap testing program 1
* $Header: d:/cvs/classistd/yap/doc.html,v 1.4 2003/11/14 06:50:21 Administrator Exp $
*/
// Include the msgbox class. This class is used to display the searchbox, and the modify/delete

// forms
include_once('CYapBox.php');
// the module itself
include_once('CYap.php');
// The session are required, start it
session_start('test');
/*
* Open the HTML page. The module make the html code to show the contents
* but not open or close the page. The caller must provide the required code
* to start and to close the page
*/
echo '<html><body>';
/*
* Sql statement to retrieve the data to show. Two statement are required. The first
* give the row to show, the second one allows to retrieve the number of rows
* returned by tre previous sql statement.
* Notice the 'where '. If you don't add condition (i.e 'where id>1'), you must add
* the 'where' without any other condition (the module append to it the condition
* that it get from the search box).
* If you add some conditional statement you must end the statement with 'and'
* (i.e '... where id>1 and ') to allow to append the required search patterns.
*/
$SelectQuery='select id, DEvent, errno, text, filename, line from dlog where ';
$SelectCount='select count(*) from dlog where ';
/*
* Start to prepare the parameters for the module
*/
//Db Connection parameters
$db_info=array('servername'     => 'localhost',
               
'dbname'         => 'log',
               
'user'           => 'your_user',
               
'password'       => 'your_password',
               
'selectquery'    => $SelectQuery,
               
'selectcount'    => $SelectCount,
               
'orderfield'     => 'id',         /* field to use to order the rows
                                                  * it must 'selected' from $SelectQuery
                                                  */
               
'orderdirection' => 'A',          /* order A=upward, D=descending*/
               
'needopendb'     => true          /* should the module open the connection
                                                  * to the database? */
               
);
// Field to use to perform the search
$Search_field=array(array('description' => 'Event Date',
                          
'fieldname'   => 'DEvent',
                          
'type'        => 'A',  /* A=alphabetic, N=Numeric */
                          
'size'        => 14,
                          
'useregex'   => 1 ),   /* use regex to match the field
                                                  * contents against the requested
                                                  * string */
                    
array('description' => 'Error Code',
                          
'fieldname'   => 'errno',
                          
'type'        => 'N'),
                    );
// Fields to show for each row
$Show_field=array(array('fieldname' => 'id',
                        
'header'    => 'Id'),
                  array(
'fieldname' => 'DEvent',
                        
'header'    => 'Event Date'),
                  array(
'fieldname' => 'errno',
                        
'header'    => 'Error Code'),
                  array(
'fieldname' => 'text',
                        
'header'    => 'Description'),
                  );

$Show_info=array('prefix' => 'tst1');
// I don't setup the detail mode, the add/modify/delete row functions
$Modify_info=array();

// new class istance
$p=new CYap($Search_field, $Show_field, $db_info, $Show_info, $Modify_info);
// Show it
$p->showpage();
echo
'</body></html>';
// That's all folk!
?>

To run the previous example, create into your Mysql server a database called 'Log' and load into it the provided 'example.sql'. It creates the table DLog and fill it.


Return to index

Playing around the events

The following example highlights the code required to define the custom events.

The complete example (not provided) shows the open ticket (one ticket per row). On each ticket the user must be able to close the ticket and add note to it. Therefore I defined the function OtherFunctionAll that add the two links on each row. The links fire the two custom events 'YAP_TKCLOSE' and 'YAP_ADDNOTE'. Then I tell to Yap which function run on my events (call to function RegisterEvent) and write the two handler (functions OnAddNote() and OnCloseTicket() ).


<?PHP
// main function
...
$Show_info=array('cfgfile' => '../cfg/itemallticket.cfg',
                 
'languagefile' => '../include/language.en',  
                 
'exit' => $_SESSION[$_SERVER['PHP_SELF'].'returnTo'],
                  
// the following parameter tells to CYap to call the function OtheFunctioAll on
                  // each row. This function add two custom links to each row.
                 
'rowcallback' => 'OtherFunctionAll',    
                  );   

...
$p=new CPciYap(array(), array(), $db_info, $Show_info,$ModifyInfoCfg);
/*
* In this example I defined two custom event 'YAP_TKCLOSE' and 'YAP_ADDNOTE'.
* Here I set the function to run on events.
*/
$p->RegisterEvent('YAP_TKCLOSE','OnCloseTicket');
$p->RegisterEvent('YAP_ADDNOTE','OnAddNote');
$p->showpage();     
...



/*
* Here I define the two functions. These function may be global or defined inside
* CYap.
*/
function OnAddNote()
{
...
}

/*
* ..and this function handle the event YAP_TKCLOSE
*/
function OnCloseTicket()
{
...
}



/**
*
* Function used to add other link to each data row.
* It adds links to add note, close ticket and show the related device.
*/
function OtherFunctionAll($row)
{
// This link fires my custom event YAP_ADDNOTE.
// All event name must begin with YAP_
$link=$_SERVER['PHP_SELF'].'?id='.$row['id'].'&amp;ev=YAP_ADDNOTE';
$text[0]='<a href='.$link.' onMouseOver="ToolTip(\'Add comments to this ticket\')" onMouseOut="ToolTip()" ><img src=\'images/postit.gif\' border=0></a>';
if(
$row['DateClose']=='2000-01-01')  
   {
   
// and this link fires my custom event YAP_TKCLOSE
   
$link=$_SERVER['PHP_SELF'].'?id='.$row['id'].'&amp;ev=YAP_TKCLOSE';
   
$text[1]='<a href='.$link.' onMouseOver="ToolTip(\'Close the ticket\')" onMouseOut="ToolTip()" ><img src=\'images/tk_close.gif\' border=0></a>';   
   }
return(
$text);
}
?>

Return to index

Public functions, basic

CYap CYap( [array $search_field = array()], [array $show_field = array()], [array $db_info = array()], [array $show_info = array()], [array $modify_info = array()] )

Istance the class. It takes 5 parameters. These parameters allow you to configure the class. You may omit those parameter and use the configuration file. In that case you must provide the configuration file name.

boolean RegisterEvent( string $EventName, string $Handler )

Set the handler to custom events or modify the default handler to defined events

void showpage( [string $ForcedEvent = ''] )

Show the HTML page. The parameter allows you to force the event to process. If it is omitted Yap looks for $_REQUEST['ev'], if exists. If it don't find the parameter it assumes to be the first time the module run.

Return to index

Configuration parameters: Database access info

The database parameters ('$db_info' in the example) contains the following index

servername

Mysql server

dbname

Database name

user

user name

password

password

selectquery

Query used to retrieve the rows to show. Notice the 'where '. If you don't add condition (i.e 'where id>1'), you must add the 'where' without any other condition (the module append to it the condition that it get from the search box).
If you add some conditional statement you must end the statement with 'and' (i.e '... where id>1 and ') to allow to append the required search patterns.

selectcount

Query used to re trievethe number of the rows to show. It has the same rule about the 'where ' statement as 'selectquery'

You may omit this parameter since Yap 1.1.0

orderfield

field to use to order the rows it must 'selected' from 'selectquery'

orderdirection

order directtion: A=upward, D=descending

needopendb

should the module open the connection to the database? (true/false). This parameter is useful if you make some temporary table so you need to open the connection inside the caller script and the module must not open its own connection to the database.(Optional, default: true)

db_class

Class to use to connect to the database. Must be a class that extends CYapDb. (Optional, default: CYap_Mysql)

Return to index

Search parameters

Parameters required to build the search box. This parameter is an array of array. Each array contains the information about the field to show into the search box and to use it to build the search pattern. If you set this parameter as an empty array, the search box will be not shown. Each field array cointains the following index

description

1.0.0

field description to use in query form

fieldname

1.0.0

mysql field name. It is case sensitive

type

1.0.0

A=alphabetic, N=Numeric

size

1.0.0

field size for padding. Used for type A

padding

1.0.0

Request the padding for the field (none, left, right) default: none. Ignored if field type = N

paddingchar

1.0.0

character to pad the field. Ignored if field type = N

useregex

1.0.0

use regex to match the field contents against the requested string. It is used for type A field, and if true the module don't pad the field. Values 1=use regex, 0=don't use regex. Optional, default: 0

fieldclass

2.1.0

Class to use to manage the input box. Available classes are: CYap_clsSearchDate, CYap_clsSearchRangeTxt, CYap_clsSearchRegexOpt, CYap_clsSearchSelectBox, and CYap_clsSearchTxt. Default: CYap_clsSearchTxt

viewclass

2.1.0

Class to use to write the HTML code for the field object. It keeps away the HTML code from the logic of the filter form, so you may customize easily the form appearance. By default, each field class has it own view. The relationship is:
CYap_clsSearchDate CYap_ViewDate
CYap_clsSearchRangeTxt CYap_ViewTextRange
CYap_clsSearchRegexOpt CYap_ViewOptRegex
CYap_clsSearchSelectBox CYap_SelectBox
CYap_clsSearchTxt CYap_ViewTextBox

optionlist

2.1.0

Used only if fieldclass is set to CYap_clsSearchSelectBox. Array of available option The index is the value returned by the form and used to build the filter condition. The value is the text shown to the user as option.

showformat

2.1.0

Used only if fieldclass is set to CYap_clsSearchDate. How the date is shown to the user and entered by the user. Available formats: d/m/Y, d-m-Y, m/d/Y, and m-d-Y.

whereformat

2.1.0

Used only if fieldclass is set to CYap_clsSearchDate. Date format to use to build the filter to look for. It accepts all formats recognized by PHP date command.

layoutclass

2.1.0

Class used to place the input box on the form. The avilable classes are

CYap_clsSearchLayout

(default) One column layout.

CYAP_cls2ColumnLayout

Two column layout.

Return to index

Table columns

List of column to show into table view. This parameter is an array of array. Each array contains the information about the fields to show. Each field array cointains the following index

fieldname

Name of the field from the select query. Note it is case sensitive: the field name has the same case used into select statement

header

Text used as column title into table view

showdetail

True/False, Should the field be shown in detail mode?

showtable

True/False, Should the field be shown in table mode?

format

Format to use to show the field's value.

Return to index

Row editing parameters

Parameters used by add/modify/delete row functions. The array cointains the following index

showadd

Should the module shows the 'new row' link? Values: true/false. Optional, default: false

showmodify

Should the module shows the ' modify row' link into each row? Values: true/false. Optional, default: false

showdelete

Should the module shows the delete row' link into each row? Values: true/false. Optional, default: false

modifyallow

It specifies the custom function to call to check if the module sholud show the 'new row' link. The 'showadd' key tell to Yap 'ok you check the modyallow function and if it allows you show the 'modify row' link. This function allows to enable/disable the modify function per row basis. The custom function must accept 1 parameter (the value of the row key) and it must return true (to show the link) or false. Optional, default:true.

deleteallow

As modifyallow applied to the delete function

addallow

As modifyallow applied to the add link

table

database table name to apply the editing function (this function don't use the information from selectquery parameter).

keyfield

Name of the unique key to use to identify the row

fieldtorequest

it contains the name of the field to ask into modify/add row. If empty, all field from the table are requested

fieldvalidator

callback to the function to perform the validation for each field filled from the form. If not set, the field is assumed correct. The function has two parameters: an array containing all the requested field (indexed by field name), and the name of the field to check; it must return true (if the value is correct) or false to reject the value.

customaddrow

Custom page to call when 'add new row' link is selected.

custommodifyrow

Custom page to call when the link 'modify row' is selected. Yap pass the id of the requested row to the called page through the post parameter 'id'.

customdeleterow

Custom page to call to delete the selected row. Yap pass the id of the requested row to the called page through the post parameter 'id'.

fields

New associative array that contains information about the field to request.

The array's indexes are the name of the fields required to be shown.

Each field item is another associative array. It has the following indexes:

default

Default value for the field

classname

Each type of input box is created as PHP class. Yap sets its own default class, but you may extend that class and here set your class name.

fieldvalidator

As the above 'fieldvalidator' this parameter set the callback function to perform the validation for each field filled from the form. If one field does not have its callback function, the field is assumed correct. The function has two parameters: an array containing all the requested field (indexed by field name), and the name of the field to check; it must return true (if the value is correct) or false to reject the value.

custom

Custom information used by the class specified in classname.

Note: this parameter give a new way to set information about field to request, so it override the old parameters 'fieldvalidator' and 'fieldtorequest'.

Return to index

Miscellaneous parameters

Group of unrelated parameters

rowcallback

Callback function called on each row. It is useful to add custom link to each row. Optional, default no callback

onokhref

Page to call if the add/modify action successed (only add o modify mode).

onaborthref

Page to call if the add/modify action is aborted (only add o modify mode).

showdethref

Should the module show the 'detail' link to switch to 'detail view'. Values: true/false. Optional, default: false

prefix

Prefix to add to the session variables to allow multiple pager istance into the same session.Optional default space

detailmode

Set the table view (if set to false) or the detail view (if set to true). Optional, default false.

languagefile

Set the file that contains the translated text. Optional, default './language.en'

showfirstcallrow

When set to true, it enables yap to show first 15 rows at the first time the page is shown. The default, or when set to false, it shows only the search box.

showpagenumber

Should the class show the link to pages 1,2,3,.. Optional, default: TRUE

showmovepage

Should the class show the link to the next/previous page? Optional, default: TRUE

mode

Set the mode to start to show the rows. The modes are: DisplayTable (shows the rows as a table, the default), DisplayDetail (display the row detail, it starts from the first), Add (it starts directly into add new row mode), Modify (it starts directly into add new row mode). Optional, default: DisplayTable

BoxClass

Class used to draw an message box. Optional, default: CYapBox

DetailViewClass

Class used to render the row's detail. Optional, default: CYap_DetailView

TableViewClass

As the previous one, but it is used to render the table Optional, default: CYap_TableView

SkipPageClass

Module used to display first, previous, next, last page. Optional, default: CYap_MoveToPage

PageNumberClass

Display the number of the pages before and after the current one. Optional, default: CYap_PageNumber

FormClass

Draw the form to perform the add/modify functions. Optional, default: CYap_Form

pre_1_0_style

Compatibility issue. In detail mode, the 1.1.1 allows to set which columns show. This way requires that the column to show must be listed in $ShowFieldCfg, otherwise the module assumes not to show the column. The previous version, in detail mode, it shows all columns regardless the $ShowFieldCfg parameter. Set this variable to false if you want to gain more control on the field to show in detail mode, or set to true if you prefer the old behaviour. Optional, default: true.

outformats

This parameter allows you to define many custom formats to use to show the values. It is an array indexed by format name. Each element is an array which may contains the following keys:

custom

Formats the output through a custom function. The function must accept one parameter (the value) and return the formatted string

printf

Formats the output according to printf format options. It accepts the same format as the PHP function printf.

date

If the field is a timestamp, it shows the date according to the format. It accepts the same format as the PHP function date.

number

Format the number through the PHP number_format function. Value: decimals,dec_point,thousands_sep

Yap comes with some predefined formats. They are:

  • NUMERIC_IT: numeric number, Italian format x.xxx.xxx
  • NUMERIC_EN: numeric number, English format x,xxx,xxx.xx
  • MONEY_IT : monetary Italian format x.xxx.xxx,xx
  • MONEY_EN : monetary English format x,xxx,xxx.xx
  • DATE_IN : convert timestamps into Italian format date day/month/year
  • DATE_US : convert timestamps into US format date month/day/year

This parameter is optional.

Return to index

Available input types

CYap_clsSearchDate

Date input box. It shows a text input box and the calendar where pick the required date.

The class allows to set the date format on the form and the format used to build the where statement.

NOTE: it requires dhtmlgoodies calendar library from www.dhtmlgoodies.com.

CYap_clsSearchRangeTxt

The class allows the user to insert the minimum and maximum value to look for. The user has two box (the min and max value), he may fill both, one, or never fill them. If only one input text is filled, Yap assumes equals the minimum and the maximum value. If it is not filled, the filter on the specified field will be not applied.

CYap_clsSearchRegexOpt

The class allows the user to choose whether look for the exact text written in the input text box, or use that text as pattern. Of course apply the pattern is slower than look for the exact text.

CYap_clsSearchSelectBox

The class show the select box with the available options to choose from.

The configuration parameters tell to the class which the text show as option and which value return for each option.

The class recognizes two reserved words ALL (return all rows) and NOFILTER (do not apply any filter on this field). Both values have the same effect, no condition will be added on the database column set for this class.

CYap_clsSearchTxt

Default input text. It shows the box where the user write the text to look for on the provided database.

Return to index

Public functions, advanced

Return to index

Advanced function, example

<?php
$p=new CYap(array(), array(), $db_info$Show_info, array());
// Get the filter object
$FilterObj=$p->GetSearchObject();
// Form Layout: 2 column layout
$FilterObj->SetLayoutClass('CYAP_cls2ColumnLayout');
// Add range of text input object;
// Create the field. The index are the same as $SearchFieldCfg
$f1=new CYap_clsSearchRangeTxt(array(
                             
// Textbox label
                            
'description' => 'Event Date',
                            
// DataBase field where look for the typed string
                            
'fieldname'   => 'DEvent',
                            
// A=alphabetic, N=Numeric
                            
'type'        => 'A',
                            
// Field size. Used to set the textbox size
                            
'size'        => 14,
                            
/* use regex to match the field
                             * contents against the requested
                             * string. 1=yes, 0=no */
                            
'useregex'   => ),'TxtRange');
// Add the field to the filter form
$FilterObj->AddSearchField($f1,'TxtRange');

// Second input. You may setup the parameters later
$f2=new CYap_clsSearchRegexOpt(array(),'TxtRegex');
// Parameters setup. You may set one paramneter on each call..
$f2->LoadCFg(array('description' => 'Event Date'));
// ... or many paramters with one call
$f2->LoadCFg(array('fieldname'   => 'DEvent',
                  
// A=alphabetic, N=Numeric
                  
'type'        => 'A',
                  
'size'        => 14,
                  
'useregex'   => ));
// Add the field to the filter form
$FilterObj->AddSearchField($f2,'TxtRegex');

//third... select input type
$f3=new CYap_clsSearchSelectBox(array( // Label
                                      
'description' => 'Error Code',
                                       
// DataBase field where look for the typed string
                                      
'fieldname'   => 'errno',
                                      
// A=alphabetic, N=Numeric
                                      
'type'        => 'N'),'SelectBox');
// Now add the available options to choose from
$f3->AddOption'OK (0)','0');
$f3->AddOption'Err 512','512');
$f3->AddOption'Err 1024','1024');
// ALL rows option
$f3->AddOption'No selection','NOFILTER');
// Add the field to the filter form
$FilterObj->AddSearchField($f3,'SelectBox');

// Finally show the table
$p->showpage();
echo 
'</body></html>';
?>

Return to index

Change Log

23/01/2007 ver 2.1.0

  • Changed the code used to manage the filter form. It uses the MVC method to draw the form, parse the input and to build the where statement to filter the rows. Now is is more easy to add custom input object, modify the form layout.
  • Added more input object type (date input, range input, select box)

28/02/2005 ver 2.0.0

  • PHP 5 support.
  • Event driven coding.
  • Added support to MSSQL Server.
  • New API documentation available at http://www.andrioli.com/en/yapapi/index.html.

30/09/2004 ver 1.2.0

  • Move out the database connection logic to classes to extend the support to many other database.
  • Added support to ODBC. Note: this module was tested to connect to Ms Access on Win32 system.

1/9/2004 ver 1.1.1

  • Added more control on which fields show in detail mode
  • Added parameters to set the value's output format
  • Many bugs fix
  • Fixed the test programs. In the previous release they haven't the correct include statements.

21/06/2004 ver 1.1.0

  • In this release I moved out from the business module the PHP code that builds the user interface. In this way I hope to make easy the design customisation. Each interface object as form, table view, detail view, message box, link to the next/previous page, now are written as single class that you may extend.

26/03/2004 ver 1.0.1

  • Added new parameter showfirstcallrow, to enable to show first 15 rows at the first time the page is shown. Normally it shows only the search box.
  • Fixed column type identification in case of type blob/text/set/enum
  • Fixed, you must set the parameter 'table' into the edit feature parameters, also if you don't enable it

23/11/2003 ver 1.0

First public release

Return to index

License

Yap is licensed under the GNU/LGPL. See license.txt.

That's all. I hope it will be useful.
Darvin
(darvin at andrioli dot com)