Validating using HTML_QuickForm stuff is slightly more complex than db_dataobject alone:
Before a form element can be validated, a validation rule must be registered, then added to the object.
Below is my code for a simple form that allows the user to enter a MAC address and IP address into the DB:
<?php
require_once("include.php");
require("Rules.php");
echo "Trying this form from scratch...<br />\n";
$host = DB_DataObject::factory('Hosts');
$host->get(1);
$builder = & DB_DataObject_FormBuilder::create($host);
$form = & $builder->getForm();
$form->registerRule("MACRule", NULL, "HTML_QuickForm_Rule_MAC");
$form->registerRule("IPRule", NULL, "HTML_QuickForm_Rule_IP");
$form->addRule("MAC", "Invalid MAC address", "MACRule");
$form->addRule("IP", "Invalid IP address", "IPRule");
if($form->validate() ) {
$form->process(array(&$builder, 'processForm'), false);
echo "<b>{$host->MAC}</b> with IP <b>{$host->IP}</b> was successfully added ";
echo "to the database.<br />\n";
}
else {
echo $form->toHtml();
}
?>
The validate() code looks for each registered Rule and executes its "validate" method, so make sure it's named "validate". The file Rules.php looks as follows:
<?php
require_once("HTML/QuickForm/Rule.php");
class HTML_QuickForm_Rule_MAC extends HTML_QuickForm_Rule
{
var $reg = "/^[0-9A-F][0-9A-F][:]{0,1}[0-9A-F][0-9A-F][:]{0,1}[0-9A-F][0-9A-F][:]{0,1}[0-9A-F][0-9A-F][:]{0,1}[0-9A-F][0-9A-F][:]{0,1}[0-9A-F][0-9A-F]/i";
function validate($mac)
{
$result = preg_match($this->reg,$mac);
if($result) { return true; }
return false;
}
}
class HTML_QuickForm_Rule_IP extends HTML_QuickForm_Rule
{
function validate($ip)
{
include("Net/IPv4.php");
return Net_IPv4::validateIP($ip);
}
}
?>
Important Note: Rules do not actually have to be registered. If you do not have any registerRule() statements, your addRules can look as follows (using the environment above):
$form->addRule("MAC", "Invalid MAC address", "HTML_QuickForm_Rule_MAC");
$form->addRule("IP", "Invalid IP address", "HTML_QuickForm_Rule_IP");
We're manually telling addRule to use the mentioned Classes. I think for Maintain we should probably register all of our rules in an include file somewhere, so we can just call addRule(blah, blah, "RuleName") safely from any form. As long as we don't have duplicate rule names (which I see no reason to have to do) it should work out fine. Registering some rules that have nothing to do with the form doesn't hurt.
Important Note again: For some reason you CAN NOT freeze a form generated via db_dataobject_formbuilder. The next best thing would be to simply make sure the submit button is removed. After processing the code successfully, add the following lines:
$form->removeElement('__submit__');
echo $form->toHtml();