Class: MailForm
- Package: saf.MailForm
- Author: John Luxford <lux@simian.ca>
- Copyright: Copyright (C) 2001-2003, Simian Systems Inc.
- License: http://www.sitellite.org/index/license Simian Open Software License
- Version: 4.0, 2004-01-29, $Id: MailForm.php,v 1.17 2008/03/03 17:15:47 lux Exp $
- Access: public
MailForm provides methods for generating, validating, and handling web
forms. Forms can be handled automatically (sent to an email address), or handled
using "action files". Action files are passed to the handle () method, and can be
used to do anything you want to the form values. MailForm will generate forms
for you, using a basic HTML tabled layout, which is okay for most applications,
or you can have complete visual customization through form templates. MailForm
also exposes an EasyText tag, which makes it much quicker to create fully
validating forms in minutes.
New in 2.0:
- 16 widgets, including date and time widgets, a directory listing widget, and more.
- 11 different validation rules, including a regular expression rule, cross
form widget comparisons (good for password verification widgets), and calling
to pre-defined functions.
- Many speed improvements, such as dynamic loading of widgets, so your form
only loads the necessary widgets.
- MailForm 2.0 is a complete rewrite, which has a much cleaner API, although it
is not backward compatible with 1.0, other than through its EasyText tag.
Widget Types:
- checkbox
- date
- datetime
- dirlist
- file
- hidden
- image
- multiple (multi-line select box)
- password
- radio
- reset
- select
- submit
- text
- textarea
- time
Validation Rules:
- is "value"
- contains "some value"
- regex "some regex"
- equals "anotherfield"
- not empty
- length "6+" (eg: 6, 6+, 6-12, 12-)
- gt "value"
- ge "value"
- lt "value"
- le "value"
- func "func_name" (or function "func_name")
Miscellaneous:
- Do not use underscores (_) in the naming of complex widgets (ie. the datetime
widget).
New in 2.2:
- Added an 'Extra' parameter to the EasyText =MailForm tag parameter list, so
that the File widget can be used without having to resort to coding the form
in PHP instead.
- Fixed a bug in the EasyText() method, where the value of the Email property
wasn't being passed on.
New in 2.4:
- Changed a reference to "$GLOBALS['PHP_SELF']" to "global $_SERVER; $_SERVER['PHP_SELF']"
so that it works with register_globals off.
- Added File widgets to the list of widgets skipped on the isset() condition in invalid(),
because some browsers don't send file fields at all if there is no file. This may inhibit
file field validation, but it's necessary due to inconsistencies across browsers.
New in 2.6:
- Moved the validation layer into the Widget level. See saf.MailForm.Widget and
saf.MailForm.Rule for more info.
- Added a template example to the DocReader docs below.
New in 2.8:
- Fixed a bug in getValues() that caused the $vars passed to a validation function
to be blank.
- Fixed EasyText() to use the new addRule() method instead of validation(), and
added the ability to include multiple rules for the same widget through EasyText()
using commas as separators.
- Added a $submitted property which is used by setValues() to keep an accurate
reading on widgets whose $passover_isset property is set to true.
New in 3.0:
- Added an $_attrs property and three new methods, attr(), unsetAttr(), and getAttrs().
- Deprecated the $extra property in favour of the new property and methods just
added.
- Improved the email output formatting in handle().
New in 3.2:
- Deprecated the handle() method in favour of a setHandler(), run(), and onSubmit()
methods. These methods make it easier to subclass MailForm to unify the
location of the form definition and handling.
- Added $sendTo, $sendFrom, $sendExtra, $screenReply, and $handler support
properties to the new methods.
- Added a parseSettings() method, which makes it much easier to create new
forms.
- getValues() and invalid() now do not use a passed $cgi object, and instead
both rely on a global $cgi object, which is set automatically in the Sitellite
Content Server, Content Manager, and the init.php script in SAF itself, so
it's reasonable to assume it will be available. This doesn't affect code
that still passes the object to invalid(), and the parameter was deprecated
in getValues() already anyway.
- getValues() now uses a new property called $uploadFiles, which tells it to
upload files from file widgets for you automatically. This breaks backward
compatibility as a default, but you can pass a false value to achieve the
old behaviour.
New in 3.4:
- Added makeAssoc() and rememberFields() methods, for use with the Sitellite
Content Server form API.
- Added a $title property, which will show in a top-level header above the form
if provided.
- Added a global formdata_get() function which returns a key/value list from
the global $formdata array defined in the application property files.
- Added a $uploadFile parameter to run(), which allows finer control over
file upload handling.
New in 3.6:
- Removed the EasyText() and EasyTextInit() methods.
- Removed the saf.MailForm.Wizard package, since SCS now provides a more
flexible, elegant, and clean, and less buggy way of accomplishing the
same effect.
- Removed the EasyText widget.
- Added the ability to report all invalid rules at once, instead of just one.
However, just one is still the default.
New in 3.8:
- Added the ability to call addWidget() by specifying the type as a loader path
to an alternate location. This does not affect backward compatibility in
any way.
- Added the ability to call addWidget () by passing a widget object as the
$type parameter.
New in 4.0:
- FormHelp ins now integrated into MailForm. In settings.php, you can
specify 'formhelp = yes' under [Form] and 'formhelp = Message' under
any widget and the display of it is automatic.
Usage Example
<?php
<?php
$form = new MailForm;
$form->template = 'mf2template.spt';
$form->message = 'Please take a moment to fill out our form.';
// old way to set attributes
//$form->extra = 'enctype="multipart/form-data"';
// new way to set attributes
$form->attr ('enctype', 'multipart/form-data');
// build the form
// standard usage:
$form->addWidget ('text', 'username');
$form->widgets['username']->display_value = 'Username (min. 6 chars)';
$form->widgets['username']->addRule ('length "6-24"', 'Your username must be between 6 and 24 characters in length. Please fix this to continue.');
// or if you prefer:
$password =& $form->addWidget ('password', 'password');
$password->addRule ('length "6-24"', 'Your password must be between 6 and 24 characters in length. Please fix this to continue.');
$verify =& $form->addWidget ('password', 'verify');
$verify->display_value = 'Verify Password';
$verify->addRule ('equals "password"', 'Your passwords did not match. Please fix this to continue.');
$form->addWidget ('text', 'firstname');
$form->widgets['firstname']->validation ('not empty');
$form->addWidget ('text', 'lastname');
$form->widgets['lastname']->validation ('not empty');
$province =& $form->addWidget ('select', 'province');
$province->setValues (array (
'BC' => 'British Columbia',
'MB' => 'Manitoba',
'ON' => 'Ontario',
));
$province->default_value = 'MB';
// the new 'dirlist' widget type
$dlist =& $form->addWidget ('dirlist', 'dltest');
$dlist->directory = 'pix';
$dlist->extensions = array ('jpg', 'gif', 'png');
// the new 'date' widget type
$form->addWidget ('date', 'birth-date');
$form->widgets['birth-date']->display_value = 'Birth Date';
$textarea =& $form->addWidget ('textarea', 'comments');
$textarea->setValue ('hello world!');
$textarea->addRule ('not empty', 'You must enter a comment. Please fix this to continue.');
$send =& $form->addWidget ('submit', 'send');
$send->setValues ('Submit!');
if ($form->invalid ($cgi)) {
// form is invalid or has not been set yet
$form->setValues ($cgi, $invalid_field);
echo $form->show ('inc/html/formtemplate.spt');
} else {
// handle submitted form
if (! $form->handle ('lux@simian.ca', 'Mail Form')) {
echo 'Error: ' . $form->error_message;
}
}
?>
-----
inc/html/formtemplate.spt (Note: Replace ** with { and }):
<form method="**mailform_method**" action="**mailform_action**" **mailform_extra**>
<p>**mailform_message**</p>
<p>Username<br />**username**</p>
<p>Password<br />**password**</p>
<p>Verify Password<br />**verify**</p>
<p>First Name<br />**firstname**</p>
<p>Last Name<br />**lastname**</p>
<p>Province<br />**province**</p>
<p>Pick an image<br />**dltest**</p>
<p>Birthday<br />**birth-date**</p>
<p>Comments<br />**comments**</p>
<p>**send**</p>
</form>
?>
Return to Top
Properties
$invalid_field = ''
Contains the name of the widget that did not validate during
the last call to the invalid () method.
$method
The value of the method attribute of the HTML form tag.
$method is actually an alias for $_attrs['method'].
$action
The value of the action attribute of the HTML form tag.
$action is actually an alias for $_attrs['action'].
$widgets = array ()
An array of form widgets.
$template
The optional template file or data used to customize the look
of the form.
$title
The title to be displayed at the top of the form.
$message
The initial message to be displayed at the top of the form.
$extra
A way to pass extra parameters to the HTML form tag, for
example 'enctype="multipart/formdata"'. Notice: This property is
deprecated in favour of the $_attrs list and the attr() and unset()
methods.
$error_message
Contains the message from any internal errors.
$error_mode = 'single'
Determines the way in which error messages are displayed.
The default ('single') is to display the error message for the first
invalid field only. The other ('all') is to display a list of all
invalid fields with their corresponding error messages. Please note
that $error_mode 'all' assumes that a custom error message is provided
for every rule.
$invalid = array ()
A list of all invalid fields in the form, and their corresponding
error messages.
$submitted = false
Contains a true or false value as to whether the form has been
submitted successfully or not. An invalid form will contain false.
This value is used internally by the setValues() method.
$name
The name of this form. Optional. $name is actually an alias
for $_attrs['name'].
$_attrs = array ()
This contains a list of attributes of the HTML form tag.
$sendTo
The email address to send the form to in the default handler.
$sendFrom = ''
The email address to send the form from in the default handler.
$sendExtra = ''
Any extra parameters for the mail() function in the default handler.
$sendSubject = 'Mail Form'
The subject line of the email to send from the default handler.
$screenReply = 'Thank you. Your form has been sent.'
The response to return upon a successfully submitted form in the
default handler. Defaults to "Thank you. Your form has been sent."
$handler
The function or object method to use to handle the submitted form.
This function or method will be called by the run() method. Use the
setHandler() method to change this setting.
$uploadFiles = true
Whether to upload files automatically or to leave them for a custom
saving mechanism.
$verify_sender = false
Whether to verify the REQUEST_METHOD and HTTP_REFERER headers to make
it more difficult (although not impossible) for spammers to abuse your
form. Note that this can be enabled in a form's settings file under
the [Form] block via: verify_sender = yes
$clean_input = false
Whether to strip all HTML and PHP tags/code from all input parameters.
This is off by default because it would break forms with the Xed editor
by default, so it must be enabled as needed. Note that this can be
enabled in a form's settings file under the [Form] block via:
clean_input = yes
$blacklist = true
Whether to verify the remote address of the form submitter against
a list of invalid IP addresses in the database table
sitellite_form_blacklist so as to prevent repeated abuse from a single
source.
$verify_session = true
Whether to verify that the submitter can accept session data, which
helps ensure they are a legitimate human user. Passing session
verification requires cookies to be enabled for the submitter, which
may help prevent abuse in combination with the other abuse-prevention
techniques because a spambot may ignore the cookie, however this
restricts forms for legitimate visitors who have cookies disabled
in their browser (only a very small number of users disable cookies,
but some do). To disable for a single form, add verify_session = no
to its settings.php form.
$autosave = false
Whether this form should tie into Sitellite's autosave capabilities.
Please note that the autosave handler is only available to authenticated
users and not to anonymous forms.
Return to Top
Methods
MailForm ($action = '', $method = 'post')
Constructor Method. Action will be set to $PHP_SELF if it
is empty, unless a global $site object is defined in which case the
action with be $site->url . $PHP_SELF.
&addWidget ($type, $name)
- Access: public
- Return: object reference
Adds another widget to the form. If the $type is specified as
a loader path, it will import from the proper location outside of
saf.MailForm.Widget.*, and if you send an object as the $type value
addWidget() will use that object as the widget (so make sure it is one!),
as of version 3.8.
invalid ()
- Access: public
- Return: boolean
Validates the form values against a global $cgi object. Used in
the logic of "if the form is invalid then...". Also sets an internal
$invalid_field property. Returns true if the form is invalid or has not
been filled out yet. If the form passes (false returned), it also sets
the $submitted value to true.
setValues ($cgi, $invalid = false)
Sets the values of the form widgets from a provided CGI object.
The second parameter is deprecated.
show ($template = '')
- Access: public
- Return: string
Generates the HTML form. You can provide an optional template
to customize the look of the form. Template directives (ie. ##field##)
must be provided for each form widget, as well as ##mailform_action## and
##mailform_method##, which correspond to the action and method attributes
of the HTML form tag.
getValues ()
- Access: public
- Return: associative array
Returns the form values as an associative array. If $uploadFiles
is set to true, it will return the saved path or false for file widgets,
otherwise it will return the saf.CGI.UploadedFile object and not act
on the object for you.
setHandler ($func)
Sets the function to use to handle the output of the current form.
To specify a method of an object, pass it an array with an object reference
as the first element and the method name as the second. The default handler
is the internal onSubmit(). The handler is called using call_user_func()
in the run() method.
run ($uploadFiles = true)
- Access: public
- Return: string
Runs the form and returns either the rendered form or the output
of the handler function. $uploadFiles can be set to false to cause the
getValues() method not to call move() on File widgets. This is useful
for situations when you need to do something other than simply save the
file to a predetermined folder. Please note: The $uploadFiles parameter
is deprecated in favour of the $uploadFiles property of the MailForm
class. This allows the setting to be managed via a settings.php file.
onSubmit ($vals)
- Access: public
- Return: string
This is the default handler function. It is called via run()
and can be overridden via subclassing.
handle ($email, $subject = 'Mail Form', $from_field = '', $extra = '')
- Access: public
- Return: boolean
Note: Deprecated in favour of the setHandler() and run() methods
and subclassing. Handles the form, once it has been satisfactorily completed.
If the first parameter points to a file (ie. 'inc/forms/contact.php'), it will
use that file as an "action file" to handle the form. Otherwise, the first
parameter must be an email address, as handle () will simply send an email
of the form contents to the specified email address. Note: Extra will be
passed to the PHP mail () function as a fourth parameter, or can be used for
any purpose you'd like in an action file.
formatEmail ($vals)
parseSettings ($file)
- Access: public
- Return: boolean
Parses the specified file using the parse_ini_file()
function. Sections in the file correspond to the names of
widgets you wish to create, in addition to a [Form] section
that sets properties for the form itself. The values in
each section correspond to properties or methods of the
widgets. This method can be used to simplify the process
of defining and customizing a form.
&createWidget ($name, $data)
Creates a widget from a name and an array, usually taken from a parsed
settings.php (ini formatted) file.
makeAssoc ($list)
- Access: public
- Return: associative array
Takes a non-associative array and creates an associative array
out of its values. This is used to send non-associative arrays to the
setValues() method of the Widget objects.
rememberFields ($list)
Takes a non-associative array listing the names of each field
from $cgi you want to "remember", and creates hidden fields for each
of them, so you don't have to hard-code lists of hidden fields in
multi-screen forms.
attr ($key, $value = false)
- Access: public
- Return: string
This is the accessor method for setting and getting the value of
any attribute of the form tag, including 'method' and 'action'. This will
replace the $extra property, which is henceforth deprecated. If you call
this method and provide no $value, you are using it as a 'getter', as in
you are getting the current value. If you provide a value, the new value
will be set, so you are acting as a 'setter'. If you simply specify that
the $value be true, then it will appear filled with its own name (useful
for things like the checked="checked" attribute of a checkbox input field,
even though this isn't a checkbox field).
unsetAttr ($key)
- Access: public
- Return: string
Use this method to remove an attribute from the form tag
attribute list. Use this instead of passing a false value to attr(),
because a false value essentially means "return the current value"
in that method. This method returns the old value of the attribute
being unset.
getAttrs ()
- Access: public
- Return: string
Returns a list of all of the attributes of this object's form tag
in a string ready to be concatenated into the actual rendered tag output.
verifyRequestMethod ()
verifyReferer ()
Return to Top