adding zend project folders into old campcaster.

This commit is contained in:
naomiaro 2010-12-07 14:19:27 -05:00
parent 56abfaf28e
commit 7ef0c18b26
4045 changed files with 1054952 additions and 0 deletions

View file

@ -0,0 +1,42 @@
<?php
class patForms_Creator_Definition {
static function create($definition, $object = null) {
$form = patForms::createForm(null, array(
'name' => $definition->name
));
foreach ($definition->elements as $el) {
$element = &$form->createElement($el['name'], $el['type'], null);
if (!empty($el['attributes']['datasource'])) {
$ds = $el['attributes']['datasource'];
unset($el['attributes']['datasource']);
$element->setDatasource(new $ds['name']($ds));
}
// patForms will choke when we try to set attributes that
// don't exist for an element type. So we'll have to ask.
foreach ($el['attributes'] as $name => $value) {
if ($element->hasAttribute($name)) {
$element->setAttribute($name, $value);
}
}
if (isset($el['rules'])) {
foreach ($el['rules'] as $rule) {
$element->addRule(new $rule['type']($rule));
}
}
$form->addElement($element);
}
if (!is_null($object)) {
$form->setValues($object->toArray());
}
if ($definition->autoValidate) {
$form->setAutoValidate($definition->autoValidate);
}
return $form;
}
}

View file

@ -0,0 +1,132 @@
<?php
/**
* patForms Creator Propel
*
* @package patForms
* @subpackage Creator
*/
/**
* Error: could not connect to the database
*/
define( 'PATFORMS_CREATOR_PROPEL_ERROR_NO_CONNECTION', 'patForms:Creator:Propel:01' );
/**
* patForms Creator DB
*
* @access protected
* @package patForms
* @subpackage Creator
* @author Bert Van den Brande <cyruzb@gmail.com>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
*/
class patForms_Creator_Propel extends patForms_Creator
{
private static $creoleTypeMapping = array(
CreoleTypes::BOOLEAN =>'Radio', // BOOLEAN = 1;
CreoleTypes::BIGINT =>'String', // BIGINT = 2;
CreoleTypes::SMALLINT =>'String', // SMALLINT = 3;
CreoleTypes::TINYINT =>'String', // TINYINT = 4;
CreoleTypes::INTEGER =>'String', // INTEGER = 5;
CreoleTypes::CHAR =>'String', // CHAR = 6;
CreoleTypes::VARCHAR =>'String', // VARCHAR = 7;
CreoleTypes::FLOAT =>'String', // FLOAT = 8;
CreoleTypes::DOUBLE =>'String', // DOUBLE = 9;
CreoleTypes::DATE =>'Date', // DATE = 10;
CreoleTypes::TIME =>'String', // TIME = 11;
CreoleTypes::TIMESTAMP =>'Date', // TIMESTAMP = 12;
CreoleTypes::VARBINARY =>'String', // VARBINARY = 13;
CreoleTypes::NUMERIC =>'String', // NUMERIC = 14;
CreoleTypes::BLOB =>'String', // BLOB = 15;
CreoleTypes::CLOB =>'String', // CLOB = 16;
CreoleTypes::TEXT =>'Text', // TEXT = 17;
CreoleTypes::LONGVARCHAR =>'Text', // LONGVARCHAR = 17;
CreoleTypes::DECIMAL =>'String', // DECIMAL = 18;
CreoleTypes::REAL =>'String', // REAL = 19;
CreoleTypes::BINARY =>'String', // BINARY = 20;
CreoleTypes::LONGVARBINARY =>'String', // LONGVARBINARY = 21;
CreoleTypes::YEAR =>'String', // YEAR = 22;
CreoleTypes::ARR =>'String',
CreoleTypes::OTHER =>'String'
);
/**
* Create a form from a propel instance
*
* @access public
* @param mixed $object An instance of a Propel object
* @param array $options Any options the creator may need
* @return object $form The patForms object, or a patError object on failure.
*/
function &create( $object, $options = array() )
{
// Propel stuff
$propel_peer = $object->getPeer();
$propel_mapBuilder = $propel_peer->getMapBuilder(); // Not sure if we're gonna need this one
$propel_tablename = constant(get_class($propel_peer) . '::TABLE_NAME');
$propel_tableMap = $propel_mapBuilder->getDatabaseMap()->getTable($propel_tablename);
// The form
$form =& patForms::createForm( null, array( 'name' => 'patForms_Creator_Form' ) );
$propel_cols = $propel_tableMap->getColumns();
foreach ($propel_cols as $propel_colname => $propel_col) {
// phpName can be altered by editing the schema.xml,
// thus I think, we should lowercase()/ucfirst() this
$propel_colname = strtolower($propel_colname);
$el_displayname = ucFirst($propel_colname);
// this could be omitted of course, but I think, it's a
// convenient way to get more safe request properties
$el_name = $propel_tablename . '[' . $propel_colname . ']';
$el_attr = array(
'edit' => 'yes',
'title' => $el_displayname,
'label' => $el_displayname,
'name' => $el_name,
'description' => $el_displayname
);
//// Obsolete ?
// Parse column info to element type info
//$type_info = $this->parseTypeInfoFromColumn($propel_col);
// Merge extra element attributes
//$el_attr = array_merge( $el_attr, $type_info['attributes'] );
// Is the element required ? Can we retrieve this info from the Column object ?
$el_attr['required'] = 'yes';
// Value: for now we use default to set the value. Is there a better (more correct) way to do this ?
$el_attr['default'] = $object->{'get'.$propel_col->getPhpName()}();
if ($propel_col->isPrimaryKey()) {
$el_type = 'hidden';
} else {
$el_type = self::$creoleTypeMapping[$propel_col->getCreoleType()];
}
$el = &$form->createElement($el_name, $el_type, null);
// patForms will choke when we try to set attributes
// that don't match the element type. So we'll ask.
foreach ($el_attr as $name => $value) {
if ($el->hasAttribute($name)) {
$el->setAttribute($name, $value);
}
}
$form->addElement($el);
}
return $form;
}
// Seems this function will become obsolete if we use the static $creoleTypeMapping
function parseTypeInfoFromColumn ( $column ) {
return array(
'type' => 'String',
'attributes' => array()
);
}
}

View file

@ -0,0 +1,201 @@
<?php
/**
* patForms_Creator_DB examples
*
* patForms_Creator is a subpackage of patForms that provides
* several formbuilder classes that create a form from
* a datasource.
*
* WARNING:
* The Creator subpackage is still in devel state!
*
* @access public
* @package patForms
* @subpackage Examples
* @author Stephan Schmidt <schst@php-tools.net
* @author Sebastian Mordziol <argh@php-tools.net>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
*/
/**
* Main examples prepend file, needed *only* for the examples framework!
*/
//include_once 'patExampleGen/prepend.php';
//$exampleGen->displayHead( 'Example' );
include('include/common.php');
// EXAMPLE START ------------------------------------------------------
/**
* main patForms class
*/
require_once ('patForms.php');
/**
* patErrorManager class
*/
require_once ('patErrorManager.php');
// create the creator :)
$creator = &patForms::createCreator( 'Propel' );
// create the form object from the given propel Object class instance
require_once('model/general/UserProfile.php');
$userProfile = UserProfilePeer::retrieveByPK(1);
$form =& $creator->create( $userProfile );
//$wikipage = WikipagePeer::retrieveByPK('wiki');
//$form =& $creator->create($wikipage);
// create the needed renderer
$renderer =& patForms::createRenderer( "Array" );
// set the renderer
$form->setRenderer( $renderer );
// use auto-validation
$form->setAutoValidate( 'save' );
// serialize the elements
$elements = $form->renderForm();
// ERROR DISPLAY ------------------------------------------------------
if ( $form->isSubmitted() )
{
displayErrors( $form ); // see patExampleGen/customFunctions.php
}
// DISPLAY FORM ------------------------------------------------------
displayForm( $form, $elements ); // see patExampleGen/customFunctions.php
/**
* Takes a patForms object, asks it if there are any validation
* errors and displays them if need be.
*
* NOTE: this is just a helper method for our examples collection,
* so that you may concentrate on the relevant parts of the examples.
* It does in no way represent the way it should be done :)
*
* @access public
* @param object &$form The patForms object to use
*/
function displayErrors( &$form )
{
// get the errors from the form object - if there are none,
// this returns false so it is easy to check if there are any.
$errors = $form->getValidationErrors();
// if there are any errors, display them.
if ( $errors )
{
echo '<div class="piErrors">';
echo ' <div class="piErrorsTitle">Validation failed</div>';
echo ' <div class="piErrorsContent">';
// the errors collection is an associative array with the
// field names as keys, so we go through that.
foreach ( $errors as $elementName => $elementErrors )
{
$element =& $form->getElementByName( $elementName );
// each element can have more than one error - this
// is rare, but can happen so this is an indexed array
// with one error in each row.
foreach ( $elementErrors as $row => $error )
{
echo ' <div class="piError">';
echo ' <b>'.$element->getAttribute( 'label' ).':</b> '.$error['message'].'('.$error['element'].' element error #'.$error['code'].')<br/>';
echo ' </div>';
}
}
echo ' </div>';
echo '</div>';
}
// no errors, tell the world everything is fine
else
{
echo '<div class="piHint">Validation successful.</div>';
}
}
/**
* Displays a standard form from the examples collection when the
* form is rendered via the array renderer. Does not work for any
* other examples.
*
* NOTE: this is just a helper method for our examples collection,
* so that you may concentrate on the relevant parts of the examples.
* It does in no way represent the way it should be done :)
*
* @access public
* @param object &$form The current form object
* @param array $elements The rendered elements from the
* @return
* @see
*/
function displayForm( &$form, $elements )
{
// output the opening form tag
echo $form->serializeStart();
echo "<table>\n";
foreach ( $elements as $element ) {
}
echo "</table>\n";
// display all elements
foreach ( $elements as $element )
{
if (!isset($element['description'])) {
// would choke a warning on hidden fields
// strange enough, we've no $element['type'] for hidden inputs
echo $element['element'] . "\n";
continue;
}
echo '<div style="margin-bottom:8px;">';
echo $element['label']."<br>";
echo "<div>".$element["element"]."</div>";
echo "<i>".$element["description"]."</i><br>";
echo '</div>';
//} else {
//echo "<tr><td>".$element['description']."</td><td>".$element['element']."</td></tr>\n";
//}
}
// submit button, closing form tag
echo '<input type="submit" name="save" value="Save form"/><br><br>';
echo $form->serializeEnd();
// form submitted? display all form values
if ( $form->isSubmitted() ) {
$els =& $form->getElements();
$cnt = count( $els );
echo '<div class="piValues">';
echo ' <div class="piValuesTitle">Submitted form values</div>';
echo ' <div class="piValuesContent">';
echo ' <table cellpadding="2" cellspacing="0" border="0">';
for ( $i = 0; $i < $cnt; $i++ ) {
echo '<tr>';
echo ' <td>'.$els[$i]->getAttribute('label').'</td><td>&nbsp;:&nbsp;</td><td>'.$els[$i]->getValue().'</td>';
echo '</tr>';
}
echo ' </table>';
echo ' </div>';
echo '</div>';
}
}

View file

@ -0,0 +1,70 @@
<?php
class patForms_Datasource_Propel {
private $peername;
private $label;
private $value;
public function __construct($conf) {
$this->peername = $conf['peername'];
$this->label = $conf['label'];
$this->value = $conf['value'];
}
public function getValues() {
$map = call_user_func(array($this->peername, 'getPhpNameMap'));
$c = new Criteria();
$c->clearSelectColumns();
foreach (array($this->label, $this->value) as $arr) {
foreach ($arr['members'] as $member) {
if (is_array($member)) {
foreach ($member as $member) {
$c->addSelectColumn(constant($this->peername . '::' . $map[$member]));
}
} else {
$c->addSelectColumn(constant($this->peername . '::' . $map[$member]));
}
}
}
if (isset($this->label['initial']) OR isset($this->value['initial'])) {
$label = isset($this->label['initial']) ? $this->label['initial'] : '';
$value = isset($this->value['initial']) ? $this->value['initial'] : '';
$result[] = array(
'value' => $value,
'label' => $label
);
}
$rs = AuthorPeer::doSelectStmt($c);
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
while ($rs->next()) {
$row = $rs->getRow();
foreach (array('label', 'value') as $key) {
$arr = $this->$key;
$params = array($arr['mask']);
foreach ($arr['members'] as $member) {
if (is_array($member)) {
foreach ($member as $member) {
$field_name = strtolower($map[$member]); // TODO is this always true?
$params[] = $row[$field_name];
}
} else {
$field_name = strtolower($map[$member]); // TODO is this always true?
$params[] = $row[$field_name];
}
}
$$key = call_user_func_array('sprintf', $params);
$tmp[$key] = $$key;
}
$result[] = $tmp;
}
return $result;
}
}

View file

@ -0,0 +1,122 @@
<?
class patForms_Definition {
private $data = array();
public function __construct($name, $autoValidate = '') {
$this->data['name'] = $name;
$this->data['mtime'] = time();
if ($autoValidate) {
$this->data['autoValidate'] = $autoValidate;
}
}
static public function create($conf) {
// TODO
}
public function __get($name) {
if (isset($this->data[$name])) {
return $this->data[$name];
}
}
// TODO change protocol to addElement(array $element)
public function addElement($name, $type, $attributes = array(), $rules = array()) {
if (is_array($type)) {
extract($type);
}
$this->data['elements'][$name]['name'] = $name;
$this->data['elements'][$name]['type'] = $type;
foreach ($attributes as $key => $value) {
$value = $this->cast($value);
$this->data['elements'][$name]['attributes'][$key] = $value;
}
foreach ($rules as $key => $rule) {
$this->data['elements'][$name]['rules'][$key] = $rule;
}
}
public function load($filename) {
$data = $this->read($filename);
foreach ($data as $key => $value) {
if ($key == 'elements') {
foreach ($value as $name => $element) {
$this->addElement($name, $element);
}
} else {
$this->data[$key] = $this->cast($value);
}
}
}
public function save($filename) {
$this->write($filename, $this->data);
}
protected function read($filename) {
$xml = file_get_contents($filename);
$unserializer = new XML_Unserializer();
$unserializer->unserialize($xml);
return $unserializer->getUnserializedData();
}
protected function write($filename, $data) {
$serializer = new XML_Serializer(array (
'addDecl' => true,
'encoding' => 'ISO-8859-1',
'indent' => ' ',
'rootName' => 'form',
'defaultTagName' => 'tag'
));
$serializer->serialize($data);
$xml = $serializer->getSerializedData();
$fp = fopen($filename, 'w+');
fputs($fp, $xml);
fclose($fp);
}
protected function cast($value) {
return $value;
// seems as if patForms_Element(s) are broken here
// e.g. in patForms_Element_Text::serializeHtmlDefault()
// at line 245 if ( $this->attributes['display'] == 'no' )
// will result to true if the display attribute is set
// to (php boolean) true
// so casting the 'true'/'false' and 'yes'/'no' values
// would break intended behaviour here
if (is_array($value) OR is_bool($value)) {
return $value;
}
if ($value === 'true') {
return true;
}
if ($value === 'false') {
return false;
}
if (preg_match('/^[+-]?[0-9]+$/', $value)) {
settype($value, 'int');
return $value;
}
if (preg_match('/^[+-]?[0-9]*\.[0-9]+$/', $value)) {
settype($value, 'double');
return $value;
}
return $value;
}
}

View file

@ -0,0 +1,165 @@
<?
class patForms_Definition_Propel extends patForms_Definition {
private static $creoleTypeMap = array(
CreoleTypes::BOOLEAN => 'Switch', // BOOLEAN = 1;
CreoleTypes::BIGINT => 'String', // BIGINT = 2;
CreoleTypes::SMALLINT => 'String', // SMALLINT = 3;
CreoleTypes::TINYINT => 'String', // TINYINT = 4;
CreoleTypes::INTEGER => 'String', // INTEGER = 5;
CreoleTypes::CHAR => 'String', // CHAR = 6;
CreoleTypes::VARCHAR => 'String', // VARCHAR = 7;
CreoleTypes::FLOAT => 'String', // FLOAT = 8;
CreoleTypes::DOUBLE => 'String', // DOUBLE = 9;
CreoleTypes::DATE => 'String', // DATE = 10;
CreoleTypes::TIME => 'String', // TIME = 11;
CreoleTypes::TIMESTAMP => 'Date', // TIMESTAMP = 12;
CreoleTypes::VARBINARY => 'String', // VARBINARY = 13;
CreoleTypes::NUMERIC => 'String', // NUMERIC = 14;
CreoleTypes::BLOB => 'Text', // BLOB = 15;
CreoleTypes::CLOB => 'Text', // CLOB = 16;
CreoleTypes::TEXT => 'Text', // TEXT = 17;
CreoleTypes::LONGVARCHAR => 'Text', // LONGVARCHAR = 17;
CreoleTypes::DECIMAL => 'String', // DECIMAL = 18;
CreoleTypes::REAL => 'String', // REAL = 19;
CreoleTypes::BINARY => 'String', // BINARY = 20;
CreoleTypes::LONGVARBINARY => 'Text', // LONGVARBINARY = 21;
CreoleTypes::YEAR => 'String', // YEAR = 22;
CreoleTypes::ARR => 'String',
CreoleTypes::OTHER => 'String'
);
private static $validatorTypeMap = array(
'unique' => null,
'minLength' => 'patForms_Rule_MinLength',
'maxLength' => 'patForms_Rule_MaxLength',
'minValue' => 'patForms_Rule_MinValue',
'maxValue' => 'patForms_Rule_MaxValue',
'match' => 'patForms_Rule_Match',
'notMatch' => 'patForms_Rule_NotMatch',
'required' => null, // will be done by the elements "required" attribute
'validValues' => 'patForms_Rule_ValidValues',
);
/**
* @param array $conf an assoc array of parameters. these are:
* - string name => $name of the propel object class
* - string filename => $filename of the form definition xml file
*/
static public function create($conf) {
extract($conf);
$autoValidate = isset($autoValidate) ? $autoValidate : 'save';
$definition = new patForms_Definition_Propel($name, $autoValidate);
if (0 AND file_exists($filename)) {
// load definition from xml file
$definition->load($filename);
} else {
// populate definition from table map and save it to xml file
$definition = self::populateFromTableMap($definition, $conf);
$definition->save($filename);
}
return $definition;
}
private function populateFromTableMap($definition, $conf) {
extract($conf);
$mapBuilder = call_user_func(array($name . 'Peer', 'getMapBuilder'));
$tablename = constant($name . 'Peer::TABLE_NAME');
$tableMap = $mapBuilder->getDatabaseMap()->getTable($tablename);
$cols = $tableMap->getColumns();
foreach ($cols as $col) {
$phpname = $col->getPhpName();
// this would need a patched version of patForms in order
// to retrieve request vars after having submitted the form
// TODO - ask patForms developers to enable this
// $elementName = $tablename . '[' . $phpname . ']';
$elementName = $phpname;
$elementType = self::$creoleTypeMap[$col->getCreoleType()];
// TODO somehow retrieve element type specific default values?
$elementAttributes = array(
'name' => $elementName,
'title' => $phpname,
'label' => $phpname,
'description' => $phpname,
'edit' => 'yes',
'display' => $col->isPrimaryKey() ? 'no' : 'yes',
// Is the element required?
// TODO Can we retrieve this info from the Column object?
'required' => true,
);
switch ($col->getCreoleType()) {
case CreoleTypes::BOOLEAN: {
$elementAttributes['value'] = 1;
break;
}
case CreoleTypes::DATE: {
// TODO doesn't seem to work for some reason
// $elementAttributes['format'] = 'date';
// $elementAttributes['dateformat'] = 'Ymd';
break;
}
}
if ($col->isForeignKey()) {
$relColname = $col->getRelatedColumnName();
$relTablename = $col->getRelatedTableName();
$relColPhpname =
Propel::getDatabaseMap(constant($relTablename . 'Peer::DATABASE_NAME'))->
getTable($relTablename)->getColumn($relColname)->getPhpname();
$elementAttributes['datasource'] = array (
'name' => 'patForms_Datasource_Propel',
'peername' => $relTablename . 'Peer',
'label' => array(
'initial' => 'Please select one ...',
'members' => array($relColPhpname),
'mask' => '%s',
),
'value' => array(
'members' => array($relColPhpname),
'mask' => '%s',
),
);
$elementType = 'Enum';
}
$rules = array();
if ($col->hasValidators()) {
foreach ($col->getValidators() as $validator) {
$name = $validator->getName();
$type = self::$validatorTypeMap[$name];
if (!is_null($type)) {
$rules[$name] = array (
'table' => $col->getTablename(),
'col' => $col->getColumnName(),
'name' => $name,
'type' => self::$validatorTypeMap[$name],
'value' => $validator->getValue(),
'class' => $validator->getClass(),
'message' => $validator->getMessage(),
);
}
}
}
$definition->addElement($phpname, $elementType, $elementAttributes, $rules);
}
return $definition;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,340 @@
<?php
/**
* patForms rule base class
*
* $Id: Rule.php 1347 2009-12-03 21:06:36Z francois $
*
* @access protected
* @package patForms
* @subpackage Rules
*/
/**
* patForms rule base class
*
* @access protected
* @package patForms
* @subpackage Rules
* @author Stephan Schmidt <schst@php-tools.net>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
* @todo implement javascript helper methods (set a javascript property plus an
* array of keys that will be replaced by the properties of the rule)
*/
class patForms_Rule
{
/**
* time when the rule should be applied
*
* Possible values are:
* -PATFORMS_RULE_BEFORE_VALIDATION
* -PATFORMS_RULE_AFTER_VALIDATION
* -PATFORMS_RULE_BOTH
*
* @access private
* @var integer
*/
var $_time = PATFORMS_RULE_AFTER_VALIDATION;
/**
* script that will be displayed only once
*
* @access private
* @var array
*/
var $globalScript = array();
/**
* script that will be displayed once per instance
*
* @access private
* @var array
*/
var $instanceScript = array();
/**
* properties that have to be replaced in the instance script.
*
* @access private
* @var array
*/
var $scriptPlaceholders = array();
/**
* store the container of the rule
*
* @access private
* @var object
*/
var $container;
/**
* define error codes an messages for each form element
*
* @abstract
* @access private
* @var array
*/
var $validatorErrorCodes = array();
/**
* error code offset for the rule
*
* @abstract
* @access private
*/
var $errorOffset;
/**
* format of the rule
*
* @abstract
* @access private
*/
var $format = 'html';
/**
* name of the rule
*
* @abstract
* @access private
*/
var $ruleName = '';
/**
* Get the time when the rule should be applied.
*
* This has to be defined in the _time property of the rule.
*
* @access public
* @return integer
*/
function getTime()
{
return $this->_time;
}
/**
* create a new rule object
*
* @access public
* @param string id
*/
function patForms_Rule( $id = null )
{
if ( $id === null )
{
$id = uniqid( '' );
}
$this->_id = $id;
}
/**
* set the id for the rule
*
* @access public
* @param string id
*/
function setId( $id )
{
$this->_id = $id;
}
/**
* set the locale, this is needed to update the rule
* translations, that have been passed to the container
* element
*
* @access public
* @param string new locale
* @return boolean
*/
function setLocale( $locale )
{
// rules do not store locale information
if (!patForms::isCustomLocale($locale)) {
return true;
}
$errorMessages = patForms::getCustomLocale($locale, 'Rule::' . $this->getRuleName());
if (is_array($errorMessages)) {
$this->validatorErrorCodes[$locale] = $errorMessages;
}
$this->container->addValidatorErrorCodes( $this->validatorErrorCodes, $this->errorOffset );
return true;
}
/**
* prepare the rule
*
* This method is used to initialize the rule.
* By default it adds it validatorErrorCodes
* to the container and stores a reference to the
* container.
*
* You may extend it in your custom rules, but should always be calling
* this method using:
*
* <code>
* patForms_Rule::prepareRule( $container );
* </code>
*
* @access public
* @param object Either a patForms or patForms_Element object
*/
function prepareRule( &$container )
{
$this->format = $container->getFormat();
$this->container = &$container;
$this->errorOffset = $container->getErrorOffset();
$container->addValidatorErrorCodes( $this->validatorErrorCodes, $this->errorOffset );
return true;
}
/**
* method called by patForms or any patForms_Element to validate the
* element or the form.
*
* @abstract
* @access public
* @param object Either a patForms or patForms_Element object
* @return boolean true, if rule has been applied succesfully, false otherwise
*/
function applyRule( &$container, $type = PATFORMS_RULE_BEFORE_VALIDATION )
{
// your code
}
/**
* addValidationError
*
* @access private
* @param integer $code
* @param array $vars fill named placeholder with values
* @return boolean $result true on success
*/
function addValidationError( $code, $vars = array() )
{
$code= $this->errorOffset + $code;
return $this->container->addValidationError( $code, $vars );
}
/**
* get the name of the rule
*
* By default just return the classname, this is sufficient.
*
* @access public
* @return string
*/
function getRuleName()
{
if (!empty($this->ruleName)) {
return $this->ruleName;
}
return get_class( $this );
}
/**
* get the global javascript of the rule
*
* @access public
* @return string
* @todo Rules need to know the output format
*/
/*
function getGlobalJavascript()
{
if ( isset( $this->globalScript['html'] ) )
{
return $this->globalScript['html'];
}
return '';
}
*/
/**
* get the instance javascript of the rule
*
* @access public
* @return string
*/
/*
function getInstanceJavascript()
{
if ( !isset( $this->instanceScript[$this->format] ) )
{
return false;
}
// get the script for the current format
$script = $this->instanceScript[$this->format];
// always replace the id
$script = str_replace( '[RULE::ID]', $this->_id, $script );
if ( method_exists( $this->container, 'getId' ) )
{
$script = str_replace( '[CONTAINER::ID]', $this->container->getId(), $script );
}
if ( method_exists( $this->container, 'getName' ) )
{
$script = str_replace( '[CONTAINER::NAME]', $this->container->getName(), $script );
}
foreach ( $this->scriptPlaceholders as $placeholder => $property )
{
if ( isset( $this->$property ) )
$script = str_replace( '['.$placeholder.']', $this->$property, $script );
else
$script = str_replace( '['.$placeholder.']', '', $script );
}
return $script;
}
*/
function registerJavascripts(&$form) {
if ($script = $this->getGlobalJavascript()) {
$form->registerGlobalJavascript($this->getRuleName(), $script);
}
if ($script = $this->getInstanceJavascript()) {
$form->registerInstanceJavascript($script);
}
}
function getGlobalJavascript() {
if (isset($this->globalScript[$this->format])) {
return $this->globalScript[$this->format];
}
}
function getInstanceJavascript(){
if (isset($this->instanceScript[$this->format])) {
$script = $this->instanceScript[$this->format];
$script = str_replace('[RULE::ID]', $this->_id, $script);
if (method_exists($this->container, 'getId')) {
$script = str_replace('[CONTAINER::ID]', $this->container->getId(), $script);
}
if (method_exists($this->container, 'getName')) {
$script = str_replace('[CONTAINER::NAME]', $this->container->getName(), $script);
}
foreach ($this->scriptPlaceholders as $placeholder => $property) {
if (isset($this->$property)) {
$script = str_replace('['.$placeholder.']', $this->$property, $script);
} else {
$script = str_replace('['.$placeholder.']', '', $script);
}
}
return $script;
}
}
}

View file

@ -0,0 +1,163 @@
<?php
/**
* patForms Rule Match
*
* This rule matches the field value against a regEx pattern. It successfully
* validates the passed value if the value *does* match the pattern.
*
* @package patForms
* @subpackage Rules
* @author Sven Fuchs <svenfuchs@artweb-design.de>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
*/
class patForms_Rule_Match extends patForms_Rule
{
/**
* script that will be displayed only once
*
* @access private
* @var array
*/
var $globalScript = array(
'html' => "/* patForms::Rule::Match */
function pFRC_Match(field) {
this.field = eval('pfe_' + field);
}
pFRC_Match.prototype.validate = function() {
value = this.field.getValue();
if (!value.match(this.pattern)) {
alert('This is an invalid value.');
}
}
pFRC_Match.prototype.setValue = function(pattern) {
this.pattern = pattern;
}
/* END: patForms::Rule::Match */
"
);
/**
* javascript that will be displayed once per instance
*
* @access private
* @var array
*/
var $instanceScript = array(
'html' => "var pfr_[RULE::ID] = new pFRC_Match('[CONTAINER::NAME]');\n"
);
/**
* properties that have to be replaced in the instance script.
*
* @access private
* @var array
*/
var $scriptPlaceholders = array(
'RULE::SOURCE' => '_source',
);
/**
* name of the rule
*
* @abstract
* @access private
*/
var $ruleName = 'Match';
/**
* define error codes and messages for the rule
*
* @access private
* @var array $validatorErrorCodes
* @todo translate error messages
*/
var $validatorErrorCodes = array(
"C" => array(
1 => "This is an invalid value.",
),
"de" => array(
1 => "Dies ist ein ungültiger Wert.",
),
"fr" => array(
1 => "This is an invalid value.",
)
);
/**
* the regEx pattern
* @access private
* @var string
*/
var $_pattern;
/**
* field id that is used
* @access private
* @var string
*/
var $_field;
private $value = 10;
public function __construct($params) {
parent::__construct();
extract($params);
$this->_pattern = $value;
}
/**
* prepare the rule
*
* @access public
* @param object patForms
*/
function prepareRule(&$container) {
patForms_Rule::prepareRule($container);
$onChange = $container->getAttribute('onchange');
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
$container->setAttribute('onchange', $newHandler . $onChange);
return true;
}
/**
* method called by patForms or any patForms_Element to validate the
* element or the form.
*
* @access public
* @param object patForms form object
*/
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
if (preg_match($this->_pattern, $element->getValue()) != 0){
return true;
}
$this->addValidationError(1);
return false;
}
/**
*
*
* @access public
*/
function registerJavascripts(&$form) {
parent::registerJavascripts($form);
$script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->_pattern);
$form->registerInstanceJavascript($script);
}
}

View file

@ -0,0 +1,161 @@
<?php
/**
* patForms Rule MaxLength
*
* This is just a simple rule, that checks for a required minimum length of a field
*
* @package patForms
* @subpackage Rules
* @author Sven Fuchs <svenfuchs@artweb-design.de>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
*/
class patForms_Rule_MaxLength extends patForms_Rule
{
/**
* script that will be displayed only once
*
* @access private
* @var array
*/
var $globalScript = array(
'html' => "/* patForms::Rule::MaxLength */
function pFRC_MaxLength(field) {
this.field = eval('pfe_' + field);
}
pFRC_MaxLength.prototype.validate = function() {
value = this.field.getValue();
if (value.length > this.value) {
alert('Please enter a value that is max. ' + this.value + ' characters long.');
}
}
pFRC_MaxLength.prototype.setValue = function(value) {
this.value = value;
}
/* END: patForms::Rule::MaxLength */
"
);
/**
* javascript that will be displayed once per instance
*
* @access private
* @var array
*/
var $instanceScript = array(
'html' => "var pfr_[RULE::ID] = new pFRC_MaxLength('[CONTAINER::NAME]');\n"
);
/**
* properties that have to be replaced in the instance script.
*
* @access private
* @var array
*/
var $scriptPlaceholders = array(
'RULE::SOURCE' => '_source',
);
/**
* name of the rule
*
* @abstract
* @access private
*/
var $ruleName = 'MaxLength';
/**
* define error codes and messages for the rule
*
* @access private
* @var array $validatorErrorCodes
* @todo translate error messages
*/
var $validatorErrorCodes = array(
"C" => array(
1 => "Please enter a value that is max. [VALUE] characters long.",
),
"de" => array(
1 => "Bitte geben Sie einen max. [VALUE] Zeichen langen Wert ein.",
),
"fr" => array(
1 => "Please enter a value that is max. [VALUE] characters long.",
)
);
/**
* possible values
* @access private
* @var array
*/
var $_values;
/**
* field id that is used
* @access private
* @var string
*/
var $_field;
private $value = 10;
public function __construct($params) {
parent::__construct();
extract($params);
$this->value = $value;
}
/**
* prepare the rule
*
* @access public
* @param object patForms
*/
function prepareRule(&$container) {
patForms_Rule::prepareRule($container);
$onChange = $container->getAttribute('onchange');
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
$container->setAttribute('onchange', $newHandler . $onChange);
return true;
}
/**
* method called by patForms or any patForms_Element to validate the
* element or the form.
*
* @access public
* @param object patForms form object
*/
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
if (strlen($element->getValue()) <= $this->value) {
return true;
}
$this->addValidationError(1, array('value' => $this->value));
return false;
}
/**
*
*
* @access public
*/
function registerJavascripts(&$form) {
parent::registerJavascripts($form);
$script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->value);
$form->registerInstanceJavascript($script);
}
}

View file

@ -0,0 +1,163 @@
<?php
/**
* patForms Rule MaxValue
*
* This rule simply checks for a required maximum value (number) of a field
*
* @package patForms
* @subpackage Rules
* @author Sven Fuchs <svenfuchs@artweb-design.de>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
*/
class patForms_Rule_MaxValue extends patForms_Rule
{
/**
* script that will be displayed only once
*
* @access private
* @var array
*/
var $globalScript = array(
'html' => "/* patForms::Rule::MaxValue */
function pFRC_MaxValue(field) {
this.field = eval('pfe_' + field);
}
pFRC_MaxValue.prototype.validate = function() {
value = this.field.getValue();
if (parseInt(value) != value) {
alert('Please enter a number that is less or equal to ' + this.value);
}
if (parseInt(value) > this.value) {
alert('Please enter a number that is less or equal to ' + this.value);
}
}
pFRC_MaxValue.prototype.setMaxValue = function(value) {
this.value = value;
}
/* END: patForms::Rule::MaxValue */
"
);
/**
* javascript that will be displayed once per instance
*
* @access private
* @var array
*/
var $instanceScript = array(
'html' => "var pfr_[RULE::ID] = new pFRC_MaxValue('[CONTAINER::NAME]');\n"
);
/**
* properties that have to be replaced in the instance script.
*
* @access private
* @var array
*/
var $scriptPlaceholders = array(
'RULE::SOURCE' => '_source',
);
/**
* name of the rule
*
* @abstract
* @access private
*/
var $ruleName = 'MaxValue';
/**
* define error codes and messages for the rule
*
* @access private
* @var array $validatorErrorCodes
* @todo translate error messages
*/
var $validatorErrorCodes = array(
"C" => array(
1 => "Please enter a number that is less or equal to [VALUE].",
),
"de" => array(
1 => "Bitte geben Sie eine Zahl kleiner oder gleich [VALUE] ein.",
),
"fr" => array(
1 => "Please enter a number that is less or equal to [VALUE].",
)
);
/**
* the regEx pattern
* @access private
* @var string
*/
var $_value;
/**
* field id that is used
* @access private
* @var string
*/
var $_field;
public function __construct($params) {
parent::__construct();
extract($params);
$this->_value = $value;
}
/**
* prepare the rule
*
* @access public
* @param object patForms
*/
function prepareRule(&$container) {
patForms_Rule::prepareRule($container);
$onChange = $container->getAttribute('onchange');
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
$container->setAttribute('onchange', $newHandler . $onChange);
return true;
}
/**
* method called by patForms or any patForms_Element to validate the
* element or the form.
*
* @access public
* @param object patForms form object
*/
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
if (intval($element->getValue()) <= intval($this->_value)){
return true;
}
$this->addValidationError(1, array('value' => $this->_value));
return false;
}
/**
*
*
* @access public
*/
function registerJavascripts(&$form) {
parent::registerJavascripts($form);
$script = sprintf("pfr_%s.setMaxValue(%s);\n", $this->_id, $this->_value);
$form->registerInstanceJavascript($script);
}
}

View file

@ -0,0 +1,161 @@
<?php
/**
* patForms Rule MinLength
*
* This is just a simple rule, that checks for a required minimum length of a field
*
* @package patForms
* @subpackage Rules
* @author Sven Fuchs <svenfuchs@artweb-design.de>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
*/
class patForms_Rule_MinLength extends patForms_Rule
{
/**
* script that will be displayed only once
*
* @access private
* @var array
*/
var $globalScript = array(
'html' => "/* patForms::Rule::MinLength */
function pFRC_MinLength(field) {
this.field = eval('pfe_' + field);
}
pFRC_MinLength.prototype.validate = function() {
value = this.field.getValue();
if (value.length < this.value) {
alert('Please enter a value that is at least ' + this.value + ' characters long.');
}
}
pFRC_MinLength.prototype.setValue = function(value) {
this.value = value;
}
/* END: patForms::Rule::MinLength */
"
);
/**
* javascript that will be displayed once per instance
*
* @access private
* @var array
*/
var $instanceScript = array(
'html' => "var pfr_[RULE::ID] = new pFRC_MinLength('[CONTAINER::NAME]');\n"
);
/**
* properties that have to be replaced in the instance script.
*
* @access private
* @var array
*/
var $scriptPlaceholders = array(
'RULE::SOURCE' => '_source',
);
/**
* name of the rule
*
* @abstract
* @access private
*/
var $ruleName = 'MinLength';
/**
* define error codes and messages for the rule
*
* @access private
* @var array $validatorErrorCodes
* @todo translate error messages
*/
var $validatorErrorCodes = array(
"C" => array(
1 => "Please enter a value that is at least [VALUE] characters long.",
),
"de" => array(
1 => "Bitte geben Sie einen mindestens [VALUE] Zeichen langen Wert ein.",
),
"fr" => array(
1 => "Please enter a value that is at least [VALUE] characters long.",
)
);
/**
* possible values
* @access private
* @var array
*/
var $_values;
/**
* field id that is used
* @access private
* @var string
*/
var $_field;
private $value = 10;
public function __construct($params) {
parent::__construct();
extract($params);
$this->value = $value;
}
/**
* prepare the rule
*
* @access public
* @param object patForms
*/
function prepareRule(&$container) {
patForms_Rule::prepareRule($container);
$onChange = $container->getAttribute('onchange');
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
$container->setAttribute('onchange', $newHandler . $onChange);
return true;
}
/**
* method called by patForms or any patForms_Element to validate the
* element or the form.
*
* @access public
* @param object patForms form object
*/
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
if (strlen($element->getValue()) >= $this->value) {
return true;
}
$this->addValidationError(1, array('value' => $this->value));
return false;
}
/**
*
*
* @access public
*/
function registerJavascripts(&$form) {
parent::registerJavascripts($form);
$script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->value);
$form->registerInstanceJavascript($script);
}
}

View file

@ -0,0 +1,165 @@
<?php
/**
* patForms Rule MinValue
*
* This rule simply checks for a required minimum value (number) of a field
*
* @package patForms
* @subpackage Rules
* @author Sven Fuchs <svenfuchs@artweb-design.de>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
*/
class patForms_Rule_MinValue extends patForms_Rule
{
/**
* script that will be displayed only once
*
* @access private
* @var array
*/
var $globalScript = array(
'html' => "/* patForms::Rule::MinValue */
function pFRC_MinValue(field) {
this.field = eval('pfe_' + field);
}
pFRC_MinValue.prototype.validate = function() {
value = this.field.getValue();
if (parseInt(value) != value) {
alert('Please enter a number that is greater or equal to ' + this.value);
}
if (parseInt(value) < this.value) {
alert('Please enter a number that is greater or equal to ' + this.value);
}
}
pFRC_MinValue.prototype.setMinValue = function(value) {
this.value = value;
}
/* END: patForms::Rule::MinValue */
"
);
/**
* javascript that will be displayed once per instance
*
* @access private
* @var array
*/
var $instanceScript = array(
'html' => "var pfr_[RULE::ID] = new pFRC_MinValue('[CONTAINER::NAME]');\n"
);
/**
* properties that have to be replaced in the instance script.
*
* @access private
* @var array
*/
var $scriptPlaceholders = array(
'RULE::SOURCE' => '_source',
);
/**
* name of the rule
*
* @abstract
* @access private
*/
var $ruleName = 'MinValue';
/**
* define error codes and messages for the rule
*
* @access private
* @var array $validatorErrorCodes
* @todo translate error messages
*/
var $validatorErrorCodes = array(
"C" => array(
1 => "Please enter a number that is greater or equal to [VALUE].",
),
"de" => array(
1 => "Bitte geben Sie eine Zahl größer oder gleich [VALUE] ein.",
),
"fr" => array(
1 => "Please enter a number that is greater or equal to [VALUE].",
)
);
/**
* the regEx pattern
* @access private
* @var string
*/
var $_value;
/**
* field id that is used
* @access private
* @var string
*/
var $_field;
private $value = 10;
public function __construct($params) {
parent::__construct();
extract($params);
$this->_value = $value;
}
/**
* prepare the rule
*
* @access public
* @param object patForms
*/
function prepareRule(&$container) {
patForms_Rule::prepareRule($container);
$onChange = $container->getAttribute('onchange');
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
$container->setAttribute('onchange', $newHandler . $onChange);
return true;
}
/**
* method called by patForms or any patForms_Element to validate the
* element or the form.
*
* @access public
* @param object patForms form object
*/
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
if (intval($element->getValue()) >= intval($this->_value)){
return true;
}
$this->addValidationError(1, array('value' => $this->_value));
return false;
}
/**
*
*
* @access public
*/
function registerJavascripts(&$form) {
parent::registerJavascripts($form);
$script = sprintf("pfr_%s.setMinValue(%s);\n", $this->_id, $this->_value);
$form->registerInstanceJavascript($script);
}
}

View file

@ -0,0 +1,163 @@
<?php
/**
* patForms Rule NotMatch
*
* This rule matches the field value against a regEx pattern. It successfully
* validates the passed value if the value does *not* match the pattern.
*
* @package patForms
* @subpackage Rules
* @author Sven Fuchs <svenfuchs@artweb-design.de>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
*/
class patForms_Rule_NotMatch extends patForms_Rule
{
/**
* script that will be displayed only once
*
* @access private
* @var array
*/
var $globalScript = array(
'html' => "/* patForms::Rule::NotMatch */
function pFRC_NotMatch(field) {
this.field = eval('pfe_' + field);
}
pFRC_NotMatch.prototype.validate = function() {
value = this.field.getValue();
if (value.match(this.pattern)) {
alert('This is an invalid value.');
}
}
pFRC_NotMatch.prototype.setValue = function(pattern) {
this.pattern = pattern;
}
/* END: patForms::Rule::NotMatch */
"
);
/**
* javascript that will be displayed once per instance
*
* @access private
* @var array
*/
var $instanceScript = array(
'html' => "var pfr_[RULE::ID] = new pFRC_NotMatch('[CONTAINER::NAME]');\n"
);
/**
* properties that have to be replaced in the instance script.
*
* @access private
* @var array
*/
var $scriptPlaceholders = array(
'RULE::SOURCE' => '_source',
);
/**
* name of the rule
*
* @abstract
* @access private
*/
var $ruleName = 'NotMatch';
/**
* define error codes and messages for the rule
*
* @access private
* @var array $validatorErrorCodes
* @todo translate error messages
*/
var $validatorErrorCodes = array(
"C" => array(
1 => "This is an invalid value.",
),
"de" => array(
1 => "Dies ist ein ungültiger Wert.",
),
"fr" => array(
1 => "This is an invalid value.",
)
);
/**
* the regEx pattern
* @access private
* @var string
*/
var $_pattern;
/**
* field id that is used
* @access private
* @var string
*/
var $_field;
private $value = 10;
public function __construct($params) {
parent::__construct();
extract($params);
$this->_pattern = $value;
}
/**
* prepare the rule
*
* @access public
* @param object patForms
*/
function prepareRule(&$container) {
patForms_Rule::prepareRule($container);
$onChange = $container->getAttribute('onchange');
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
$container->setAttribute('onchange', $newHandler . $onChange);
return true;
}
/**
* method called by patForms or any patForms_Element to validate the
* element or the form.
*
* @access public
* @param object patForms form object
*/
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
if (preg_match($this->_pattern, $element->getValue()) == 0){
return true;
}
$this->addValidationError(1);
return false;
}
/**
*
*
* @access public
*/
function registerJavascripts(&$form) {
parent::registerJavascripts($form);
$script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->_pattern);
$form->registerInstanceJavascript($script);
}
}

View file

@ -0,0 +1,182 @@
<?php
/**
* patForms Rule ValidValues
*
* This is just a simple rule, that checks for a required minimum length of a field
*
* @package patForms
* @subpackage Rules
* @author Sven Fuchs <svenfuchs@artweb-design.de>
* @license LGPL, see license.txt for details
* @link http://www.php-tools.net
*/
class patForms_Rule_ValidValues extends patForms_Rule
{
/**
* script that will be displayed only once
*
* @access private
* @var array
*/
var $globalScript = array(
'html' => "/* patForms::Rule::ValidValues */
Array.prototype.inArray = function(value) {
var i;
for (i=0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
function pFRC_ValidValue(field) {
this.field = eval('pfe_' + field);
}
pFRC_ValidValue.prototype.validate = function() {
value = this.field.getValue();
for (var i = 0; i < this.values.length; i++) {
if (this.values[i] === value) {
return true;
}
}
var msg = 'Please enter one of the following values: ';
for (var i = 0; i < this.values.length; i++) {
msg = msg + this.values[i];
if (i < this.values.length - 1) {
msg = msg + ', ';
}
}
alert(msg);
}
pFRC_ValidValue.prototype.setValues = function(values) {
this.values = values;
}
/* END: patForms::Rule::ValidValue */
"
);
/**
* javascript that will be displayed once per instance
*
* @access private
* @var array
*/
var $instanceScript = array(
'html' => "var pfr_[RULE::ID] = new pFRC_ValidValue('[CONTAINER::NAME]');\n"
);
/**
* properties that have to be replaced in the instance script.
*
* @access private
* @var array
*/
var $scriptPlaceholders = array(
'RULE::SOURCE' => '_source',
);
/**
* name of the rule
*
* @abstract
* @access private
*/
var $ruleName = 'ValidValue';
/**
* define error codes and messages for the rule
*
* @access private
* @var array $validatorErrorCodes
* @todo translate error messages
*/
var $validatorErrorCodes = array(
"C" => array(
1 => "Please enter one of the following values: [VALUES].",
),
"de" => array(
1 => "Bitte geben Sie einen der folgenden Werte ein: [VALUES].",
),
"fr" => array(
1 => "Please enter one of the following values: [VALUES].",
)
);
/**
* possible values
* @access private
* @var array
*/
var $_values;
/**
* field id that is used
* @access private
* @var string
*/
var $_field;
public function __construct($params) {
parent::__construct();
extract($params);
$this->_values = explode('|', $value);
}
/**
* prepare the rule
*
* @access public
* @param object patForms
*/
function prepareRule(&$container) {
patForms_Rule::prepareRule($container);
$onChange = $container->getAttribute('onchange');
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
$container->setAttribute('onchange', $newHandler . $onChange);
return true;
}
/**
* method called by patForms or any patForms_Element to validate the
* element or the form.
*
* @access public
* @param object patForms form object
*/
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
if (in_array($element->getValue(), $this->_values)) {
return true;
}
$this->addValidationError(1, array('values' => implode(', ', $this->_values)));
return false;
}
/**
*
*
* @access public
*/
function registerJavascripts(&$form) {
parent::registerJavascripts($form);
foreach ($this->_values as $value) {
$values[] = "'$value'";
}
$script = sprintf("pfr_%s.setValues(new Array(%s));\n", $this->_id, implode(', ', $values));
$form->registerInstanceJavascript($script);
}
}

View file

@ -0,0 +1,146 @@
<?php
class patForms_Storage_Propel extends patForms_Storage
{
private $peer;
private $peername;
public function setStorageLocation($peername) {
$this->peer = new $peername();
$this->peername = $peername;
$parts = explode('.', explode('.', $this->peer->getOMClass()));
$this->classname = array_pop($parts);
$this->setPrimaryField('Id');
}
private function getCriteria($values) {
$object = new $this->classname();
//$object->populateFromArray($values); //TODO use a workaround until we'll get phpNamed keys in populateFromArray()
$object = $this->populateObjectFromArray($object, $values);
return $object->buildPkeyCriteria();
}
/**
* get an entry
*
* This tries to find an entry in the storage container
* that matches the current data that has been set in the
* form and populates the form with the data of this
* entry
*
* @access public
* @param object patForms patForms object that should be stored
* @return boolean true on success
*/
public function loadEntry(&$form) {
if (!$object = $this->_entryExists($form->getValues())) {
// entry does not exists (why return an array here??)
return array();
}
$form->setValues($object->toArray());
return true;
}
public function validateEntry(&$form) {
if (!$object = $this->_entryExists($form->getValues())) {
$object = new $this->classname();
}
//$object->populateFromArray($form->getValues()); //TODO use a workaround until we'll get phpNamed keys in populateFromArray()
$object = $this->populateObjectFromArray($object, $form->getValues());
$result = $object->validate();
if ($result !== true) {
$mapBuilder = $this->peer->getMapBuilder();
$dbMap = $mapBuilder->getDatabaseMap();
foreach ($result as $colname => $error) {
list($tablename, $colname) = explode('.', $colname);
$column = $dbMap->getTable($tablename)->getColumn($colname);
$element = $form->getElement($column->getPhpName());
$element->addValidatorErrorCodes(array(
'C' => array(
1 => $error->getMessage() . ' (occured in Storage)',
),
), 1000);
$element->addValidationError(1001);
}
return false;
}
}
/**
* adds an entry to the storage
*
* @param object patForms patForms object that should be stored
* @return boolean true on success
*/
public function _addEntry(&$form) {
$object = new $this->classname();
//$object->populateFromArray($form->getValues()); //TODO use a workaround until we'll get phpNamed keys in populateFromArray()
$object = $this->populateObjectFromArray($object, $form->getValues());
$object->save();
return true;
}
/**
* updates an entry in the storage
*
* @param object patForms patForms object that should be stored
* @return boolean true on success
*/
public function _updateEntry(&$form, $primary) {
$object = $this->_entryExists($form->getValues());
//$object->populateFromArray($form->getValues()); //TODO use a workaround until we'll get phpNamed keys in populateFromArray()
$object = $this->populateObjectFromArray($object, $form->getValues());
$object->save();
return true;
}
/**
* check, whether an entry exists
*
* @access private
* @param array
*/
public function _entryExists($values) {
// This method gets called multiple times, e.g. when an existing
// object gets updated. We'll therefor cache results locally using
// a criteria string representation as hash.
static $objects;
$criteria = $this->getCriteria($values);
$hash = $criteria->toString();
if (isset($objects[$hash])) {
return $objects[$hash];
}
$objects[$hash] = $this->peer->doSelectOne($criteria);
if (empty($objects[$hash])) {
return false;
}
return $objects[$hash];
}
// this method is just a workaround
private function populateObjectFromArray($object, $values) {
foreach (array_keys($object->toArray()) as $key) {
if (array_key_exists($key, $values)) {
$object->{'set' . $key}($values[$key]);
}
}
return $object;
}
}

View file

@ -0,0 +1,94 @@
<patTemplate:tmpl name="page">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>{TITLE}</title>
<style>
body {
font: normal 13px arial;
}
form div.row {
clear: left;
float: left;
margin-bottom: 5px;
}
form label {
float: left !important;
display: block;
width: 100px;
}
form div div {
float: left !important;
margin: 0px 10px 0px 0px;
}
form div.descr {
font-style: italic;
}
form div.buttons {
clear: left;
padding: 5px 0px 0px 100px;
}
form div.errors {
border: solid 1px #666666;
margin-bottom: 25px;
padding-bottom: 10px;
background: #f6f6f6;
}
form div.errors h3 {
background: #666666;
color: #ffffff;
font-size: 14px;
padding: 2px 5px 2px 10px;
margin: 0px;
}
form div.errors p {
padding: 10px 10px 10px 10px;
margin: 0px;
}
form div.errors ul {
margin: 0px;
padding-left: 24px;
}
input, select {
font: normal 12px arial;
}
</style>
</head>
<body>
<patTemplate:tmpl name="form">
{START}
<pattemplate:tmpl name="errors" visibility="hidden">
<div class="errors">
<h3>Validation failed</h3>
<p>Sorry, your input could not be saved for the following reasons:</p>
<ul>
<pattemplate:tmpl name="error">
<li><b>{FIELD}:</b> {MESSAGE}</li>
</pattemplate:tmpl>
</ul>
</div>
</pattemplate:tmpl>
<patTemplate:tmpl name="elements" type="condition" conditionvar="display">
<patTemplate:sub condition="no">
{ELEMENT}
</patTemplate:sub>
<patTemplate:sub condition="__default">
<div class="row">
<label for="{ID}" title="{TITLE}">{LABEL}:</label>
<div>{ELEMENT}</div>
<div class="descr">{DESCRIPTION}</div>
</div>
</patTemplate:sub>
</patTemplate:tmpl>
<div class="buttons">
<input type="submit" name="save" value="Save form"/>
</div>
{END}
</patTemplate:tmpl>
</body>
</html>
</patTemplate:tmpl>

View file

@ -0,0 +1,10 @@
# This first example is tested with a Bookstore project on MySql
# (default setting Sqlite has not been tested)
#
# Additionally, you'll need some data in your tables. In case you
# don't have - here's a mini-dump to get the example running.
INSERT INTO `author` VALUES (1, 'Martin', 'Heidegger');
INSERT INTO `book` VALUES (1, 'Sein und Zeit', '3484701226', NULL, NULL);
INSERT INTO `publisher` VALUES (1, 'Max Niemeyer Verlag');