Jump to content

Form Class Help


ChadNomad

Recommended Posts

I'm writing a class (or trying) to make forms quicker to produce. Heres an example function:

 


function input($type, $class, $value, $newline)
{
	if (!empty($type))
	{
		$html .= "type=".$type.self::space;
	}

	if (!empty($class))
	{
		$html .= "class=".$class.self::space;
	}

	if (!empty($value))
	{
		$html .= "value=".$value.self::space;
	}

	if (!empty($newline))
	{
		$html .= self::lineBreak;
	}

	$this->output = '<input '.$html.' />'.self::newLine;

	echo $this->output;
}

 

What would be a better approach to all the if statements or is that perfectly fine?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/117509-form-class-help/
Share on other sites

make each tag type it's own class.

 

so for an input tag you could use this:

 

<?php

class input {

private $options = array();

function __construct($name = NULL, $type = NULL){
	if($type) $name = array('name' => $name, 'type' => $type);
	if(is_array($name)) $this->fill($name);	
}

function fill($stuff){
	foreach($stuff as $option=>$value) $this->options[$option] = $value;
}

function setOption($option,$value){
	$this->options[$option] = $value;	
}

////insert more add/modify methods here


function getHTML(){
	$html = '<input';
	foreach($this->options as $option=>$value) $html .= " $option='$value'";
	$html .= ">";

	return $html;
}

function printHTML(){
	echo $this->getHTML();
}
}
?>

 

This class keeps all options (everything in the form of something="value") in one array.  This is just a prototype... I wrote it off the top of my head and rather quickly, so it could stand for some cleaning up.

 

  When you create the object, you can either just define the name and type of the input like:

 

$foo = new input('name', 'type');

 

or pass an array of options to it:

 

$options = array('name' => 'bar', 'type' =>'text', 'class' => 'someclass');

$foo = new input($options);

 

Passing no arguments will just create an empty object.

 

Additional options are set and unset with fill() in array form, or by setOption() like:

 

$foo->setOption('options', 'value');

 

getHTML() returns the html string wile printHTML() echos it out

 

 

I have a select class similar to this that is exceedingly useful.  I event went so far as to write a tag class that will build any html tag given type, options (within the opening tag) and the contents (between the tags).  If you go that route, the above code would simplify even more.

 

Link to comment
https://forums.phpfreaks.com/topic/117509-form-class-help/#findComment-604477
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.