Skip to content

Instantly share code, notes, and snippets.

@develmaycare
Created April 14, 2012 14:37
Show Gist options
  • Save develmaycare/2384825 to your computer and use it in GitHub Desktop.
Save develmaycare/2384825 to your computer and use it in GitHub Desktop.
Sample Form Class for the Dead Simple Framework
<?php
/*! DeadSimple_Form allows you to work with a form template (created with
PHP) rather than dynamically added fields (as with Zend_Form or HTML_QuickForm).
This is most useful when your favorite form API cannot easily reproduce the
the desired form in a programmatic way.
Two things are required to utilize this class:
1. A script that instantiates and validates the form. A "controller", if you will.
2. A form template. A "view", if you will.
Example controller:
@code
// Set up Zend autoloader. Or use the auto-loader of your choice.
require 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance()->registerNamespace('DeadSimple_');
// Create the form and register elements.
$Form = new DeadSimple_Form('example-form.tpl.php');
$Form->addElements('fname, lname, city, state');
$Form->setIgnore('submit');
// Set up validation rules. You can use DeadSimple or Zend validators.
$Form->addRule('NotEmpty','city');
$Form->addRule('EmailAddressString','email');
// Set options for lookup elements.
$Form->setOptions('state',array('ne' => 'Nebraska','ia' => 'Iowa', 'sd' => 'South Dakota'));
// Validate the form.
if ($Form->isValid($_POST))
{
$values = $Form->getValues();
// Do something with the values ...
return;
}
// Output the form.
print $Form;
@endcode
Example template:
@code
<form action="example.php" method="post">
<p class="inline">
<b>Name: </b>
<input id="fname" type="text" name="fname" value="<?=$Form->fname?>" />
<label for="fname" class="under">first</label>
</p>
<p class="inline">
<input id="lname" type="text" name="lname" value="<?=$Form->lname?>" />
<label for="lname" class="under">last</label>
</p>
<br clear="all" />
<p>
<label>Email:<input class="<?=$Form->email->class?>" id="city" type="text" name="email" value="<?=$Form->email?>" /></label>
<span class="error"><?= $Form->email->error ?></span>
</p>
<p>
<label>City:<input class="<?=$Form->city->class?>" id="city" type="text" name="city" value="<?=$Form->city?>" /></label>
<span class="error"><?= $Form->city->error ?></span>
</p>
<p>
<label for="state">state</label>
<select id="state" name="state">
<? foreach ($Form->state->getOptions() as $Option): ?>
<option value="<?=$Option->value?>"><?=$Option->label?></option>
<? endforeach ?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Submit" />
</p>
</form>
@endcode
*/
class DeadSimple_Form {
/* Properties */
//! An array of element names.
protected $_elements = array();
//! An array of validation messages. The key is the element name, and the value is the message.
protected $_errors = array();
//! An array of elements to be omitted when exporting element values.
protected $_ignored_elements = array();
//! An array of validation rule objects.
protected $_rules = array();
//! Template file to use for the form.
protected $_template = NULL;
/* Methods */
/*! Instantiate the form.
@param template Path to the template file.
@param values Initialize element values.
*/
public function __construct($template,$values=NULL)
{
if (!is_file($template))
{
trigger_error("$template file does not exist.",E_USER_WARNING);
return;
}
$this->_template = $template;
if (is_array($values))
{
foreach ($values as $k => $v) { $this->_importValue($k,$v); }
}
} # __constructor()
/*! Convert the Form to an HTML string. See toHtml().
*/
public function __toString()
{
return $this->toHtml();
} # __toString()
/*! Import a value and create an element object.
@param name Name of the element.
@param value Value of the element.
*/
protected function _importValue ($name,$value)
{
if ('_' == $name{0})
{
//! @todo Throw exception if $name starts with _. trigger_error("Field names cannot begin with an underscore.",E_USER_NOTICE);
return;
}
if (isset($this->$name)) { return; }
$this->$name = new DeadSimple_Form_Element($name,$value);
$this->_elements[] = $name;
} # _importValue
/*! Register an element that is not otherwise created by addFilter(),
addRule(), isValid(), etc.
@param element The element name.
@param value Initial value, if any.
@retval object
@return Returns the Reform_Form_Element object that represents the element.
*/
public function addElement($element,$value=NULL)
{
$this->_importValue($element,$value);
return $this->$element;
} # addElement()
/*! Add a bunch of elements at once.
@param elements Separate each element with a coma or an associative array
where the element name is the key and the element value is the value.
@fluent
*/
public function addElements($elements)
{
if (is_array($elements))
{
foreach ($elements as $k => $v) { $this->addElement($k,$v); }
return;
}
foreach (func_get_args() as $element) { $this->addElement($element); }
return $this;
} # addElements()
/*! Add an input filter to an element.
@param filter Name of the filter.
@param element Name of the form element to be validated.
@param extra Any extra argument to be given to the filter.
@retval object
@retval Returns the filter object.
*/
public function addFilter($filter,$element,$extra=NULL)
{
$this->_importValue($element,NULL);
return $this->$element->addFilter($filter,$extra);
} # addFilter()
/*! Add a validation rule to an element.
@param rule Name of the validation rule.
@param element Name of the form element to be validated.
@param extra Any extra argument associated with the rule.
@param message The message to display when validation fails.
@retval object
@retval Returns the validation object.
*/
public function addRule ($rule,$element,$extra=NULL,$message=NULL)
{
$this->_importValue($element,NULL);
return $this->$element->addRule($rule,$extra,$message);
} # addRule()
/*! Get form elements.
@retval array
@return Returns an array of element objects.
*/
public function getElements()
{
$elements = array();
foreach ($this->_elements as $element_name)
{
if (!is_object($this->$element_name)) { continue; }
$elements[$element_name] = $this->$element_name;
}
return $elements;
} # getElements()
/*! Get validation error messages.
@retval array
@return Returns error messages.
@note This array may be empty. See hasErrors().
*/
public function getErrors()
{
return $this->_errors;
} # getErrors()
/*! Get submitted values.
@retval array
@return Returns an array of submitted values.
*/
public function getValues()
{
$values = array();
foreach ($this->getElements() as $element_name => $Element)
{
if (isset($this->_ignored_elements[$element_name])) { continue; }
$values[$element_name] = $Element->getValue();
}
return $values;
} # getValue()
/*! Get submitted value as an object.
@param class Optional class name to use instead of creating a standard class.
@retval object
@return Returns submitted values as an object. See getValues().
*/
public function getValuesAsObject($class=NULL)
{
if (empty($class)) { $class = 'StdClass'; }
$Obj = new $class();
foreach ($this->getValues() as $k => $v) { $Obj->$k = $v; }
return $Obj;
} # getValuesAsObject()
/*! Parse the values into a PHP template.
@param path Path to the template.
*/
public function getValuesAsOutput($path)
{
if (!is_file($path))
{
throw new DeadSimple_Form_Exception('%s template does not exist.',$path);
}
$Message = $this->getValuesAsObject();
$output = '';
ob_start();
include $path;
$output = ob_get_contents();
ob_end_clean();
return $output;
} # getValuesAsOutput()
/*! Determine whether the form has error messages.
@retval bool
@return Returns TRUE if form has encountered a validation error.
*/
public function hasErrors()
{
if (count($this->_errors) > 0) { return TRUE; }
return FALSE;
} # hasErrors()
/*! Check to see if form input validates.
@param input An array or object with input values.
@retval bool
@return Returns TRUE if the form validates.
*/
public function isValid($input=NULL)
{
$values = array();
if (is_object($input)) { $values = get_object_vars($input); }
else if (is_array($input)) { $values = $input; }
else { return FALSE; }
if (0 == count($values)) { return FALSE; }
$validates = TRUE;
foreach ($values as $k => $v)
{
$this->_importValue($k,$v);
if (!$this->$k->isValid($v))
{
$this->_errors[$k] = $this->$k->error;
$validates = FALSE;
}
}
return $validates;
} # isValid()
/*! Ignore on or more fields when using getValues().
@param ignore A single element name or an array of element names.
@fluent
*/
public function setIgnore($ignore)
{
if (is_string($ignore)) { $this->_ignored_elements[$ignore] = TRUE; }
else if (is_array($ignore))
{
foreach ($ignore as $element) { $this->_ignored_elements[$element] = TRUE; }
}
else { /* do nothing */ }
return $this;
} # setIgnore()
/*! Set the options for a select, radio group, or checkboxes element.
@param element Name of the element.
@param options An array of value/label pairs.
@fluent
*/
public function setOptions ($element,$options)
{
$this->_importValue($element,NULL);
$this->$element->setOptions($options);
return $this;
} # setOptions()
/*! Converts the form to HTML.
@retval string
@return Returns the HTML for the form.
*/
public function toHtml ()
{
$Form = $this;
ob_start();
include $this->_template;
$html = ob_get_contents();
ob_end_clean();
return $html;
} # toHtml()
} # DeadSimple_Form
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment