Page 1 of 1

form class

Posted: Sat Apr 15, 2006 10:31 am
by pleigh
hi guys, just wanna know your opinion on this...is it a good practice to make a form class, instead of hardcoding it in the editor? a good example will be an excerpt from my book:

Code: Select all

class Form
{
var $fields=array();
var $processor;
var $submit = "Submit Form";
var $Nfields = 0;

function __construct($processor,$submit)
{
$this->processor = $processor;
$this->submit = $submit;
}

function displayForm()
{
echo "<form action='{$this->processor}' method='post'>";
echo "<table width=’100%’>";
for($j=1;$j<=sizeof($this->fields);$j++)
{
echo "<tr><td align=\"right\">
{$this->fields[$j-1]['label']}: </td>\n";
echo "<td>
<input type='text'
name=’{$this->fields[$j-1]['name']}'>
</td></tr>\n";
}
echo "<tr><td colspan=2 align='center'>
<input type='submit'
value=’{$this->submit}’></td></tr>\n";
echo "</table>";
}

function addField($name,$label)
{
$this->fields[$this->Nfields]['name'] = $name;
$this->fields[$this->Nfields]['label'] = $label;
$this->Nfields = $this->Nfields + 1;
}
}

echo "<html><head><title>phone form</title></head><body>";
$phoneForm = new Form("classes.php", "submit phone");
$phoneForm->addField("firstname", "First Name");
$phoneForm->addField("lastname", "Last Name");
$phoneForm->addField("phone", "label");

echo "<h3>Please fill out the following form:</h3>";
$phoneForm->displayForm();
echo "</body></html>";
thanks in advance. :)

Posted: Sat Apr 15, 2006 10:35 am
by feyd
A render class such as this helps keep nice, uniform output. So I tend to use them quite a bit. It also can allow you to more easily change the render target from HTML to say PDF or XML.

Posted: Sat Apr 15, 2006 10:56 am
by pleigh
tnx feyd..a quick one, i'm really newb in OO of php, so if you can explain to me what the loop is doing in line 9? :oops:

Code: Select all

for($j=1;$j<=sizeof($this->fields);$j++)
how does it help the function?

Posted: Sat Apr 15, 2006 10:58 am
by feyd
it iterates over the fields that have been added to the object for output.

Posted: Sat Apr 15, 2006 11:00 am
by pleigh
ok feyd, tnx a lot. :wink: