begin process at 2012 05 27 21:23:25
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Formulaires

 > FORM, ORM POUR FORMULAIRE

FORM, ORM POUR FORMULAIRE


 Description

Bonjour tout le monde, si je poste aujourd'hui c'est pour vous présenter fORM.

fORM est une class php5 qui a pour but de faciliter la gestion de formulaires pour le web. En définissant à l'avance la structure des données à récupérer, il devient facile d'automatiser les tâches plus ou moins courrantes et récurantes (validation, affichage,...).

Création et définition d'un formulaire

Pour créer un nouveau formulaire il suffit de créer une nouvelle class qui étend fORM. Prenons l'exemple d'un formulaire de contact :

class Form_Contact extends fORM
{
    protected function setDefinition()
    {
        // Définition du formulaire ici
    }
}

La méthode protected setDefinition vous permet de définir la structure des données du formulaire. Nous allons donc nous en servir en commençant par ajouter les champs lastname, firstname, email :

class Form_Contact extends fORM
{
    protected function setDefinition()
    {
        $this->hasOne('lastname');
        $this->hasOne('firstname');
        $this->hasOne('email');
    }
}

Nous avons donc ajouté nos trois champs à l'aide de la méthode hasOne. Un contact pourraît avoir plusieurs adresse email, nous alons modifier notre formulaire pour permettre la récupération de plusieurs adresses :

class Form_Contact extends fORM
{
    protected function setDefinition()
    {
        $this->hasOne('lastname');
        $this->hasOne('firstname');
        $this->hasMany('email');
    }
}

Peut-être serait-il judicieux de limiter le nombre d'adresses à... disons 5 :

class Form_Contact extends fORM
{
    protected function setDefinition()
    {
        $this->hasOne('lastname');
        $this->hasOne('firstname');
        $email = $this->hasMany('email');
        $email->hasLimit(5);
    }
}

Vous noterez que si nous définissons la limite manuellement nous pouvons aussi bien utiliser hasOne que hasMany.

Compliquons un peu les choses avec un formulaire d'envois à des amis :

class Form_Send2Friends extends fORM
{
    protected function setDefinition()
    {
        $this->hasOne('lastname');
        $this->hasOne('firstname');
        $this->hasMany('email');
        $this->hasOne('message');
        $friend = $this->hasMany('friend');
        $friend->hasOne('lastname');
        $friend->hasOne('firstname');
        $friend->hasMany('email');
    }
}

Ce qui saute tout de suite aux yeux c'est que notre formulaire est composé des même champs que le formulaire de contact. Nous y avons simplement ajouté un champs message ainsi qu'un "noeud" friend ayant lui aussi la même composition que le formulaire de contact. Nous allons pouvoir simplifier tout ça :

class Form_Send2Friends extends Form_Contact
{
    protected function setDefinition()
    {
     parent::setDefinition();
        $this->hasOne('message');
        $this->hasMany('friend', new Form_Contact);
    }
}

C'est quand même bien pratique est nettement plus clair ainsi. En étandant la class Form_Contact tout en appelant sa définition (parent::setDefinition()), nous héritons de toutes ses propriétés auxquels nous pouvons ajouter de nouvelles.
Vous remarquerez que nous pouvons aussi passer un objet fORM en argument des fonction hasOne et hasMany afin de combiner et réutiliser facilement des formulaires existant.


Utilisation d'un formulaire

Pour remplir notre formulaire nous alons utiliser la méthode fill :

$form  =   new Form_Send2Friend;
$form->fill($_POST);

pour en récupérer les valeurs nous utiliserons la méthode value :

$form->value();

fORM implémente les interface Iterator et ArrayAccess permettant de parcourir notre formulaire comme un simple array. Nous récupérons toujours un objet fORM ce qui nous permet de modifier, supprimer, ajouter, valider... tout ou partie de notre formulaire :

// retournera toutes les valeurs de notre formulaire
$form->value();

// retournera la valeur du champs friend[0][email]
$form['friend'][0]['email']->vali date();

// ajoute une adresse email au friend 0
$form['friend'][0]['email'][] = 'cahnory@gmail.c om';

// affichera tous les valeurs de friend
foreach($form['friend'] as $friend) {
echo $friend->value().'<br />';
}

Chaque objet fORM dispose de plusieurs méthodes publiques :
clear
data
fill
isParent
length
limit
name
paren t
validate
value

La description de chaqu'une d'entre elle est présente dans la source de la class mais il est, pour la plupart, facil d'imaginer à quoi elles sont destinées.

Une de ces méthodes qui doit attiser les curiosité est sans doute la méthode validate. Chaque fORM peut décider de comment il sera validé à l'aide de la méthode validateValue qui doit retourner une valeur boolean.
Prenons le cas courant de l'adresse email. Nous allons créer un objet Field_Email comme ceci :

class Field_Email extends fORM
{
    protected function validateValue($value)
    {
        return filter_var($value, FILTER_VALIDATE_EMAIL);
    }
}

Je ne reviens pas sur la méthode de validation, c'est un problème générique qui ne manque pas d'explication sur le net. Nous alons maintenant utiliser ce nouvel objet dans notre formulaire de contact :

class Form_Contact extends fORM
{
    protected function setDefinition()
    {
        $this->hasOne('lastname');
        $this->hasOne('firstname');
        $this->hasMany('email', new Field_Email);
    }
}

Notre champs email n'est plus un simple objet fORM mais un objet Field_Email et utilisera donc la fonction de validation de Field_Email.

Et l'affichage dans tout ça ?

L'affichage n'est pas quelque chose de propre aux formulaires. En grande majorité réalisé en html, l'affichage pourraît très bien se faire dans d'autre format et pour cette raison il n'est pas pris en charge par fORM... c'est là qu'intervient les méthodes hasData et data.
La méthode protected hasData va vous permettre de définir des données qui ne sont pas spécifiques aux formulaires mais qui n'en sont pas moins utiles :

class Form_Send2Friends extends Form_Contact
{
    protected function setDefinition()
    {
     parent::setDefinition();
        $message = $this->hasOne('message');
        
        // Définition de toutes nos data
        $message->hasData(array(
         'type' => 'textarea',
         'label' => 'Message to your friend(s)'
        ));
        
        // Définition d'une seule valeur
        $message->hasData('placeHolder', 'Type your message here...');
        
        $this->hasMany('friend', new Form_Contact);
    }
}

Ces informations couplées aux implémentations d'Iterator et ArrayAccess nous permet de générer facilement et automatiquement n'importe quel formulaire à l'aide de fichier de template par exemple. Un exemple (sommaire) tournant sur un framework personnel est en ligne : http://cahnory.fr/fORMDemo/

N'hésitez pas à me faire part de vos remarques, elles seront appréciées. Je vous laisse avec quelques liens :
Le projet sur github (code source) : https://github.com/cahnory/fORM
La démo en ligne : http://cahnory.fr/fORMDemo/
La démo à télécharger : http://cahnory.fr/fORMDemo/files/fORM-demo.zip

Source

  • <?php
  • /**
  • * LICENSE: Copyright (c) 2011 François 'cahnory' Germain
  • * Permission is hereby granted, free of charge, to any person obtaining a copy
  • * of this software and associated documentation files (the "Software"), to deal
  • * in the Software without restriction, including without limitation the rights
  • * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  • * copies of the Software, and to permit persons to whom the Software is
  • * furnished to do so, subject to the following conditions:
  • *
  • * The above copyright notice and this permission notice shall be included in
  • * all copies or substantial portions of the Software.
  • *
  • * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  • * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  • * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  • * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  • * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  • * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  • * THE SOFTWARE.
  • * that is available through the world-wide-web at the following URI:
  • * http://www.php.net/license/3_01.txt. If you did not receive a copy of
  • * the PHP License and are unable to obtain it through the web, please
  • * send a note to license@php.net so we can mail you a copy immediately.
  • *
  • * @package FORM
  • * @author François 'cahnory' Germain <cahnory@gmail.com>
  • * @copyright 2011 François Germain
  • * @license http://www.opensource.org/licenses/mit-license.php
  • */
  • class fORM implements Iterator, ArrayAccess
  • {
  • /**
  • * Additional datas (ex:label,placeHolder)
  • *
  • * @var array
  • * @access private
  • */
  • private $_data = array();
  • /**
  • * Max number of values.
  • *
  • * Use a limit < 0 to allow
  • * unlimited number of values
  • *
  • * @var int
  • * @access private
  • */
  • private $_limit = 1;
  • /**
  • * Children
  • *
  • * @var array
  • * @access private
  • */
  • private $_children = array();
  • /**
  • * Element name
  • *
  • * @var string
  • * @access private
  • */
  • private $_name;
  • /**
  • * Children offsets
  • *
  • * @var array
  • * @access private
  • */
  • private $_offsets = array();
  • /**
  • * The parent element
  • *
  • * @var Form_Element
  • * @access protected
  • */
  • protected $_parent;
  • /**
  • * Value
  • *
  • * @var array
  • * @access private
  • */
  • private $_values = array();
  • public function __construct()
  • {
  • $this->setDefinition();
  • $this->fill(array(NULL));
  • }
  • /**
  • * Add a new child
  • *
  • * @param string $offset the child offset
  • * @param fORM $child the child object
  • *
  • * @return fORM the child object
  • *
  • * @access private
  • */
  • private function _hasChild($offset, $child)
  • {
  • $this->_children[] = $child;
  • $this->_offsets[] = $offset;
  • $this->_prepareChild($offset, $child);
  • return $child;
  • }
  • /**
  • * Prepare child
  • *
  • * @param string $offset the child offset
  • * @param fORM $child the child object
  • *
  • * @return fORM the child object
  • *
  • * @access private
  • */
  • private function _prepareChild($offset, $child)
  • {
  • $child->_name = $offset;
  • $child->_parent = $this;
  • return $child;
  • }
  • /**
  • * Clear values
  • *
  • * @access public
  • */
  • public function clear()
  • {
  • $this->fill(array(NULL));
  • }
  • /**
  • * Return data values
  • *
  • * @param string $name the data name
  • *
  • * @return mixed the data or null
  • *
  • * @access public
  • */
  • public function data($name = NULL)
  • {
  • if($name === NULL)
  • return $this->_data;
  • return array_key_exists($name, $this->_data) ? $this->_data[$name] : NULL;
  • }
  • /**
  • * Fill the values
  • *
  • * @param mixed $value the values
  • *
  • * @access public
  • */
  • public function fill($value)
  • {
  • $this->_values = array();
  • if($this->_limit !== 1) {
  • // Multiple elements
  • if(!is_array($value) || empty($value))
  • $value = array(NULL);
  • $i = sizeof($this->_values);
  • // Clone the multiple element into single elements
  • foreach($value as $v) {
  • if($i === $this->_limit) break;
  • $clone = $this->_prepareChild($i, clone($this));
  • $clone->hasLimit(1);
  • $clone->fill($v);
  • $this->_values[] = $clone;
  • $i++;
  • }
  • } elseif(sizeof($this->_children)) {
  • // Single node
  • if(!is_array($value))
  • $value = array();
  • // Clone the multiple element into single elements
  • foreach($this->_children as $key => $child) {
  • $offset = $this->_offsets[$key];
  • $clone = $this->_prepareChild($offset, clone($child));
  • $clone->_parent = $this;
  • $clone->fill(array_key_exists($offset, $value) ? $value[$offset] : array());
  • $this->_values[] = $clone;
  • }
  • } else {
  • // Single field
  • if(is_array($value))
  • $value = NULL;
  • $this->_values = array($value);
  • }
  • }
  • /**
  • * Set data value
  • *
  • * @param string $name the data name
  • * @param string $value the data value
  • *
  • * @access protected
  • */
  • protected function hasData($name, $value = NULL)
  • {
  • if($value === NULL && is_array($name)) {
  • $this->_data = $name;
  • } elseif($value !== NULL) {
  • $this->_data[$name] = $value;
  • }
  • }
  • /**
  • * Set values limit
  • *
  • * If limit < 1, unlimited
  • *
  • * @param string $limit the limit
  • *
  • * @access protected
  • */
  • protected function hasLimit($limit)
  • {
  • $this->_limit = (int)$limit;
  • }
  • /**
  • * Add a single child (limit = 1)
  • *
  • * @return mixed the child offset
  • * @return mixed the child object
  • *
  • * @access public
  • */
  • protected function hasOne($offset, fORM $child = NULL)
  • {
  • if($child === NULL)
  • $child = new fORM;
  • return $this->_hasChild($offset, $child);
  • }
  • /**
  • * Add a multiple child (limit = -1)
  • *
  • * @return mixed the child offset
  • * @return mixed the child object
  • *
  • * @access public
  • */
  • protected function hasMany($offset, fORM $child = NULL)
  • {
  • if($child === NULL)
  • $child = new fORM;
  • $child->hasLimit(-1);
  • return $this->_hasChild($offset, $child);
  • }
  • /**
  • * Check if the fORM has child
  • *
  • * @return boolean if the fORM has child
  • *
  • * @access public
  • */
  • public function isParent()
  • {
  • return sizeof($this->_children) > 0;
  • }
  • /**
  • * Return the number of values
  • *
  • * @return int nb values
  • *
  • * @access public
  • */
  • public function length()
  • {
  • return sizeof($this->_values);
  • }
  • /**
  • * Return the values limit
  • *
  • * @return int Nb values limit
  • *
  • * @access public
  • */
  • public function limit()
  • {
  • return $this->_limit;
  • }
  • /**
  • * Return the field name
  • *
  • * @param boolean $full If name start from root
  • * @param string $prefix
  • * @param string $glue
  • * @param string $suffix
  • *
  • * @return string the element name
  • *
  • * @access public
  • */
  • public function name($full = true, $prefix = '', $glue = '[', $suffix = ']')
  • {
  • if(!$full) {
  • $name = $this->_name;
  • } elseif($this->_parent === NULL || ($pname = $this->_parent->name($full, $prefix, $glue, $suffix)) === NULL) {
  • $name = $this->_name;
  • } else {
  • $name = $prefix.$pname.$glue.$this->_name.$suffix;
  • }
  • return $name;
  • }
  • /**
  • * Return the fORM parent
  • *
  • * @return fORM the fORM parent or NULL
  • *
  • * @access public
  • */
  • public function parent()
  • {
  • return $this->_parent;
  • }
  • /**
  • * Object definition (to overide)
  • *
  • * @access protected
  • */
  • protected function setDefinition() {}
  • /**
  • * Validate values and child values
  • *
  • * @return boolean true/false if valid or not
  • *
  • * @access public
  • */
  • public function validate()
  • {
  • $output = true;
  • if($this->_limit !== 1 || sizeof($this->_children)) {
  • foreach($this->_values as $value) {
  • if(!$value->validate()) {
  • $output = false;
  • break;
  • }
  • }
  • } else {
  • if(sizeof($this->_values))
  • $output = $this->validateValue($this->_values[0]);
  • }
  • return $output;
  • }
  • /**
  • * Validate a value (to overide)
  • *
  • * @return boolean true/false if valid or not
  • *
  • * @access protected
  • */
  • protected function validateValue($value)
  • {
  • return true;
  • }
  • /**
  • * Return the values
  • *
  • * @return mixed the values
  • *
  • * @access public
  • */
  • public function value()
  • {
  • $output = NULL;
  • if($this->_limit !== 1 || sizeof($this->_children)) {
  • $output = array();
  • foreach($this->_values as $key => $value) {
  • $output[$value->_name] = $value->value();
  • }
  • } else {
  • if(sizeof($this->_values))
  • $output = $this->_values[0];
  • }
  • return $output;
  • }
  • /* !Interfaces */
  • /**
  • * Interface: Iterator
  • *
  • * Traversing element's values
  • */
  • public function rewind()
  • {
  • $this->_offset = 0;
  • }
  • public function current()
  • {
  • return $this->_values[$this->_offset];
  • }
  • public function key()
  • {
  • return $this->_limit !== 1 ? $this->_offset : $this->_offsets[$this->_offset];
  • }
  • public function next()
  • {
  • ++$this->_offset;
  • }
  • public function valid()
  • {
  • return array_key_exists($this->_offset, $this->_values);
  • }
  • /**
  • * Interface: ArrayAccess
  • *
  • * Traversing element's values
  • */
  • public function offsetSet($offset, $value)
  • {
  • if($this->_limit !== 1) {
  • // Multiple elements
  • $i = sizeof($this->_values);
  • if($offset === NULL) {
  • $offset = $i;
  • }
  • if($offset < $i) {
  • $this->_values[$offset]->fill($value);
  • } else {
  • for($i; $offset >= $i; $i++) {
  • if($i === $this->_limit) break;
  • $clone = clone($this);
  • $clone->hasLimit(1);
  • $clone->_name = $i;
  • $clone->fill($i === $offset ? $value : NULL);
  • $this->_values[] = $clone;
  • }
  • }
  • } elseif(sizeof($this->_children)) {
  • // Single node
  • if($offset !== NULL && ($key = array_search($offset, $this->_offsets)) !== false) {
  • $clone = clone($this->_children[$key]);
  • $clone->fill($value);
  • $this->_values[$key] = $clone;
  • }
  • }
  • }
  • public function offsetExists($offset)
  • {
  • if($this->_limit === 1) {
  • return ($offset = array_search($offset, $this->_offsets)) !== false && array_key_exists($offset, $this->_values);
  • } else {
  • return array_key_exists($offset, $this->_values);
  • }
  • }
  • public function offsetUnset($offset)
  • {
  • if($this->_limit === 1) {
  • if(($offset = array_search($offset, $this->_offsets)) !== false && array_key_exists($offset, $this->_values)) {
  • $this->_values[$offset]->fill(NULL);
  • }
  • } else {
  • array_splice($this->_values, $offset, 1);
  • for($offset; array_key_exists($offset, $this->_values); $offset++)
  • $this->_values[$offset]->_name = $offset;
  • }
  • }
  • public function offsetGet($offset)
  • {
  • if($this->_limit === 1) {
  • return ($offset = array_search($offset, $this->_offsets)) !== false && array_key_exists($offset, $this->_values)
  • ? $this->_values[$offset] : null;
  • } else {
  • return array_key_exists($offset, $this->_values) ? $this->_values[$offset] : null;
  • }
  • }
  • }
  • ?>
<?php

	/**
	 * LICENSE: Copyright (c) 2011 François 'cahnory' Germain
	 * Permission is hereby granted, free of charge, to any person obtaining a copy
	 * of this software and associated documentation files (the "Software"), to deal
	 * in the Software without restriction, including without limitation the rights
	 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	 * copies of the Software, and to permit persons to whom the Software is
	 * furnished to do so, subject to the following conditions:
	 * 
	 * The above copyright notice and this permission notice shall be included in
	 * all copies or substantial portions of the Software.
	 * 
	 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	 * THE SOFTWARE.
	 * that is available through the world-wide-web at the following URI:
	 * http://www.php.net/license/3_01.txt.  If you did not receive a copy of
	 * the PHP License and are unable to obtain it through the web, please
	 * send a note to license@php.net so we can mail you a copy immediately.
	 *
	 * @package    FORM
	 * @author     François 'cahnory' Germain <cahnory@gmail.com>
	 * @copyright  2011 François Germain
	 * @license    http://www.opensource.org/licenses/mit-license.php
	 */

	class fORM implements Iterator, ArrayAccess
	{
		/**
	     *	Additional datas (ex:label,placeHolder)
	     *
	     *	@var array
	     *	@access	private
	     */
		private		$_data		=	array();
		
		/**
	     *	Max number of values.
	     *
	     *  Use a limit < 0 to allow
	     *	unlimited number of values
	     *
	     *	@var int
	     *	@access	private
	     */
		private	$_limit	=	1;
		
		/**
	     *	Children
	     *
	     *	@var array
	     *	@access	private
	     */
		private	$_children	=	array();
		
		/**
	     *	Element name
	     *
	     *	@var string
	     *	@access	private
	     */
		private	$_name;
		
		/**
	     *	Children offsets
	     *
	     *	@var array
	     *	@access	private
	     */
		private	$_offsets	=	array();
		
		/**
	     *	The parent element
	     *
	     *	@var Form_Element
	     *	@access	protected
	     */
		protected	$_parent;
		
		/**
	     *	Value
	     *
	     *	@var array
	     *	@access	private
	     */
		private	$_values	=	array();
		
		public	function	__construct()
		{
			$this->setDefinition();
			$this->fill(array(NULL));
		}
		
		/**
		 *	Add a new child
		 *
		 *	@param string $offset the child offset
		 *	@param fORM   $child  the child object
		 *
		 *	@return fORM the child object
		 *
		 *	@access private
		 */
		private	function	_hasChild($offset, $child)
		{
			$this->_children[]	=	$child;
			$this->_offsets[]	=	$offset;
			$this->_prepareChild($offset, $child);
			return	$child;
		}
		
		/**
		 *	Prepare child
		 *
		 *	@param string $offset the child offset
		 *	@param fORM   $child  the child object
		 *
		 *	@return fORM the child object
		 *
		 *	@access private
		 */
		private	function	_prepareChild($offset, $child)
		{
			$child->_name	=	$offset;
			$child->_parent	=	$this;
			return	$child;
		}
		
		/**
		 *	Clear values
		 *
		 *	@access public
		 */
		public	function	clear()
		{
			$this->fill(array(NULL));
		}
		
		/**
		 *	Return data values
		 *
		 *	@param string $name  the data name
		 *
		 *	@return mixed the data or null
		 *
		 *	@access public
		 */
		public	function	data($name = NULL)
		{
			if($name === NULL)
				return	$this->_data;
			
			return	array_key_exists($name, $this->_data) ? $this->_data[$name] : NULL;
		}
		
		/**
		 *	Fill the values
		 *
		 *	@param mixed $value the values
		 *
		 *	@access public
		 */
		public	function	fill($value)
		{
			$this->_values	=	array();
			if($this->_limit !== 1) {
			//	Multiple elements
				if(!is_array($value) || empty($value))
					$value	=	array(NULL);
				$i	=	sizeof($this->_values);
				//	Clone the multiple element into single elements
				foreach($value as $v) {
					if($i === $this->_limit)	break;
					$clone	=	$this->_prepareChild($i, clone($this));
					$clone->hasLimit(1);
					$clone->fill($v);
					$this->_values[]	=	$clone;
					$i++;
				}
			} elseif(sizeof($this->_children)) {
			//	Single node
				if(!is_array($value))
					$value	=	array();
				//	Clone the multiple element into single elements
				foreach($this->_children as $key => $child) {
					$offset	=	$this->_offsets[$key];
					$clone	=	$this->_prepareChild($offset, clone($child));
					$clone->_parent	=	$this;
					$clone->fill(array_key_exists($offset, $value) ? $value[$offset] : array());
					$this->_values[]	=	$clone;
				}
			} else {
			//	Single field
				if(is_array($value))
					$value	=	NULL;
				$this->_values	=	array($value);
			}
		}
		
		/**
		 *	Set data value
		 *
		 *	@param string $name  the data name
		 *	@param string $value the data value
		 *
		 *	@access protected
		 */
		protected	function	hasData($name, $value = NULL)
		{
			if($value === NULL && is_array($name)) {
				$this->_data	=	$name;
			} elseif($value !== NULL) {
				$this->_data[$name]	=	$value;
			}
		}
		
		/**
		 *	Set values limit
		 *
		 *	If limit < 1, unlimited
		 *
		 *	@param string $limit the limit
		 *
		 *	@access protected
		 */
		protected	function	hasLimit($limit)
		{
			$this->_limit	=	(int)$limit;
		}
		
		/**
		 *	Add a single child (limit = 1)
		 *
		 *	@return mixed the child offset
		 *	@return mixed the child object
		 *
		 *	@access public
		 */
		protected	function	hasOne($offset, fORM $child = NULL)
		{
			if($child === NULL)
				$child	=	new fORM;
			return	$this->_hasChild($offset, $child);
		}
		
		/**
		 *	Add a multiple child (limit = -1)
		 *
		 *	@return mixed the child offset
		 *	@return mixed the child object
		 *
		 *	@access public
		 */
		protected	function	hasMany($offset, fORM $child = NULL)
		{
			if($child === NULL)
				$child	=	new fORM;
			$child->hasLimit(-1);
			return	$this->_hasChild($offset, $child);
		}
		
		/**
		 *	Check if the fORM has child
		 *
		 *	@return boolean if the fORM has child
		 *
		 *	@access public
		 */
		public	function	isParent()
		{
			return	sizeof($this->_children) > 0;
		}
		
		/**
		 *	Return the number of values
		 *
		 *	@return int nb values
		 *
		 *	@access public
		 */
		public	function	length()
		{
			return	sizeof($this->_values);
		}
		
		/**
		 *	Return the values limit
		 *
		 *	@return int Nb values limit
		 *
		 *	@access public
		 */
		public	function	limit()
		{
			return	$this->_limit;
		}
		
		/**
		 *	Return the field name
		 *
		 *	@param boolean $full If name start from root
		 *	@param string  $prefix
		 *	@param string  $glue
		 *	@param string  $suffix
		 *
		 *	@return string the element name
		 *
		 *	@access public
		 */
		public	function	name($full = true, $prefix = '', $glue = '[', $suffix = ']')
		{
			if(!$full) {
				$name	=	$this->_name;
			} elseif($this->_parent === NULL || ($pname = $this->_parent->name($full, $prefix, $glue, $suffix)) === NULL) {
				$name	=	$this->_name;
			} else {
				$name	=	$prefix.$pname.$glue.$this->_name.$suffix;
			}
			return	$name;
		}
		
		/**
		 *	Return the fORM parent
		 *
		 *	@return fORM the fORM parent or NULL
		 *
		 *	@access public
		 */
		public	function	parent()
		{
			return	$this->_parent;
		}
		
		/**
		 *	Object definition (to overide)
		 *
		 *	@access protected
		 */
		protected	function	setDefinition() {}
		
		/**
		 *	Validate values and child values
		 *
		 *	@return boolean true/false if valid or not
		 *
		 *	@access public
		 */
		public	function	validate()
		{
			$output	=	true;
			if($this->_limit !== 1 || sizeof($this->_children)) {
				foreach($this->_values as $value) {
					if(!$value->validate()) {
						$output	=	false;
						break;
					}
				}
			} else {
				if(sizeof($this->_values))
					$output	=	$this->validateValue($this->_values[0]);
			}
			return	$output;
		}
		
		/**
		 *	Validate a value (to overide)
		 *
		 *	@return boolean true/false if valid or not
		 *
		 *	@access protected
		 */
		protected	function	validateValue($value)
		{
			return	true;
		}
		
		/**
		 *	Return the values
		 *
		 *	@return mixed the values
		 *
		 *	@access public
		 */
		public	function	value()
		{
			$output	=	NULL;
			if($this->_limit !== 1 || sizeof($this->_children)) {
				$output	=	array();
				foreach($this->_values as $key => $value) {
					$output[$value->_name]	=	$value->value();
				}
			} else {
				if(sizeof($this->_values))
					$output	=	$this->_values[0];
			}
			return	$output;
		}
		
	/* !Interfaces */
		
		/**
		 *	Interface: Iterator
		 *
		 *	Traversing element's values
		 */
		public	function	rewind()
		{
			$this->_offset	=	0;
		}
		
		public	function	current()
		{
			return	$this->_values[$this->_offset];
		}
		
		public	function	key()
		{
			return	$this->_limit !== 1 ? $this->_offset : $this->_offsets[$this->_offset];
		}
		
		public	function	next()
		{
			++$this->_offset;
		}
		
		public	function	valid()
		{
			return	array_key_exists($this->_offset, $this->_values);
		}		
		
		/**
		 *	Interface: ArrayAccess
		 *
		 *	Traversing element's values
		 */
		public function offsetSet($offset, $value)
		{
			if($this->_limit !== 1) {
			//	Multiple elements
				$i = sizeof($this->_values);
				if($offset === NULL) {
					$offset	=	$i;
				}
				if($offset < $i) {
					$this->_values[$offset]->fill($value);
				} else {
					for($i; $offset >= $i; $i++) {
						if($i === $this->_limit)	break;	
						$clone	=	clone($this);
						$clone->hasLimit(1);
						$clone->_name	=	$i;							
						$clone->fill($i === $offset ? $value : NULL);
						$this->_values[]	=	$clone;
					}
				}
			} elseif(sizeof($this->_children)) {
			//	Single node
				if($offset !== NULL && ($key = array_search($offset, $this->_offsets)) !== false) {
					$clone	=	clone($this->_children[$key]);
					$clone->fill($value);
					$this->_values[$key]	=	$clone;
				}
			}
		}
		
		public function offsetExists($offset)
		{
			if($this->_limit === 1)	{
				return	($offset = array_search($offset, $this->_offsets)) !== false && array_key_exists($offset, $this->_values);
			} else {
				return	array_key_exists($offset, $this->_values);
			}
		}
		
		public function offsetUnset($offset)
		{
			if($this->_limit === 1)	{
				if(($offset = array_search($offset, $this->_offsets)) !== false && array_key_exists($offset, $this->_values)) {
					$this->_values[$offset]->fill(NULL);
				}
			} else {
				array_splice($this->_values, $offset, 1);
				for($offset; array_key_exists($offset, $this->_values); $offset++)
					$this->_values[$offset]->_name	=	$offset;
			}
		}
		
		public function offsetGet($offset)
		{
			if($this->_limit === 1) {
				return	($offset = array_search($offset, $this->_offsets)) !== false && array_key_exists($offset, $this->_values)
					?	$this->_values[$offset] : null;
			} else {
				return	array_key_exists($offset, $this->_values) ? $this->_values[$offset] : null;
			}
		}
    }

?>



 Sources du même auteur

PARCOURS DE TABLEAU À L'AIDE D'ATTRIBUTS HTML "NAME
CLASS MOTEUR DE TEMPLATE PHP5
VÉRIFIER LES CHAMPS OBLIGATOIRES D'UN FORMULAIRE

 Sources de la même categorie

Source avec Zip Source avec une capture VALIDATEUR DE FORMULAIRE par Reldan
Source avec Zip SUIVI SERVICE CLIENT PHP par hige52
Source avec Zip POO - FORMULAIRE NEWSLETTER PHP - PROFESSEUR-PHP.COM par mtrix000
Source avec Zip Source avec une capture SELECTEUR DE NOTE par Reldan
Source avec Zip Source avec une capture ESPACE MEMBRE , AVEC CASE OPTIONNEL , SANS MYSQL par sartoz

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture VALIDATEUR DE FORMULAIRE par Reldan
CLASSE FORM, GESTION DE VALIDATION POUR FORMULAIRE par phpAnonyme
PHP5 - CLASSE DE VÉRIFICATION DE FORMULAIRE SIMPLE par NainPuissant
Source avec Zip Source avec une capture FORMOL, PACKAGE PHP5 DE GESTION DE FORMULAIRES XHTML par tmaziere
Source avec Zip [PHP5] FORMCHECKER : VALIDATION DE SAISIES UTILISATEUR par malalam

Commentaires et avis

Commentaire de cod57 le 05/02/2011 11:33:50

bonjour

en appelant /Form/Test.php
ou en faisant tes exemples
j'ai :

Cahnory framework
Simple fORM demo. To see how it works :

fORM definiton
/Form/Test.php
fORM view
/View/form[.*].html
Controller
/Module/TestForm.php
As it's a short demo, the error display is very limited but could be improved. If the form get cleared it's because the token expired (you could see this in /Debug/gui.log or by configuring the Helper_Debug_GrowlRegistrar for your system).

La vue demandée n'existe pas

a++

Commentaire de choy le 05/02/2011 11:48:19

Mince, ça doit être une erreur de case... bosser sur un mac est agréable (enfin ça c'est mon avi perso) mais alors pour le coté case insensitive ça me rend fou parfois... je regarderai ça sur le pc au taff. Merci de m'avoir prévenu ;)

En attendant lundi, reste la class, le mini tuto et la démo en ligne... ralala je suis déçu et désolé.

Commentaire de choy le 07/02/2011 16:53:47

Correction : il n'y avait en réalité pas de problème (ou alors un autre). Mon application n'as qu'un point d'entré via une redirection htaccess. L'accès aux fichiers est bloqués si ce n'est ceux se trouvant dans le dossier files.
L'adresse du module de test est http://host/installationPath/TestForm/index.html, mais pas besoin de celle-ci, le module de test est celui par défaut (page d'accueil).

Pour la partie "To see how it works" il était question de regarder les sources et non de tenter d'accéder au fichier via http. Désolé si je me suis mal fait comprendre.

Commentaire de gunhunter le 28/03/2011 16:14:52

BONJOUR JE SUIS NOUVEAU EN PHP ET SVP J'AIMERAIS KON M'AIDE A REALISER UN PROJET
voici le topo
offet je voudrais réaliser un programme simple qui permet a un utilisateur de remplir les informations dans une page et avoir le résultat dans une autre page déjà saisi exemple de remplissage des attestations de stage ou autre type de document de ce type ...merci deja de votre aide

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Problème de validation de formulaire [ par ehmarc ] Hello world!!!Bon j'ai un petit problème jai formulaire tres simple une case identification un bouton envoyerj'arrive à m'identifier nickel quand quan Prob de redirection et validation [ par LeManchot ] Voila jai encoren un souci:jai un formulaire que je valide via un bouton (pr linstant ok) mais par ce meme bouton je dois rediriger la page ou se toru Prob Debutant - Validation d'1 formulaire par Menu Déroulant . [ par marcooo ] Bonjour a tous .J'esplique le problème ... Tout d'abord je tien a dire ke je débute dans le PHP/MySQL.Alors voila, je voudrai créer une sorte de moteu Validation Formulaire [ par kiboumz ] Bonjour, J'ai cr&#233;e un formulaire duquel j'envoie des donn&#233;es vers une base de donn&#233;es, cependant j'aimerais pouvoir valider mes donn& Double envoie lors d'une validation de formulaire? [ par Monico9385 ] Bonjour &#224; tous, j'ai un petit soucis concernant un double envoie lors de la validation d'un formulaire, je m'explique : j'ai sur un site un for Activation d'un compte par mail [ par aissiou1979 ] Voila.J'ai realisé un formulaire d'inscription pour jouer à un concours.A la suite de la validation de ce formulaire un mail est envoyé à  la personne CLASS PERMETTANT DE CRÉER UNE IMAGE POUR LA VALIDATION D'UN FORMULAIRE [ par Tanaka56 ] Bonjour à tous.<br style="mso Référence dans formulaire [ par mheditions ] bonjour.tjs dans le but d'améliorer un formulaire de commande, je cherche à partir d'une page html qui contient plusieurs objet à commander ; que chac validation de courriel [ par luciano12 ] Bonjour,J'aurais besoin de votre aide pour m'aider à faire la chose suivante:Je voudrais que les visiteurs qui visitent mon site Intenret puissent rem Balise select liées [ par nagrom_om ] Salut, Voila mon probleme : J'ai une page dans laquelle il y a une balise select qui affiche une liste d'éléments, le choix d un élément provoque l af


Nos sponsors


Sondage...

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,515 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales