Forms With Ajax And Advanced Plugins
-
Upload
manuel-lemos -
Category
Business
-
view
6.810 -
download
2
Transcript of Forms With Ajax And Advanced Plugins
Formulrios Web avanados em PHP
Advanced Web forms using PHP
Web forms using PHP with AJAX and advanced plug-ins
http://www.phpclasses.org/formsgeneration
Manuel Lemos
This presentation license: Creative Commons
Attribution-NoDerivs 2.5
Creative Commons License Deed
Attribution-No Derivs 2.5
You are free:
to Share -- to copy, distribute, display, and perform the work
to make commercial use of the work
Under the following conditions:
Attribution. You must attribute the work in the manner specified by Manuel Lemos.
No Derivative Works. You may not alter, transform, or build upon this work.
For any reuse or distribution, you must make clear to others the license terms of this work.
Any of these conditions can be waived if you get permission from Manuel Lemos.
Your fair use and other rights are in no way affected by the above.
This is a human-readable summary of the Legal Code (the full license).
This means you must preserve the original license terms and copyright notices.
You can redistribute this presentation in full and without modifications.
If you have questions about the license terms just contact Manuel Lemos for further clarification. The contact address is in the presentation initial page.
Forms Generation and Validation class What is it?
A class of objects written in PHP
Generates HTML to present Web forms
Generates Javascript to validate before submitting the forms to the Web server
Validate forms on the server side with the PHP code of the class itself
Extensible using plug-in classes
Open Source with a BSD like license
Good reputation in the PHP Open Source world
Over 44.000 distinct users downloaded it from the PHPClasses site
Number 248 in Freshmeat popularity top
The license of the class is not GPL or LGPL. You can modify and use it in proprietary code projects, without having to distribute your code changes, nor having to open the code of your projects. It is IP clean.
The statistics are from January 2007
Near 42.000 projects listed in Freshmeat
1 Mplayer | 2 Linux | 3 cdrtools | 4 gcc | 5 PHP | 6 Apache | 9 MySQL | 13 phpMyAdmin | 14 PostgreSQL | 23 Perl | 76 Python | 133 ADODB | 248 Forms | 603 Ruby | 6341 Ruby on Rails
Number 2 in most popular PHP class packages, right after ADODB package
Class development history
12/01/1999: Class creation
../../1999: Offer the class to other users in PHP mailing lists
05/06/1999: User recommends the class a lot in the php-general list
18/06/1999: Beginning of the PHPClasses site
24/06/1999: Launch of the PHPClasses site
16/12/2002: Plug-in to integrate with Smarty
03/04/2004: Templates with simple PHP code within HTML
14/06/2004: Special input controls using plug-in classes
29/12/2004: Processing browser side events on the server side
25/06/2005: Connected input trigger actions upon browser side events
14/03/2006: Submission of forms using AJAX
The class was meant to avoid the need to learn and write Javascript manually, and develop the forms the Web developers need using only PHP.
The user that recommended the class a lot was Robert Chalmers from Australia
The Smarty compiled templates concept was proposed by Manuel Lemos on 19/02/2000 in the now extinct php-template mailing list
Plug-in release history
14/06/2004: Date
29/12/2004: CAPTCHA
25/06/2005: Linked select
30/12/2005: MySQL, Metabase, MDB2 linked select
14/03/2006: AJAX submit
26/03/2006: Layout vertical
24/05/2006: Map location
21/06/2006: Autocomplete
12/07/2006: MySQL, Metabase, MDB2 autocomplete
28/07/2006: Animation
20/12/2006: Upload progress meter
How should it be used?
The script that processes the form also presents it.
Create an object of the classDefine the form inputsLoad the submitted values, if anyShow the form for the first time?Validate submitted input valuesAll the inputs are valid?Process the form
Output the form
Output the form denoting invalid inputs
Yes
No
No
Yes
The traditional approach is to use one page for presenting the form, and another to display the form processing results.
If the form is invalid you need to present the form again. So the single script approach is better, as it avoids the need to redirect to the page of the form. This way it is easier preserve the submitted form values and denote the invalid inputs.
Example of usage
include('forms.php');
$form = new forms_class;
$form->AddInput(array(
'TYPE'=>'text',
'NAME'=>'nome',
'ID'=>'nome',
'LABEL'=>'Name,
'ACCESSKEY'=>'N',
'ValidateAsNotEmpty'=>1,
'ValidationErrorMessage'=>
'No name was entered.'
));
$form->LoadInputValues();
$processed=false;
if($form->WasSubmitted()) {
$error=$form->Validate($verify);
if(strlen($error))
echo 'Error: ', $error;
else {
// Processing goes here
$processed=true;
}
}
if($processed)
echo 'The form was processed!';
else {
$form->StartLayoutCapture();
require('template.php');
$form->EndLayoutCapture();
$form->DisplayOutput();
}
Template sample
template.php
:
This is a simple HTML template with some PHP code in the middle to specify where the inputs and the respective labels appear.
There are other ways to define the presentation of the forms, like for instance using Smarty templates, or using an automatic layout engine that does not require HTML editing. These ways are presented in detail ahead.
API
Divided in 3 layers:
Definition
Presentation
Processing
API: Form definition
AddInput
Adds an input to the form with given parameters
Connect, ConnectFormToInput
Connect inputs in such way that when an event happens in the source input or the form, an action is executed in the scope of the target input
Example: when a select input changes, it is emulated a click action in a submit input
Configuration class variables
Example: ACTION, METHOD, TARGET, etc..
API: Form presentation
AddInputPart, AddLabelPart, AddDataPart
Adds an input, an input label, or custom HTML to the form output
StartLayoutCapture, EndLayoutCapture
Automatic capture of HTML to include in the form output
FetchOutput, DisplayOutput
Generates HTML and Javascript of the whole form
PageHead, PageLoad, PageUnload
Generates HTML and Javascript that must be included in the page HEAD section or in the ONLOAD and ONUNLOAD attributes of the BODY tag
The HTML code in the page HEAD section may be Javascript code or CSS style definitions.
API: Form processing
LoadInputValues
Extract submitted input values, discards forged values, convert escaped values, format input value masks
WasSubmitted
Checks whether the form is being submitted for processing, or the form is being presented for the first time
Validate
Checks whether the input values of the whole form (or part) are valid
GetInputValue, GetCheckedState, GetCheckedRadio
Retrieve the input values to let the application process the form
Form input definitions
Associative array passed to the AddInput function:
Mandatory parameters: TYPE, NAME, ID
Presentation parameters: CLASS, LABEL, etc.
Validation parameters
Input type specific parameters
Example:
$form->AddInput( array(
'TYPE'=>'password',
'NAME=>'password',
'ID'=>'password',
'CLASS'=>'password'
'ValidateAsNotEmpty'=>true,
'ValidationErrorMessage'=>'The password field is empty.',
'MAXLENGTH'=>10
) );
Filtering the input values
Load submitted input values
Convert escaped values magic quotes
Filter forged values
Example: MAXLENGTH, DiscardInvalidValues
Format input value masks using regular expressions
Example: zip code ^([0-9]{5})-?([0-9]{3})$ \1-\2
Validating the input values
Generates Javascript for browser side validation
Server side validation in PHP with the class itself
Sub-forms to validate a subset of inputs depending on the submit button that was used
Example: SubForm cancel
Special values to skip validation
Example: ValidateOptionalValue
Error messages to show when input values are invalid
Focus and highlighting of invalid inputs
Example: InvalidCLASS, InvalidSTYLE
If necessary, the validation may happen only on the browser side, or only server side.
The generation of Javascript may not be wanted, like for instance in some sites for United States government, as explained by an user of the class.
Predefined types of validation
Empty input, minimum length
Input is equal or different from another input or value
Integer, decimal or floating point number
E-mail address, credit card number
Match or does not match a regular expression
Ticked an input of a group of radio or check box inputs
Developer defined validation functions
Special validation type implemented by plug-in classes
Supports only POSIX regular expressions to assure compatibility between browser side validation with Javascript and server side validation with PHP.
Developer defined validation functions may be written in Javascript or PHP.
Plug-ins may generate Javascript to validate other fields, and so implement custom validation rules.
Plug-in based validation happens only after base input validations.
Form presentation using templates
HTML with PHP
StartLayoutCapture and EndLayoutCapture to capture the current script HTML output and adds it to the form output using AddDataPart
Plug-in for the Smarty template engine
Pre-filter that replaces Smarty templates with the tags {input} and {label} by calls to AddDataPart, AddInputPart and AddLabelPart
Automatic layout
Standard form presentation defined without requiring that the developer enters HTML manually
Uses PHP output buffer to capture the script HTML output.
Vertical layout of all inputs, showing one input per row.
Ideal for quick prototypes, or for developers that work alone, as they do not need a Web designer to produce the form HTML template.
Implemented by a plug-in.
Plug-ins
Provide:
New types of input controls
New behaviors
New validation types
New types of layout for groups inputs
Implemented using sub-classes of a base plug-in class
May generate HTML and Javascript, or nothing at all
New behavior example: auto-complete.
The plug-in base class is defined in the same PHP script as the main forms class.
Plug-ins just for server side validation do not need to generate any HTML or Javascript.
Plug-in: Calendar date
Displays 3 inputs to choose the year, month and day
The date format is configurable
Accepts any valid date between 1 and 9999 AC
May restrict accepted dates within a start and end day
The months may appear as numbers or as names in any idiom.
The plug-in also generates Javascript to validate a date on the browser side before submitting the form.
The start day restriction may be applied without an end day restriction, and vice-versa.
If the date is restricted to a small range of years, the year is chosen with a select input instead of a text input.
Plug-in: Human user validation using CAPTCHA
Generates an image with the text to be typed
The image is obfuscated to difficult guessing by robots
Users can use a button to redraw unreadable images
The validation text may expire after a timeout period
The font, size, color and the obfuscation image are configurable details.
The text to be typed is encrypted with secret key only known by PHP form script
The secret key may be stored in session variables, if the developer wishes that, but the plug-in does not use sessions nor cookies to show the validation image
After the timeout period, the validation text may no longer be decrypted with the same secret key. A new text must be generated. This is meant to avoid repetition attacks.
Plug-in: Pick a map location
Get the coordinates of a location picked by the user
The maps are presented using the Google Maps API
The coordinates appear in text inputs
The map zoom level may be adjusted in several ways
The location picked by the user is marked with an icon.
The use of Google Maps API is free. In the future, this plug-in may also support other map APIs, like the Yahoo Maps or Microsoft MapPoint.
The user may change the coordinates manually in the text inputs. These inputs may be hidden from the user to prevent manual changes.
The developers may add custom markers for locations with specific coordinates and location descriptions.
The zoom level may be adjusted to make all custom markers visible.
Plug-in: Automatic vertical layout
Layout several inputs vertically, one per row
Does not require defining HTML for the default layout
The layout HTML templates are customizable
Invalid inputs appear with a special mark
Specific inputs may be turned invisible
Ideal to layout all or part of the form inputs very quickly.
The default HTML templates use tables to avoid hardcoding column widths. The templates may be redefined to use tableless HTML.
Invisible inputs may be omitted from the form output depending on a condition value passed in the definition parameters.
Plug-in: Animation visual effects
Animates page elements using visual effects
Each animation is a sequence of visual effects
Several animation sequences may run in parallel
Several effect types may be used:
Replace or insert HTML content
Show or hide a page element
Fade-in or fade-out a page element
Cancel running animation to synchronize effects
It can animate any page elements, even those that are not part of the form.
More animation effects will be implemented in the future.
Plug-in: Submit a form using AJAX
Submit the form without reloading the page
Uses the hidden IFRAME approach, which is more powerful and portable than using XMLHttpRequest
Can show server-side activity feedback
Generates Javascript to execute actions in response:
Replace or insert HTML content in the current page
Change properties of page elements
Pause for a given period
Redirect the browser to another page
Execute an arbitrary Javascript command
IFRAMEs works on practically all browsers.
IFRAMEs can be used to achieve certain things that are not possible with XMLHttpRequest, as file uploading. IFRAME do not need to access the files directly.
IFRAMEs also can retrieve multiple responses with a single HTTP connection. This is useful to show the progress of tasks that take a long time to finish.
Javascript code is embedded in the response HTML document that is loaded in the hidden IFRAME.
Almost every kind of response action can be specified without requiring that the developer writes custom Javascript.
COMET: AJAX using IFRAME
: Browser : Web Server
Accesses the form page
Sends form with Javascript and IFRAME
Submits form with the IFRAME
Sends HTML with Javascript to update the form page
Plug-in: Linked select inputs
May link two or more select inputs in chain
Switches options when the value of another changes
Static options or retrieved from the server using AJAX
Has special versions to get options from a database
It may also link inputs of other types besides select.
The select options are switched without reloading the page.
Static options are defined using arrays.
The versions that retrieve options from a database support MySQL and other database types using the Metabase API or PEAR::MDB2 API.
Other developers may easily write other versions to use other database access APIs.
Plug-in: Auto-complete text
Completes typed text using a list of words
Shows menu with the words that can complete the text
May get completion words from the server using AJAX
Has special versions to get the words from a database
The words that appear in the menus may be formatted using custom HTML.
Optionally, a button may be used to make the words appear all at once in the menu.
Also uses hidden IFRAME to retrieve the words from the server with AJAX.
The versions that retrieve options from a database support MySQL and other database types also using the Metabase API or PEAR::MDB2 API.
Other developers also may easily write other versions to use other database access APIs.
Plug-in: Upload progress meter
Sends a parallel AJAX request during form submission
Uses the uploadprogress extension to monitor upload
Renders a progress bar with optional upload statistics
The uploadprogress extension requires PHP 5.2 to work.
The forms class comes a patch that can be applied to PHP 4.3 and 4.4 to let the uploadprogress extension work under these PHP versions.
The progress bar output is defined using an HTML template.
The progress bar template may include template marks to show upload statistics like the uploaded size, remaining time, the current and the average upload speeds.
3rd party plug-ins
Xinha: Alessandro Bianchi (Italy)
HTML editor
http://www.phpclasses.org/xinha_plug_in
Cal: Alessandro Bianchi (Italy)
Calendar with pop-up to browse the months and years
http://www.phpclasses.org/plugin_cal_class
FCKEditor: Matas Montes (Argentina)
HTML editor
http://www.phpclasses.org/form_fckeditor
Your plug-in
Anybody can develop, share, or even sell your own plug-ins
Plug-ins written by 3rd developers are not required to be made publicly available. The plug-ins have licenses defined by their developers.
The forms class license is BSD, so it does not require that 3rd plug-ins have their source opened.
3rd plug-ins may be distributed or even sold as proprietary, either separately or bundled with the main forms class.
Future plans
Define forms using separate XML files
Take plain HTML templates for form authoring with visual editing programs like DreamWeaver
Cache the definition and output of forms
Drag and drop event processing plug-in
Generic scaffolding plug-in: list and edit dynamic data
Example: insert, list, change and delete database table records
Other plug-ins you may ask
Visual templates only have HTML without special marks, so they do not include PHP code or any template language marks.
A cache engine allows accelerating the form processing, as well the generation of the HTML and Javascript to present the form.
Scaffolding support will allow a sort of data grid editing mode, similar to spreadsheet programs. It will use AJAX to accelerate updating the forms and saving the changes.
Contribution opportunities
Fix and report eventual bugs
Suggest new features
Translate the documentation to other idioms
Develop and share new plug-ins
Spread the word about this project
The class does not provide everything that everybody can possibly want.
There are plenty of business opportunities for developers willing to develop plug-ins for customers with special needs.
The end
Thank you for your time and attention!
Questions?
Send a message to [email protected]
References
Forms class page
http://www.phpclasses.org/formsgeneration
Support forum
http://www.phpclasses.org/discuss/package/1/
Mailing list
http://groups.yahoo.com/group/forms-dev
Mailing list for Portuguese speakers
http://br.groups.yahoo.com/group/forms-pt
Message from Robert Chalmers of Australia recommending the class a lot in the php-general list
http://marc.theaimsgroup.com/?m=92856190403431
PHPClasses site launch message
http://marc.theaimsgroup.com/?m=93020963511392
Smarty concept proposal
http://news.php.net/php.template/186
Click to edit the title text format