Location: PHPKode > scripts > Forms class > forms-class/Forms.class.php
<style>
  .actionbuttonssmall{background-color: Green;border: 0px;color: Aqua;width: 25px;height: 20px;font-size: 9px;}
  .actionbuttonsbig{background-color: Green;border: 0px;color: Aqua;width: 45px;height: 20px;font-size: 9px;}
  .yearokbutton{background-color: Gray;border: 0px;color: Aqua;width: 15px;height: 20px;font-size: 9px;}
  .daybuttons{border: 0px;width: 25px;height: 15px;background-color: #EEEEEE ;background: #EEEEEE ;font-family: Tahoma;font-size: 12px;position: relative;}
  .presseddaybutton{border: 2px;width: 25px;height: 15px;background: white ;font-family: Tahoma;font-size: 12px;position: relative;}
  .caltable {border: 0px;background-color: #EEEEEE;font-family: Tahoma;font-size: 12px;}
  .monthyear {border: 0px;background-color: Silver;font-family: Tahoma;font-size: 12px;align :center}
  .grid {  font-family: Tahoma, Arial, Helvetica, sans-serif; font-size: 11px; color: #000000}
</style>

<?php
/********************************************************************************************
** 	Autor		:	Andrés Darío Gutiérrez Poveda.			          																*
** 	Fecha  	:	Abril 14 de 2004.	         				   	          															*
** 	Versión	:	1.0.1.                      			   	          															*
**	Empresa	:	Atila Servicios S.A. 			                      															*
**																																													*
*********************************************************************************************
**	Proposito:																																							*
**																																													*
** 		Esta clase se ocupa de hacer un formulario de una tabla, teniendo en cuenta los tipos	*
**		de cada campo de ésta.	Además es capaz de hacer la validación de dichos campos.			*
**		Realiza las adiciones y actualizaciones en dichas tablas.															*
**																																													*
*********************************************************************************************
**	Nota:																																										*
**																																													*
**		Esta clase fue creada basandose en la clase publicada en www.phpclasses.org llamada		*
**		Formitable.class.php v.98.																														*
**																																													*
*********************************************************************************************
**	Version 1.0.1  -  Abril 14 de 2004																											*
** 	Cambios para la versión 1.0.1																														*
**																																													*
** 		- Adición de validación de campos, tipos como: Int, String, Real, Date, Datetime.			*
** 		- Validación de E-mail.																																*
**		- Inclusión de otra clase que genera un calendario para	escoger la fecha.							*
**	 	- Deshabilitación de campos del formulario.																						*
**		- Orden de aparición de los campos en el formulario por medio de un array.						*
**		- Posibilidad de cambiar la acción para manejar la adición	y la actualización a una 	*
**			función diferente a esta clase.																											*
********************************************************************************************/  

class Forms{

	/*******************************************************************************************
 	** 	VARIABLES PRIVADAS																																		**
  *******************************************************************************************/
	var $forms_javascript;
	var $forms_feedback;

	/*******************************************************************************************
 	** 	CONSTANTES PRIVADAS																																		**
  *******************************************************************************************/
	//these vars determine whether to use default form input type 
  //or alternate based on field size
  //enum field default is select, alternate is radio
  //set field default is multiselect, alternate is checkbox
  //blob or text field default is textarea, alternate is text
  var $enumField_toggle = 3;
  var $setField_toggle = 4;
  var $strField_toggle = 70;

  //these vars determine form input size attributes
  var $textInputLength = 50;
  var $textareaRows = 4;
  var $textareaCols = 50;
  var $multiSelectSize = 4;   
  
  
  /*******************************************************************************************
 	** 	MÉTODOS																																								**
  *******************************************************************************************/
  
  /*****************************************************************************
 	** 	NOMBRE:																																	**
  **																																					**
 	** 	SET y GET para la variable privada forms_javascript.										**
  **																																					**
  ******************************************************************************
 	** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Métodos utilizados para ajustar y obtener el valor de la variable.			**
 	**																																					**
 	******************************************************************************
 	**	ARGUMENTOS:																															**
 	**																																					**
 	**	- value: Valor a asignar.																								**
 	*****************************************************************************/
	function get_forms_javascript(){
		return $this->forms_javascript;
	} 
	
	function set_forms_javascript($value){
		$this->forms_javascript = $value;
	}
	
	
	/*****************************************************************************
 	** 	NOMBRE:																																	**
  **																																					**
 	** 	SET y GET para la variable privada forms_feedback.											**
  **																																					**
  ******************************************************************************
 	** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Métodos utilizados para ajustar y obtener el valor de la variable.			**
 	**																																					**
 	******************************************************************************
 	**	ARGUMENTOS:																															**
 	**																																					**
 	**	- value: Valor a asignar.																								**
 	*****************************************************************************/
	function get_forms_feedback(){
		return $this->forms_feedback;
	} 
	
	function set_forms_feedback($value){
		$this->forms_feedback = $value;
	}
  
  
 	/*****************************************************************************
 	** 	NOMBRE:																																	**
  **																																					**
 	** 	Forms (&$conn,$DB,$table,$usuid)																				**
  **																																					**
  ******************************************************************************
 	** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Constructor de la clase, configura el nombre de la forma y trae la info **
 	** 	de la tabla.																														**
 	** 	Si la forma fue enviada el constructor adicionaraá un nuevo registro en **
 	** 	la tabla con los datos enviados.																				**
 	**																																					**
 	******************************************************************************
 	**	ARGUMENTOS:																															**
 	**																																					**
 	**	- conn: Conexión a la base de datos.																		**
 	**	- DB: Nombre de la base de datos.																				**
 	**	- table: Nombre de la tabla.																						**
 	**	-	usuid: Idetificación del usuario.																			**
 	*****************************************************************************/  
 	function Forms(&$conn,$DB,$table,$usuid){
    if( stristr(getenv("HTTP_USER_AGENT"), "Mozilla/4") && !stristr(getenv("HTTP_USER_AGENT"), "compatible" ) )
      $this->NS4 = true; else $this->NS4 = false;  
    	$this->conn = $conn;
    	$this->DB = $DB;
      $this->formName = $this->table = $table;
      $this->fields = @mysql_list_fields($DB, $table, $conn) or die("BD, tabla o error de conexión.");
      $this->columns = @mysql_num_fields($this->fields);
      $this->usuarioid = $usuid;          
      $this->pkey = $pkey = "";        
      $this->labelBreak = "";        
      $this->fieldBreak = ""; 
  	}
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	AddJavas ()																															**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función inserta el código Javascript necesario para hacer toda la 	**
  ** 	validación de los campos, si no se quiere hacer validación simplemente 	**
  ** 	no se llama esta función.																								**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																													 	**
  *****************************************************************************/
  function AddJavas($validaciones){
		$isEmailAddr  = " function isEmailAddr(email){";
		$isEmailAddr .= "		var result = false;";
		$isEmailAddr .= "		var theStr = new String(email);";
		$isEmailAddr .= "	 	var index = theStr.indexOf('@');";
		$isEmailAddr .= "	 	if(index > 0){";
		$isEmailAddr .= "			var pindex = theStr.indexOf('.',index);";
		$isEmailAddr .= "			if((pindex > index+1) && (theStr.length > pindex+1))";
		$isEmailAddr .= "				result = true;";
		$isEmailAddr .= "		}";
		$isEmailAddr .= "		return result;";
		$isEmailAddr .= "	}";
						
		$validRequired  = " function validRequired(formField,fieldLabel){";
		$validRequired .= "		var result = true;";
		$validRequired .= "		if (formField.value == ''){";
		$validRequired .= "			alert('Por favor digite el valor para el campo ' + fieldLabel + '.');";
		$validRequired .= "			formField.focus();";
		$validRequired .= "			result = false;"; 
		$validRequired .= "		}";
		$validRequired .= "		return result;";
		$validRequired .= "	}"; 
						
		$allDigits  = " function allDigits(str){";
		$allDigits .= "		return inValidCharSet(str,'0123456789');";
		$allDigits .= "	}";
							
		$allDigitss  = "function allDigitss(str){";
		$allDigitss .= "	return inValidCharSet(str,'0123456789.');"; 
		$allDigitss .= "}";
						
		$inValidCharSet  = "function inValidCharSet(str,charset){";
		$inValidCharSet .= "	var result = true;";
		$inValidCharSet .= "	// Note: doesn't use regular expressions to avoid early Mac browser bugs"; 
		$inValidCharSet .= "	for (var i=0;i<str.length;i++)";
		$inValidCharSet .= "		if (charset.indexOf(str.substr(i,1))<0){";
		$inValidCharSet .= "			result = false;";
		$inValidCharSet .= "			break;";
		$inValidCharSet .= "		}";
		$inValidCharSet .= "	return result;";
		$inValidCharSet .= "}";
						
		$validEmail  = "function validEmail(formField,fieldLabel,required){";
		$validEmail .= "	var result = true;";
		$validEmail .= "	if(required && !validRequired(formField,fieldLabel))";
		$validEmail .= "		result = false;";
		$validEmail .= "	if(result && ((formField.value.length < 3) || !isEmailAddr(formField.value)) ){";
		$validEmail .= "		alert('Por favor ingrese una direcci&#243n de email completa en la forma: hide@address.com');";
		$validEmail .= "		formField.focus();";
		$validEmail .= "		result = false;";
		$validEmail .= "	}";
		$validEmail .= "	return result; ";
		$validEmail .= "}";
						
		$validNum  = "function validNum(formField,fieldLabel,required){";
		$validNum .= "	var result = true;";
		$validNum .= "	if(required && !validRequired(formField,fieldLabel))";
		$validNum .= "		result = false;";
		$validNum .= "		if(result){";
		$validNum .= "			if(!allDigitss(formField.value)){";
		$validNum .= "				alert('Por favor digite un n&#250mero para el campo ' + fieldLabel + '.');";
		$validNum .= "				formField.focus();";		
		$validNum .= "				result = false;";
		$validNum .= "			}";
		$validNum .= "		}";
		$validNum .= "	return result;"; 
		$validNum .= "}";
													
		$validInt  = "function validInt(formField,fieldLabel,required){";
		$validInt .= "	var result = true;";
		$validInt .= "	if(required && !validRequired(formField,fieldLabel))";
		$validInt .= "		result = false;";
		$validInt .= " 		if (result){";
		$validInt .= " 			var num = parseInt(formField.value,10);";
		$validInt .= " 			if(isNaN(num)){";
		$validInt .= " 				alert('Por favor digita un entero para el campo ' + fieldLabel + '.');";
		$validInt .= "				formField.focus();";
		$validInt .= "				result = false;";
		$validInt .= "			}";
		$validInt .= "		}";
		$validInt .= "	return result;";
		$validInt .= "}";
						
		$validDate  = " function validDate(formField,fieldLabel,required){";
		$validDate .= "		var result = true;";
		$validDate .= "		if(required && !validRequired(formField,fieldLabel))";
		$validDate .= "			result = false;";
		$validDate .= "			if(result){";
		$validDate .= "				var elems = formField.value.split('-');";
		$validDate .= "				result = (elems.length == 3); // should be three components";
		$validDate .= "				if(result){";
		$validDate .= "				 	var month = parseInt(elems[0],10);";
		$validDate .= "				  var day = parseInt(elems[1],10);";
		$validDate .= "				 	var year = parseInt(elems[2],10);";
		$validDate .= "					result = allDigits(elems[0]) && (month > 0) && (month < 13) &&";
		$validDate .= "					allDigits(elems[1]) && (day > 0) && (day < 32) &&";
		$validDate .= "					allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4));";
		$validDate .= "				}";
		$validDate .= "				if(!result){";
		$validDate .= "				 	alert('Por favor digite la fecha en el formato YYYY-MM-DD para el campo ' + fieldLabel + '.');";
		$validDate .= "					formField.focus();";
		$validDate .= "				}";
		$validDate .= "			}";
		$validDate .= "		return result;";
		$validDate .= "	}";
							
		$validDatetime  = "	function validDatetime(formField,fieldLabel,required){";
		$validDatetime .= "		var result = true;";
		$validDatetime .= "		if(required && !validRequired(formField,fieldLabel))"; 
		$validDatetime .= "			result = false;";
		$validDatetime .= "			if(result){";
		$validDatetime .= "				var elemen = formField.value.split(' ');";
		$validDatetime .= "				var elems = elemen[0].split('-');";
		$validDatetime .= "				var horas = elemen[1].split(':');";
		$validDatetime .= "				result = (elems.length == 3) && (horas.length == 3); // should be three components";
		$validDatetime .= "				if(result){";
		$validDatetime .= "					var month = parseInt(elems[0],10);";
		$validDatetime .= "					var day = parseInt(elems[1],10);";
		$validDatetime .= "				 	var year = parseInt(elems[2],10);"; 
		$validDatetime .= "				 	var hora = parseInt(horas[0],10);";
		$validDatetime .= "				 	var min = parseInt(horas[1],10);";
		$validDatetime .= "				 	var seg = parseInt(horas[2],10);";
		$validDatetime .= "					result = allDigits(elems[0]) && (month > 0) && (month < 13) &&";
		$validDatetime .= "					allDigits(elems[1]) && (day > 0) && (day < 32) &&";
		$validDatetime .= "					allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4)) &&";
		$validDatetime .= "					allDigits(horas[0]) && (hora >= 0) && (hora < 24) &&";
		$validDatetime .= "					allDigits(horas[1]) && (min >= 0) && (min < 60) &&";
		$validDatetime .= "					allDigits(horas[2]) && (seg >= 0) && (seg < 60);";
		$validDatetime .= "				}";
		$validDatetime .= "				if(!result){";
		$validDatetime .= "				 	alert('Por favor digite la fecha en el formato YYYY-MM-DD HH:MM:SS para el campo ' + fieldLabel + '.');";
		$validDatetime .= "					formField.focus();";
		$validDatetime .= "				}";
		$validDatetime .= "			}";
		$validDatetime .= "		return result;";
		$validDatetime .= "	}";							
						
		$validaForm  = "function validateForm(){";
		$validaForm .= "	result = true;";
		$validaForm .= "	for(i=0; i < document.".$this->formName.".length && result; i++){";
		$validaForm .= "		switch(document.".$this->formName.".elements[i].id){";
		$validaForm .= "			case 'string':";
		$validaForm .= "				result = true;";
		$validaForm .= "				break;";
		$validaForm .= "			case 'int':";
		$validaForm .= "				result = validInt(document.".$this->formName.".elements[i],document.".$this->formName.".elements[i].name,true);";
		$validaForm .= "				break;";
		$validaForm .= "			case 'real':";
		$validaForm .= "				result = validNum(document.".$this->formName.".elements[i],document.".$this->formName.".elements[i].name,true);";
		$validaForm .= "				break;";
		$validaForm .= "			case 'date':";
		$validaForm .= "				result = validDate(document.".$this->formName.".elements[i],document.".$this->formName.".elements[i].name,true);";
		$validaForm .= "				break;";
		$validaForm .= "			case 'datetime':";
		$validaForm .= "				result = validDatetime(document.".$this->formName.".elements[i],document.".$this->formName.".elements[i].name,true);";
		$validaForm .= "				break;";
		$validaForm .= "			default:";
		$validaForm .= "				break;";
		$validaForm .= "		}";
		$validaForm .= "	}";
		$validaForm .= "	return result;";
		$validaForm .= "}";
							
		$script = "<script language='JavaScript' type='text/javascript'>";
		
		if($validaciones['isEmailAddr'] == 1)
			$script .= $isEmailAddr;
		
		if($validaciones['validRequired'] == 1)	
			$script .= $validRequired;
			
		if($validaciones['allDigits'] == 1)	
			$script .= $allDigits;
			
		if($validaciones['allDigitss'] == 1)	
			$script .= $allDigitss;
			
		if($validaciones['inValidCharSet'] == 1)	
			$script .= $inValidCharSet;
			
		if($validaciones['validNum'] == 1)	
			$script .= $validNum;
			
		if($validaciones['validInt'] == 1)	
			$script .= $validInt;
			
		if($validaciones['validDate'] == 1)	
			$script .= $validDate;
			
		if($validaciones['validDatetime'] == 1)	
			$script .= $validDatetime;
			
		if($validaciones['validForm'] == 1)	
			$script .= $validaForm;
			
		$script .= "</script>";
						
		return $script;
  }
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	submitForm ()																														**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función envia el formulario a la base de datos, adicionando el 		**
  ** 	registro si el valor de 'pkey' del formulario no está especificado, si 	**
  ** 	lo está actualiza el registro.																					**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS:																														 	**
  *****************************************************************************/
  function submitForm(){
  	if(isset($_POST['pkey'])){
	  	foreach($_POST as $key=>$value){
	    	if($key=="pkey" || $key=="submit") 
	    		continue;
	      if(is_array($value)){
	      	$fields .= ",$key = '".implode(",",$_POST[$key])."'";
	      }else{
	      	$fields .= ",$key = '".$value."'"; 
	      }
      }
      
      //remove first comma
      $fields = substr($fields,1);     
             
      //form and execute query, echoing results
      $SQLquery = "UPDATE $this->table SET $fields WHERE $this->pkey = '".$_POST['pkey']."'";
      @mysql_select_db($this->DB,$this->conn);
      @mysql_query($SQLquery,$this->conn);
      if( @mysql_error() == "" ){
      	$this->forms_feedback .= "$Actializaci&#243n exitosa!.</strong></font></p>";
      }else 
      	$this->forms_feedback .= " No se pudo actualizar el registro!! ";	      
    }else{
      //cycle array while forming query args
      foreach($_POST as $key=>$value){
	    	if($key == "submit") continue;
	      $fields .= ",".$key;
	        
	      if(is_array($value)){	
	      	$values .= ",'".implode(",",$_POST[$key])."'";
	      }else{ 
	      	$values .= ",'".$value."'";
	      }
      }
      
      //remove first comma
      $fields = substr($fields,1);
      $values = substr($values,1);	 
             
      //form and execute query, echoing results
      $SQLquery = "INSERT INTO $this->table ($fields) VALUES ($values)";
      @mysql_select_db($this->DB,$this->conn);
      if( @mysql_query($SQLquery,$this->conn) ){
      	$this->forms_feedback .= " Inserci&#243n exitosa!! ";
      }else 
      	$this->forms_feedback .= " No se pudo insertar el registro!! ";
		}
    unset($_POST['submit']);
  }
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	_mysql_enum_values ($tableName,$fieldName)															**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función fue modificada de la que existe en php.net:								**
  ** 	http://www.php.net/manual/en/function.mysql-fetch-field.php							**
	** 	Cortesia de: hide@address.com & hide@address.com						**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  ** 	- tableName: Nombre de la tabla.																				**
  **	- fieldName: Nombre del campo.																					**
  *****************************************************************************/       
  function _mysql_enum_values($tableName,$fieldName){
    $result = @mysql_query("DESCRIBE $tableName");
    while($row = @mysql_fetch_array($result)){
      ereg('^([^ (]+)(\((.+)\))?([ ](.+))?$',$row['Type'],$fieldTypeSplit);
          
      //split type up into array
      $fieldType = $fieldTypeSplit[1];
      $fieldLen = $fieldTypeSplit[3];

      if ( ($fieldType=='enum' || $fieldType=='set') && ($row['Field']==$fieldName) ){
          $fieldOptions = split("','",substr($fieldLen,1,-1));
          return $fieldOptions;
      }
		}
    return FALSE;
	}    
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	_getFieldData ($fieldName)																							**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Recuperar los datos normalizados de otra tabla y campo.									**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- fieldName: Nombre del campo.																					**
  *****************************************************************************/
  function _getFieldData($fieldName){
    $SQLquery = "SELECT "
                .$this->normalized[$fieldName]['tableKey']." AS pkey".
                ", "
                .$this->normalized[$fieldName]['tableValue']." AS value ".
                "FROM "
                .$this->normalized[$fieldName]['tableName']." ".
                "WHERE "
                .$this->normalized[$fieldName]['where']." ".
                "ORDER BY "
                .$this->normalized[$fieldName]['orderBy'];
                  
    $retrievedData = @mysql_query($SQLquery,$this->conn);
    if(@mysql_error()!="") die ("ERROR: No fue posible normalizar los datos de '".$this->normalized[$fieldName]['tableName']."'.");
      
    $numPairs = @mysql_num_rows($retrievedData);
    $this->normalized[$fieldName]['pairs'] = $numPairs;
      
    for($i=0; $i<$numPairs; $i++){
      $set = @mysql_fetch_assoc($retrievedData);
      $this->normalized[$fieldName]['keys'][$i] = $set['pkey'];
      $this->normalized[$fieldName]['values'][$i] = $set['value'];
    }  
  }        
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	getRecord ($id)																													**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función consultará la tabla para la llave primaria con el valor del**
  ** 	argumento.																															**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- id: Identificador del registro.																				**
  *****************************************************************************/
  function getRecord($id){
    $SQLquery = "SELECT * FROM $this->table WHERE $this->pkey = '$id'";
    @mysql_select_db($this->DB,$this->conn);
    $result = @mysql_query($SQLquery,$this->conn);
    
    if( @mysql_num_rows($result) == 1 ){
      $this->pkeyID = $id;
      $this->record = @mysql_fetch_assoc($result);
      return true;
    }else 
    	return false;
  }
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	normalizedField ($fieldName, $tableName, $tableKey, $tableValue, $where,**
  ** 									$orderBy = "value ASC")																	**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**	
  ** 	Esta función recupera registros de otra tabla para ser utilizados como 	**
  ** 	valores para la adición.																								**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- fieldName: Nombre del campo.																					**
  **	- tableName: Nombre de la tabla.																				**
  **	- tableKey:	Nombre del campo de llave primaria de la tabla.							**
  **	- tableValue: Valor.																										**
  **	- where: Condición.																											**
  **	-	orderBy: Condición de ordenamiento.																		**
  *****************************************************************************/
  function normalizedField($fieldName, $tableName, $tableKey, $tableValue, $where,$orderBy = "value ASC"){
    $this->normalized[$fieldName]['tableName'] = $tableName;	
    $this->normalized[$fieldName]['tableKey'] = $tableKey;	
    $this->normalized[$fieldName]['tableValue'] = $tableValue;	
    $this->normalized[$fieldName]['where'] = $where;
    $this->normalized[$fieldName]['orderBy'] = $orderBy;	
  }

	/*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	forceType ($fieldName,$inputType)																				**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función fuersa a un campo del formulario a un tipo expecífico sin 	**
  ** 	importar el tamaño.																											**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- fieldName: Nombre del campo.																					**
  ** 	- inputType: Tipo del campo.																						**
  ** 		- Para campos enum: "select" o "radio"																**
	**		- Para campos set: "multiselect" or "checkbox"												**
	**		- Para campos string o blob: "text" or "textarea"											**
  *****************************************************************************/
  function forceType($fieldName,$inputType){
    $this->forced[$fieldName] = $inputType;	    
  }
  
  function forceTypes($fieldNames,$inputTypes){
    if( sizeof($fieldNames) != sizeof($inputTypes) ) 
    	return false;
    
    for($i=0;$i<sizeof($fieldNames);$i++)	    
       $this->forced[$fieldNames[$i]] = $inputTypes[$i];	
       
    return true;    
  }  
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	disabledField ($fieldName)																							**
  ** 	disabledFields ($fieldNames)																						**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función deshabilita un campo del formulario.												**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- fieldName: Nombre del campo.																					**
  *****************************************************************************/  
  function disabledField($fieldName){
    $this->disabled[$fieldName] = "true";	    
  } 
  
  function disabledFields($fieldNames){
  	for($i=0;$i<sizeof($fieldNames);$i++)	    
      $this->disabled[$fieldNames[$i]] = "true";	    	    
  } 
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	hideField ($fieldName)																									**
  ** 	hideFields ($fieldNames)																								**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función enconde un campo del formulario.														**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- fieldName: Nombre del campo.																					**
  *****************************************************************************/
  function hideField($fieldName){
    $this->hidden[$fieldName] = "hide";	    
  }
  
  function hideFields($fieldNames){
    for($i=0;$i<sizeof($fieldNames);$i++)	    
       $this->hidden[$fieldNames[$i]] = "hide";	    
  }    
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	labelField ($fieldName,$fieldLabel)																			**
  ** 	labelFields ($fieldNames,$fieldLabels)																	**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función coloca la etiqueta del campo.															**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- fieldName: Nombre del campo.																					**
  **	-	fieldLabel: Etiqueta de campo.																				**
  *****************************************************************************/
  function labelField($fieldName,$fieldLabel){
    $this->labels[$fieldName] = $fieldLabel;	    
  }
  
  function labelFields($fieldNames,$fieldLabels){
    if( sizeof($fieldNames) != sizeof($fieldLabels) ) 
    	return 0;
    
    for($i=0;$i<sizeof($fieldNames);$i++)	    
       $this->labels[$fieldNames[$i]] = $fieldLabels[$i];	    
  }
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	labelField ($fieldName,$fieldLabel)																			**
  ** 	labelFields ($fieldNames,$fieldLabels)																	**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función le da el número para el orden en que aparecerán los campos.**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- fieldName: Nombre del campo.																					**
  **	-	place: Turno del campo.																								**
  *****************************************************************************/
  function orderField($campos){
		for($i = 0; $i < count($campos); $i++)
			$this->order[$campos[$i]] = $i;
	}
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	setLabelBreak ($HTML)																										**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función coloca el HTML inmediatamente después del tag label.				**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- HTML: Es código HTML.																									**
  *****************************************************************************/
  function setLabelBreak($HTML){
    $this->labelBreak = $HTML;
  }  
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	setLabelBreak ($HTML)																										**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función coloca el HTML inmediatamente después de cada tipo de campo**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- HTML: Es código HTML.																									**
  *****************************************************************************/
  function setFieldBreak($HTML){
    $this->fieldBreak = $HTML;
  }
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	setPrimaryKey ($pkey_name)																							**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función configura el nombre de la llave primaria de la tabla.			**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  **	- pkey_name: Nombre de la llave primaria de la tabla.										**
  *****************************************************************************/
  function setPrimaryKey($pkey_name){    
    $this->pkey = $pkey_name;
    return $this->pkey;
  }             
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	_putValue ($fieldName,$fieldType="text",$fieldValue="")									**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función es utilizada por printForm para escribir los valores de los**
  ** 	campos si el registro a sido recuperado utilizando el método getRecord()**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  ** 	- fieldName: Nombre del campo de la tabla.														 	**
  **	- fieldType: Tipo del campo.																						**
  *****************************************************************************/
  function _putValue($fieldName,$fieldType="text",$fieldValue=""){
    switch($fieldType){	    
	    case "textarea":	    
        if($this->record[$fieldName] != "")
          return $this->record[$fieldName];
        break;
        
      case "text":	    
        if($this->record[$fieldName] != "")
          return " value=\"".$this->record[$fieldName]."\"";
        break;
        
      case "select":	    
        if($this->record[$fieldName] == $fieldValue)
          return " selected";
        break;
        
      case "multi":	    
        if(strstr($this->record[$fieldName],$fieldValue))
          return " selected";
        break;
        
      case "radio":	    
        if($this->record[$fieldName] == $fieldValue)
          return " checked";
        break;
        
      case "checkbox":	    
        if(strstr($this->record[$fieldName],$fieldValue))
          return " checked";
        break;
    }
  }
      
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	_putLabel ($fieldName,$fieldLabel,$css="text",$focus=true)							**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**	
  ** 	Esta función es utilizada por printForm para escribir los tags HTML de  **
  ** 	todas las etiquetas. 																									 	**
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  ** 	- fieldName: Nombre del campo de la tabla															 	**
  **	- fieldLabel: Etiqueta para el campo.																		**
  *****************************************************************************/
  function _putLabel($fieldName,$fieldLabel,$css="text",$focus=true){
    if($focus) 
    	$onclick = " onClick=\"forms['$this->formName'].$fieldName.select();\"";
    if(!$this->NS4) 
    	return "<label class=\"".$css."label\" for=\"$fieldName\"$onclick><font size=2>".$fieldLabel."</font></label>$this->labelBreak";	    
    else 
    	return "<label class=\"".$css."label\" for=\"$fieldName\"><font size=2>".$fieldLabel."</font></label>$this->labelBreak";	    
  }    
  
  /*****************************************************************************
  ** 	NOMBRE:																																	**
  **																																					**
  ** 	printForm ($accion)																											**
  **																																					**
  ******************************************************************************
  ** 	OBJETIVO:																															 	**
  **																																					**
  ** 	Esta función se encarga de organizar y preparar el formulario completo. **
  **																																					**
  ******************************************************************************
  ** 	ARGUMENTOS: 																														**
  **																																					**
  ** 	- Accion: Acción a realizar al oprimir el botón enviar.								 	**
  **			- Si se deja vacio la clase realizará la actualización o adición.	 	**
  **			- Si se quiere manejar la adicón y actualización de otra manera se 	**
  **				debe colocar la dirección hacia donde se debe dirigir.					 	**
  *****************************************************************************/
  function printForm($accion){
    if( isset($_POST['submit']) ){ 
    	$this->submitForm(); 
    	return; 
    }      
          
    echo "<form name=\"$this->formName\" action=\"".$accion."\" method=\"POST\" style=\"margin:0\"><table class=\"grid\" align=center>\n";
    for ($n=0; $n < $this->columns; $n++){ 
     	$byForce = false;
      $name = @mysql_field_name($this->fields,$n);
      $type = @mysql_field_type($this->fields,$n);
      $len  = @mysql_field_len($this->fields,$n);
      $flag = @mysql_field_flags($this->fields,$n);
    	
      if(strstr($flag,"primary_key")) 
       	$this->setPrimaryKey($name);
        
      if(isset($this->labels[$name])) 
       	$label = $this->labels[$name];
      else 
       	$label = $name;
        
      if(isset($this->forced[$name])) 
       	$byForce = $this->forced[$name];
        
      if(isset($this->hidden[$name])) 
       	$type = "hidden";
        
      if(isset($this->normalized[$name]) ) 
       	$valuePairs = true;
      else
        $valuePairs = false;
				
			if(isset($this->disabled[$name])) 
				$dis = "disabled=\"true\" value=0";
			else
				$dis = "";
				
			if(isset($this->order[$name]))
				$turno = $this->order[$name];
			else
				$turno = $n;
			
			$forma[$turno] = "";
				
			switch($type){
       	case "real":
       		$forma[$turno] .= "<tr><td>";
         	if($valuePairs){
         	 	$forma[$turno] .= $this->_putLabel($name,$label,"select",false);
          	$forma[$turno] .= "</td><td>";
          	$this->_getFieldData($name);
           	$forma[$turno] .= "<select ".$dis." name=\"$name\" id=\"$name\" size=\"1\" class=\"select\">\n";
            for($i=0;$i<$this->normalized[$name]['pairs'];$i++)
              $forma[$turno] .= "  <option value=\"".$this->normalized[$name]['keys'][$i]."\"".$this->_putValue($name,"select",$this->normalized[$name]['keys'][$i]).">".$this->normalized[$name]['values'][$i]."</option>\n";
            $forma[$turno] .= "</select>$this->fieldBreak";
          }else{
          	$forma[$turno] .= $this->_putLabel($name,$label);
           	$forma[$turno] .= "</td><td>";
             if($len<$this->textInputLength) $length = $len; else $length=$this->textInputLength; 
             $forma[$turno] .= "<input ".$dis." type=\"text\" name=\"$name\" id=\"real\" size=\"$length\" MAXLENGTH=\"$len\" class=\"real\"".$this->_putValue($name).">$this->fieldBreak";
          }
          $forma[$turno] .= "</td></tr>";
			 		break;
        	
        case "int":                
    			$forma[$turno] .= "<tr><td>";
       		if($valuePairs){
       	  	$forma[$turno] .= $this->_putLabel($name,$label,"select",false);
         		$forma[$turno] .= "</td><td>";
          	$this->_getFieldData($name);
          	$forma[$turno] .= "<select ".$dis." name=\"$name\" id=\"$name\" size=\"1\" class=\"select\">\n";
            for($i=0;$i<$this->normalized[$name]['pairs'];$i++)
              $forma[$turno] .= "  <option value=\"".$this->normalized[$name]['keys'][$i]."\"".$this->_putValue($name,"select",$this->normalized[$name]['keys'][$i]).">".$this->normalized[$name]['values'][$i]."</option>\n";
            $forma[$turno] .= "</select>$this->fieldBreak";
          }else{
          	$forma[$turno] .= $this->_putLabel($name,$label);
          	$forma[$turno] .= "</td><td>";
            if($len<$this->textInputLength) 
            	$length = $len; 
            else 
            	$length=$this->textInputLength; 
            $forma[$turno] .= "<input ".$dis." type=\"text\" name=\"$name\" id=\"int\" size=\"$length\" MAXLENGTH=\"$len\" class=\"int\"".$this->_putValue($name).">$this->fieldBreak";
          }
          $forma[$turno] .= "</td></tr>";
          break; 
   
        case "blob":
         	$forma[$turno] .= "<tr><td>";
          $forma[$turno] .= $this->_putLabel($name,$label);
          $forma[$turno] .= "</td><td>";
          if(($len>$this->strField_toggle || $byForce == "textarea") && $byForce != "text" )
           	$forma[$turno] .= "<textarea ".$dis." name=\"$name\" id=\"$name\" rows=\"$this->textareaRows\" cols=\"$this->textareaCols\" class=\"textarea\">".$this->_putValue($name,"textarea")."</textarea>$this->fieldBreak";
          else 
          	$forma[$turno] .= "<input ".$dis." type=\"text\" name=\"$name\" id=\"blob\" size=\"$this->textInputLength\" MAXLENGTH=\"$len\" class=\"text\"".$this->_putValue($name).">$this->fieldBreak";
          $forma[$turno] .= "</td></tr>";
        	break; 
   
        case "string":
          $forma[$turno] .= "<tr><td>";
          if( strstr($flag,"enum") ){
          	if($valuePairs) 
          		$this->_getFieldData($name);
          	else 
          		$options = $this->_mysql_enum_values($this->table,$name);
            if( ($len > $this->enumField_toggle || $byForce == "select") && $byForce != "radio"){
            	$forma[$turno] .= $this->_putLabel($name,$label,"",false);
            	$forma[$turno] .= "</td><td>";
            	$forma[$turno] .= "<select ".$dis." name=\"$name\" id=\"$name\" size=\"1\" class=\"select\">\n";
              
            	if( $valuePairs )
            		for($i=0;$i<$this->normalized[$name]['pairs'];$i++)
            			$forma[$turno] .= "  <option value=\"".$this->normalized[$name]['keys'][$i]."\"".$this->_putValue($name,"select",$this->normalized[$name]['keys'][$i]).">".$this->normalized[$name]['values'][$i]."</option>\n";
            	else 
              	foreach($options as $opt) 
              	  $forma[$turno] .= "  <option value=\"$opt\"".$this->_putValue($name,"select",$opt).">$opt</option>\n";
                   
            	$forma[$turno] .= "</select>$this->fieldBreak";
          	}else{
            	$forma[$turno] .= $this->_putLabel($name,$label,"",false);
            	$forma[$turno] .= "</td><td>";
            	if($valuePairs)
                for($i=0;$i<$this->normalized[$name]['pairs'];$i++){
                	$forma[$turno] .= "  <input type=\"radio\" name=\"$name\" id=\"{$name}_".$this->normalized[$name]['keys'][$i]."\" value=\"".$this->normalized[$name]['keys'][$i]."\" class=\"radio\"".$this->_putValue($name,"radio",$this->normalized[$name]['keys'][$i]).">";	                      
                  $forma[$turno] .= $this->_putLabel($name."_".$this->normalized[$name]['keys'][$i],$this->normalized[$name]['values'][$i],"radio");                         
                }
              else 
                foreach($options as $opt){
                  $forma[$turno] .= "  <input ".$dis." type=\"radio\" name=\"$name\" id=\"{$name}_{$opt}\" value=\"$opt\" class=\"radio\"".$this->_putValue($name,"radio",$opt).">";
                  $forma[$turno] .= $this->_putLabel($name."_".$opt,$opt,"radio");
                }
            }  
          }else if( strstr($flag,"set") ){
          	if( $valuePairs ) 
          		$this->_getFieldData($name);
            else 
            	$options = $this->_mysql_enum_values($this->table,$name);
          	if( ($len > $this->enumField_toggle || $byForce == "multiselect") && $byForce != "checkbox" ){
          		$forma[$turno] .= $this->_putLabel($name,$label,"",false);
              $forma[$turno] .= "<select ".$dis." name=\"".$name."[]\" id=\"$name\" size=\"$this->multiSelectSize\" multiple=\"multiple\" class=\"multiselect\">\n";
              if( $valuePairs )
                for($i=0;$i<$this->normalized[$name]['pairs'];$i++)
                  $forma[$turno] .= "  <option value=\"".$this->normalized[$name]['keys'][$i]."\"".$this->_putValue($name,"multi",$this->normalized[$name]['keys'][$i]).">".$this->normalized[$name]['values'][$i]."</option>\n";
              else 
                foreach($options as $opt) 
                  $forma[$turno] .= "  <option value=\"$opt\"".$this->_putValue($name,"multi",$opt).">$opt</option>\n";
              $forma[$turno] .= "</select>$this->fieldBreak"; 
            }else{
            	$forma[$turno] .= $this->_putLabel($name,$label,"",false);
            	$forma[$turno] .= "</td><td>";
            	$cb = 0;
              if($valuePairs)
                for($i = 0; $i < $this->normalized[$name]['pairs']; $i++){
                	$forma[$turno] .= "  <input ".$dis." type=\"checkbox\" name=\"".$name."[]\" id=\"{$name}_{$cb}\" value=\"".$this->normalized[$name]['keys'][$i]."\"".$this->_putValue($name,"checkbox",$this->normalized[$name]['keys'][$i]).">";
                 	$forma[$turno] .= $this->_putLabel($name."_".$cb,$this->normalized[$name]['values'][$i],"checkbox");
                 	$cb++;
                }
              else 
                foreach($options as $opt){
                	$forma[$turno] .= "  <input ".$dis." type=\"checkbox\" name=\"".$name."[]\" id=\"{$name}_{$cb}\" value=\"$opt\"".$this->_putValue($name,"checkbox",$opt).">";
                 	$forma[$turno] .= $this->_putLabel($name."_".$cb,$opt,"checkbox");
                 	$cb++;
                }
            }     
          }else{
        		$forma[$turno] .= $this->_putLabel($name,$label);
        		$forma[$turno] .= "</td><td>";
          	if($len < $this->textInputLength) $length = $len; else $length=$this->textInputLength;
          	if(($len>$this->strField_toggle || $byForce == "textarea") && $byForce != "text")
            	$forma[$turno] .= "<textarea ".$dis." name=\"$name\" id=\"$name\" rows=\"$this->textareaRows\" cols=\"$this->textareaCols\" class=\"textarea\">".$this->_putValue($name,"textarea")."</textarea>$this->fieldBreak";
          	else 
          		$forma[$turno] .= "<input ".$dis." type=\"text\" name=\"$name\" id=\"string\" size=\"$length\" MAXLENGTH=\"$len\" class=\"text\"".$this->_putValue($name).">$this->fieldBreak";
          }
          $forma[$turno] .= "</td></tr>";
        	break; 
   
        case "date":
       		$forma[$turno] .= "<tr><td>";
          $forma[$turno] .= $this->_putLabel($name,$label);
          $forma[$turno] .= "</td><td>";
          $value = ( isset($this->record) )?($this->_putValue($name)):("value=\"0000-00-00\"");
					$forma[$turno] .= "<input ".$dis." type=\"text\" name=\"$name\" id=\"$name\" size=\"10\" MAXLENGTH=\"10\" $value class=\"date\">";
					$dsel = new DateSel("document.".$this->formName.".".$name.".value",false,'su','yyyy-mm-dd');
					$forma[$turno] .= $dsel->ChangeButton('both');
					$forma[$turno] .= $dsel->DrawCal();
					$forma[$turno] .= $dsel->AddJavascript();
					$today = getdate(); 
					$month = $today['mon'];
					$mday = $today['mday']; 
					$year = $today['year'];
					if($month < 10)
						$forma[$turno] .= $dsel->setDate('y'.$year.'m0'.$month.'d'.$mday);
					else
						$forma[$turno] .= $dsel->setDate('y'.$year.'m'.$month.'d'.$mday);
					$forma[$turno] .= "$this->fieldBreak";
					$forma[$turno] .= "</td></tr>";
					break; 
           
        case "datetime":
       		$forma[$turno] .= "<tr><td>";
          $forma[$turno] .= $this->_putLabel($name,$label);
          $forma[$turno] .= "</td><td>";
          $value = ( isset($this->record) )?($this->_putValue($name)):("value=\"0000-00-00 00:00:00\"");
          $forma[$turno] .= "<input ".$dis." type=\"text\" name=\"$name\" id=\"date\" size=\"19\" MAXLENGTH=\"19\" $value class=\"text\">$this->fieldBreak";
          $forma[$turno] .= "</td></tr>";
          break; 
           
        case "timestamp":
       		$forma[$turno] .= "<tr><td>";
          for($ts=0;$ts<$len;$ts++) $zeroes .= "0";
          	$value = ( isset($this->record) )?($this->_putValue($name)):("value=\"$zeroes\"");
          $forma[$turno] .= $this->_putLabel($name,$label);
          $forma[$turno] .= "</td><td>";
          $forma[$turno] .= "<input ".$dis." type=\"text\" name=\"$name\" id=\"timestamp\" size=\"$len\" MAXLENGTH=\"$len\" $value class=\"text\">$this->fieldBreak";
          $forma[$turno] .= "</td></tr>";
          break; 
           
        case "time":
       		$forma[$turno] .= "<tr><td>";
          $forma[$turno] .= $this->_putLabel($name,$label);
          $forma[$turno] .= "</td><td>";
          $value = ( isset($this->record) )?($this->_putValue($name)):("value=\"00:00:00\"");
          $forma[$turno] .= "<input ".$dis." type=\"text\" name=\"$name\" id=\"time\" size=\"8\" MAXLENGTH=\"8\" $value class=\"text\">$this->fieldBreak";
          $forma[$turno] .= "</td></tr>";
          break; 
           
        case "year":
       		$forma[$turno] .= "<tr><td>";
          $forma[$turno] .= $this->_putLabel($name,$label);
          $forma[$turno] .= "</td><td>";
          $value = ( isset($this->record) )?($this->_putValue($name)):("value=\"0000\"");
          $forma[$turno] .= "<input ".$dis." type=\"text\" name=\"$name\" id=\"year\" size=\"4\" MAXLENGTH=\"4\" $value class=\"text\">$this->fieldBreak";
          $forma[$turno] .= "</td></tr>";
          break; 
           
        case "hidden":
          $value = ( isset($this->record) )?($this->_putValue($name)):("value=\"0000\"");
          $forma[$turno] .= "<input ".$dis." type=\"hidden\" name=\"$name\" id=\"hidden\" size=\"4\" MAXLENGTH=\"4\" $value class=\"text\">$this->fieldBreak"; 	
          break;
      } //end switch
    } //end for
    for($j=0;$j<$this->columns;$j++)
   		echo $forma[$j];
    if( isset($this->record) ) 
      echo "<input type=\"hidden\" name=\"pkey\" value=\"$this->pkeyID\">\n";
    echo "<tr align=center><td colspan=2>
    			<input type=\"reset\" value=\"Reestablecer\" name=\"reset\" onClick=\"return confirm('Est&#225 seguro de reestablecer?')\" class=\"button\"> 
    			<input type=\"submit\" name=\"submit\" value=\"Enviar\" onClick=\"return validateForm()\" class=\"button\">
    			</td></tr></table></form>\n";
  } //end function printForm 
} //end class
?>
Return current item: Forms class