Location: PHPKode > scripts > Form Generator > form-generator/formgen.php
<?php
	//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//
	// Form Maker Class v0.1 Public					//
	// By: ADZ							//
	// Project: Sphinx Experimentation For IG Group			//
	// Updated On: Jul 16, 2009 5:27 AM			  	//
	//							  	//
        // This makes HTML forms very easily with as little parameters	//
	// parameters as possible while providing a huge amount of   	//
	// flexibility.							//
	//								//
	// Layout:							//
	// * Instance Variables - these are used throughout the whole 	//
	//   class for storage, counting, and configuration. All config	//
	//   is available through Config Functions			//
	// * Config Functions - used to configure global parameters	//
	//   * SetTable: Sets the Width, Column Width, and Border of	//
	//     the standard table.					//
	// * Main Add Functions - these are used to add HTML elements 	//
	//   to a form. Please use this whenfever possible.		//
	//   * AddField: Supports most HTML Form Elements (Text, 	//
	//     Textarea, Checkbox, Select, and Radio), as well as 	//
	//     ranges (Textbox - Textbox and Select - Select).		//
	//     Paramets for each are described thoroughly in the 	//
	//     function headers as well as the documentation (to come)	//
	//   *  
	// 								//		
        //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//

	class FormGen {
		///////////////////////
		//INSTANCE VARIABLES //
		///////////////////////
				
		//STORAGE
		var $form = array(); //main array to store form fields until output		

		//COUNTER
		var $seq_name = 0; //counts unnamed fields
		var $form_counter = 0; //counts total fields
		
		//TABLE CONFIGURATION VARIABLES (set through setTable)
		var $table_width = '100%';
		var $table_label_column = '40%';
		var $table_border = 1;

		/////////////////////
		//CONFIG FUNCTIONS //
		/////////////////////
				
		//SET TABLE:
		//Sets the parameters of the table
		function setTable($width, $label_column = '40%', $border=1) {
			$table_width = $width;
			$table_label_column = $label_column;
			$table_border = $border;
		}
		
		//////////////////////
		//MAIN ADD FUNCTIONS//
		//////////////////////
				
		//ADD FIELD
		//This is the main add function allowing to add
		
		function addField($label, $type="text", $name="", $description="", $options="", $value="", $properties="", $output='add_to_form') {
			$out = ""; //holds the output
			switch ($type) {
				case "text":
					$out = $this->addText($label, $name, $description, $value);
					break;
				case "textarea":
					$out = $this->addTextarea($label, $options, $name, $description);
					break;					
				case "checkbox":
					$out = $this->addCheckbox($label, $options, $name, $description);
					break;
				case "select":
	    				if(!isset($properties) || $properties=="") {
						$out = $this->addSelect($label, $options, $name, $description);
					}
					else {
						foreach($properties as $property) {
							if ($property == "multiple") {
								$out = $this->addSelect($label, $options, $name, $description, true);
							}
						}
					}
					break;
				case "radio":
					$out = $this->addRadio($label, $options, $name, $description);
					break;
				case "textRange":
					$out = $this->addTextRange($label, $name, $description, $value);
					break;
				case "selectRange":
					$out = $this->addSelectRange($label, $options, $name, $description);
					break;
			}
			
			if($output=='add_to_form') {
				$this->form[$this->form_counter]['label_box'] = $out['label_box'];
				$this->form[$this->form_counter]['description_box'] = $out['description_box'];
				$this->form[$this->form_counter]['field_box'] = $out['field_box'];
				$this->form_counter++; //increment the field counter
			}
			else {
				return $out;
			}
		}


		//////////////////////////
		//FIELD ADDER FUNCTIONS //
		//////////////////////////
				
		// These are used by the addField Function to get the code needed to make a field. 
		// All these functions accept label, description, which are used to form the label and description boxes
		// All these functions accept name which is used internally to name the field and options where appropriate. Name is optional as it can be generated sequentially
		//
		// All these functions return an array of 3 HTML bits:
		// * label_box: has the label
		// * description_box: has the description
		// * field_box: has the field(s)		
				
		// ADD TEXT
		function addText($label, $name="", $description="", $value="") {
			
			//INSTANCE VARIABLES
			$out = array(); //holds output

			$this->standardMake($name,$label,$description, $out); //Set the name, label, and description through the standard make function

			$out['field_box'] = "<input style='width:100%' type='text' name='{$name}' value='{$value}' />";
			
			return $out;
		}
				
		// ADD TEXT AREA
		function addTextarea($label, $name="", $description="", $value="") {
			//INSTANCE VARIABLES
			$out = array();

			$this->standardMake($name,$label,$description, $out); //Set the name, label, and description through the standard make function

			$out['field_box'] = "<textarea style='width: 100%; height:150; padding: 0; margin: 0' type='text' name='{$name}'>{$value}</textarea>";

			return $out;
		}
		
		// ADD RADIO
		// Label, Name, Description: Standard
		// Options accepted as array of Array { [0] label -> "Label1" name -> "name1" checked -> false [1] label -> "Label2" name -> "name2" checked -> false ... } 
		function addRadio($label, $options, $name="", $description="") {
			//INSTANCE VARIABLES
			$out = array();
			$fields = ""; //stores html for fields
			$element_list = array(); //an array of elements that will be passed to the table maker
			$element_counter = 0; //element counter we use when adding a new element	
	
			$this->standardMake($name,$label,$description, $out); //Set the name, label, and description through the standard make function
			
			$options = $this->choiceParse($options,$name,false); //send in the options variable for repair :)
			
			foreach($options as $option) {
				if($option['checked'] == true) {
					$option['checked'] == "CHECKED";
				}
				
				$element_list[$element_counter]['label'] = $option['label'];
				$element_list[$element_counter]['content'] = "<input type='radio' name='{$name}' value='{$option['name']}' {$option['checked']} />";
				$element_counter++;
			}
			
			$out['field_box'] = $this->addToTable($element_list); //build our field box through the table adder
		
			return $out; //spit out our stuff
		}

		// ADD SELECT
		// Options accepted as array of Array { [0] label -> "Label1" name -> "name1" checked -> false [1] label -> "Label2" name -> "name2" checked -> false ... } 
		// Multiple specifies whether it is a multiple select box (true or false)
		function addSelect($label, $options, $name="", $description="", $multiple = false) {
			//INSTANCE VARIABLES
			$out = array();
			$fields = ""; //stores html for fields
							
			$this->standardMake($name,$label,$description, $out); //Set the name, label, and description through the standard make function
						
			$options = $this->choiceParse($options,$name,$multiple); //send in the options variable for repair :)
				
			if($multiple==true) {
				$multiple = "MULTIPLE";
			}
			$fields = "<select $multiple style='width:100%' name='{$name}'>";
												
			foreach ($options as $option) {
				$fields .= "<option value='{$option['name']}'> {$option['label']} </option>";
			}
		
			$fields .= "</select>";
			
			$out['field_box'] = $fields;
			
			return $out;
		}

	
		// ADD CHECK BOX		
		// Options accepted as array of Array { [0] label -> "Label1" name -> "name1" checked -> false [1] label -> "Label2" name -> "name2" checked -> false ... } 
		function addCheckBox($label, $options, $name="", $description="") {
			//INSTANCE VARIABLES
			$out = array();
			$fields = ""; //stores html for fields
			$element_list = array(); //an array of elements that will be passed to the table maker
			$element_counter = 0; //element counter we use when adding a new element
						
			$this->standardMake($name,$label,$description, $out); //Set the name, label, and description through the standard make function
						
			$options = $this->choiceParse($options,$name,true); //send in the options variable for repair :)
			
			foreach($options as $option) {
				if($option['checked'] == true) {
					$option['checked'] = "CHECKED";
				}
				$element_list[$element_counter]['label'] = $option['label'];
				$element_list[$element_counter]['content'] = "<input type='checkbox' name='{$name}' value='{$option['name']}' {$option['checked']} />";
				$element_counter++; 
			}
			
			$out['field_box'] = $this->addToTable($element_list); //build our field box through the table adder
			
			return $out; //spit out the result
		}
		
				
		//ADD TEXT RANGE
		//Label, Name, Description: Standard
		//Value: Holds the minimum and maximum value that will show in the text fields, comma space separated (ex: "0, 100")
		function addTextRange($label, $name="", $description="", $value="") {
			//INSTANCE VARIABLES
			$out = array();
			$min = ''; //stores the minimum value of the text range
			$max = ''; //stores the maximum value of the text range
			$fields = ""; //stores html for fields

			$this->standardMake($name,$label,$description, $out); //Set the name, label, and description through the standard make function
						
			//If our use specified a min/max it will be in value...let's extract it
			if ($value != "") {
				$value = explode (", ", $value);
				$min = $value[0];
				$max = $value[1]; 
			}

			$box1 = $this->addText("null", $name . "__min", "", $min); //make the min text field (we only need the field part of it, so we can make the name and discription whatever)
			$box2 = $this->addText("null", $name . "__max", "", $max); //make the max text field
			
			$out['field_box'] = "<table style='width:100%'><tr><td>{$box1['field_box']}</td><td style='width:0'> to </td><td><input style='width:100%' type='text' name='{$name}__max' value='{$max}' /></td></tr></table>";

			return $out;
		}
		//ADD SELECT RANGE
		function addSelectRange($label, $options, $name="", $description="" ) {
			//INSTANCE VARIABLES
			$out = array();
			$min = ''; //stores the minimum value of the text range
			$max = ''; //stores the maximum value of the text range
			$fields = ""; //stores html for fields

			$this->standardMake($name,$label,$description, $out); //Set the name, label, and description through the standard make function
						
			$options = $this->choiceParse($options,$name,false); //send in the options variable for repair :)
				
			$box1 = $this->addSelect("null", $options, $name . "__min"); //make the min select field (we only need the field part of it, so we can make the name and discription whatever)
			$box2 = $this->addSelect("null", $options, $name . "__max"); //make the max select field

			$out['field_box'] = "<table style='width:100%'><tr><td> {$box1['field_box']} </td><td style='width:0'> to </td><td>{$box2['field_box']}</td></tr></table>";
			return $out;
		}

		
		function nextName() {
			return $this->seq_name;
			$this->seq_name++;
		}

		function makeForm($action='index.php?action=process', $format='table') {
			$out = ""; //will store the output as a string if needed			
			if ($format=="table") {
				$out .= "<form action='{$action}' method='post'>"; //make form header
				$out .= "<table border='{$this->table_border}' width='{$this->table_width}'>";
				
				foreach ($this->form as $field) {
					if($field['label_box']!="" && $field['field_box']!="") {
						$out .= "<tr>
							<th width='{$this->table_label_column}'> {$field['label_box']} <br/> <small> {$field['description_box']} </small> </th>
							<td> {$field['field_box']} </td>
							</tr>";
					}

					else if($field['type'] == "section") {
						$out .= "</table> <h2> {$field['label']} </h2> {$field['description']} <table border='{$this->table_border}' width='{$this->table_width}'>";
					}
				}
				$out .= "</table>";
				$out .= "<input class='button' type='submit' value='Go!'/>";
				$out .= "</form>";
				return $out;
			}

			if ($format=='field_array') {
				return $form;
			}
		}
	
	////////////////////
	// SPECIAL FIELDS //
	////////////////////

	//These are the special fields that are too weird to be included in the standard addField function
				
	//Adds a Section using fields unique to it (type=section, label=.., description=...) so that the form maker can parse it differentlty from the REGULAR fields
	function addSection($label, $description) {
		$this->form[$this->form_counter]['label'] = $label;
		$this->form[$this->form_counter]['description'] = $description;
		$this->form[$this->form_counter]['type'] = "section";
		$this->form_counter++;
	}		
		
	//////////////////////
	// HELPER FUNCTIONS //
	//////////////////////
	//Generic-ish functions used throughout the code
		
		
	//Constructs a table given an array of HTML elements (Label and 
	//max_columns: what is max amount of columns we can have until we start a new row
	function addToTable($html, $max_columns=2, $label_percent=90) { 
		//INSTANCE VARIABLES
		$column_current = 0; //holds the current column number
		$output = ""; //holds the output table
				
		//CALCULATIONS
		$column_label_width = ((100 / $max_columns) * ($label_percent) * .01) . "%"; //the label
		$column_content_width = ((100 / $max_columns) * (100 - $label_percent) * .01) . "%";
				 
		$output = "<table>"; //start the table
				
		foreach($html as $element) {
			//FIGURE OUT IF WE SHOULD START A NEW ROW
			if ($column_current == 0) { //if the table hasn't been started 
				$output.= "<tr>";
			}
					
			$output .= "<td style='border-top: solid; border-bottom: solid; border-left:solid; width:{$column_label_width}'> {$element['label']} </td> <td style='border-top: solid; border-bottom: solid; border-right:solid; width: {$column_content_width}'> {$element['content']} </td>";
					
			if($column_current == $max_columns - 1) { //we reached the last column
				$output .= "</tr>"; //finish it up!
				$column_current = 0; //go back to 0
			}
			else {
				$column_current++; //increment to the next column number
			}
		}
		
		$output .= "</table>"; //finish up the table
		return $output; //spit out the result
	}
			
	// STANDARD MAKE
	//This sets the label, description, and name if needed....Standard stuff but maybe somebody wants to edit it...
	function standardMake(&$name, &$label, &$description="", &$out) {
		//If there is no name give it a name
		if ($name == "") {
			$name = $this->nextName();
		}
			
		$out['label_box'] = $label;
		$out['description_box'] = $description;
	}
	
			
	// CHOICE PARSE
	// (Applies to Radio, Checkbox, and Select)
	function choiceParse($options,$name,$multiple=false) { //name refers to the element name (so that we can name the choices accordingly)
		//INSTANCE VARIABLE
		$option_counter = 0; //might be used to count the radio field options
			
		//If the user used the Label1:Name1:Check2, Label2:Name2:Check2 format of adding
		if (!is_array($options)) {
						
			$options_exploded = explode(", ", $options); //now we have an array of Label:Name:Check values
			unset($options); //we no longer need the old option structure since we are making it an array
									
			//Test if the user even specified a name and check value...
			$option_exploded = explode(":", $options_exploded[0]);
			if (!isset($option_exploded[1])) { //if the 2nd group (name) is not set guess he did not set it :(
				//Set the label and "" and false for the name and checked values so that they can be handled later on
		
				foreach($options_exploded as $key=>$option) {
					$options[$key]['label'] = $option;
					$options[$key]['name'] = "";
					$options[$key]['checked'] = false;
				}
			}
				
			else { //Otherwise we need to set all 3 properties
				//Go through each Option Group
				
				foreach($options_exploded as $key=>$option) {
					$property = explode(":",$option); //now we have 3 groups
					if (!isset($property[2]) || $property[2] == "") { //if it's not set we assume false. anything else is true
						$property[2] = false;
					}
					
					$options[$key]['label'] = $property[0];
					$options[$key]['name'] = $property[1];
					$options[$key]['checked'] = $property[2];
				}
			}
		}
					
		//Now, either way, options is an array of Array { [0] label -> "Label1" name -> "name1" checked -> false [1] label -> "Label2" name -> "name2" checked -> false ... } so we can do some further processing and pass it on...

		//Set the names. If this is a checkbox or multi-select we need a [] to make it an array...
		foreach($options as $key=>$option) {
			//The user specified no name for this option so we give it a [] name and append to the field name. This is usefull for a select and checkbox. It will give a numeric array of options
			if ($option['name'] == "" && $multiple == true) {
			$options[$key]['name'] = $name . "[]";
			}	
			
			//This is useful for a numeric array of radio buttons (for example rate this 0-10). Just spit back an empty string for future handling
			else if($option['name'] == "" && $multiple == false) {
				$options[$key]['name'] = $option_counter;
				$option_counter++;
			}
				
			//This is useful for selects and checkboxes where a user wants to name each option specifically
			else if($option['name'] != "" && $multiple == true) {
				$options[$key]['name'] = $name . "[{$option['name']}]";
			}
				
			//This is usefull for a radio button. It will result in an array of options with the same name. $option[name] will be used in VALUE
			else if($option['name'] != "" && $multiple == false) {
				$options[$key]['name'] = $name; //return the name for future handling
			}
		}	
		return $options; //return the new and improved $option
	}
}
Return current item: Form Generator