Changed at 12 July 07 / 12:54 edit 12 july: changed the code to be eval'd
I ran into a snag with a custom validator. I had a text field, that needed to be filled if a certain checkbox was checked. If that checkbox was not checked, the text field was allowed to be empty. The problem was, there could be any number of these combinations on the one form, so I needed a way to find out from the validator function, which textfield was being checked.
Here's my simplified form:
<?php
$oForm = new FormHandler();
foreach ($aEvents as $iEventId => $sEventName)
{
$oForm->checkBox("Register for {$sEventName}", "register_{$iEventId}");
$oForm->textField("Number of people", "people_{$iEventId}", array(&$this, "checkEvent"));
}
$oForm->flush();
?>
Get the problem? To be able to determine which checkbox to look for, and see whether it is checked, I need to know either the name of the field, so I can split out the event ID, or I need to know the event ID itself.
I've adjusted the validator function in class.Field.php to allow for custom validators to be given parameters (if it's a method).
That turns my textfield into this:
<?php
$oForm->textField("Number of people", "people_{$iEventId}", array(&$this, "checkEvent", $iEventId));
?>
My validator becomes:
<?php
function checkEvent($iNumber, $iEventId)
{
// It's a checkbox, which has a counter added to
// its name, so we need to loop through everything
foreach ($_POST as $sField => $mValue)
{
// If the current field is the checkbox
if (substr($sField, 0, 9) == "register_" &&
substr($sField, 9, strlen($iEventId)) == $iEventId &&
$mValue == 'on')
{
// return whether the number of people
// coming is filled in and numeric
return (!empty($iNumber) && ctype_digit($iNumber));
}
}
// If the checkbox could not be found, it doesn't
// matter what the value is, because the function
// executed onCorrect won't look at this field anyway
return true;
}
?>
To make this possible, I've changed the fields/class.Field.php file in the following manner:
<?php
// Find these lines
// check if the method exists
if(method_exists($this->_sValidator[0], $this->_sValidator[1]))
{
$error = call_user_func(array(&$this->_sValidator[0], $this->_sValidator[1]), trim( $this->getValue() ) );
}