form class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
pleigh
Forum Contributor
Posts: 445
Joined: Wed Jan 19, 2005 4:26 am

form class

Post 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. :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
pleigh
Forum Contributor
Posts: 445
Joined: Wed Jan 19, 2005 4:26 am

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it iterates over the fields that have been added to the object for output.
User avatar
pleigh
Forum Contributor
Posts: 445
Joined: Wed Jan 19, 2005 4:26 am

Post by pleigh »

ok feyd, tnx a lot. :wink:
Post Reply