Making PHP Forms Object-Oriented - Example of a Form (Page 6 of 7 ) Now we are equipped for the final touch: building a small example. I will demonstrate creation of the first page of a wizard that should collect some information. Let's say, about a subscription to some internet resource. As the first step, the user must enter the username he/she is going to use and a valid email address, then select the type of the registration. Based on the registration type the user chooses, the wizard should proceed to a corresponding screen. Before the wizard can proceed, it validates values that the user enters. I will not build the forms for the second step. There's not much interesting to do without introducing additional input classes; and I would still like the article's subject to stay on the same topic. <?php
define('MinNameLength', 5); class RegForm01 extends FormProcessor { function CustomCheck() { if (strlen($this->Values['Name']) < MinNameLength) $this->Errors['Name'] = 'Username should contain at least ' . MinNameLength . ' symbols'; if ($this->Values['Email']) { if (!eregi('^[-!#$%&\'*+\\./0-9=?A-Z^_\`a-z{|}~]+ @[-!#$%&\'*+\\/0-9=?A-Z^_\`a-z{|}~]+\.[-!#$%&'*+ '\\./0-9=?A-Z^_\`a-z{|}~]+$', $this->Values['Email'])) $this->Errors['Email'] = 'Value entered does not appear to be a valid e-mail address'; } else { $this->Errors['Email'] = 'E-mail address is required to complete subscription'; } } function NextWizardPage() { //decision about what wizard's screen to load next is made here, //based on the submitted values: return ($this->Values['PaymentMethod'] == 'P')?'reg_form_free.php':'reg_form_payed.php'; } function StoreData() { // we will not discuss storing persistent variables in this article. // here would normally appear code that updates a database or // stores session variables STORE_VARIABLE($this->Values['Name']); } function DisplayForm() { // I'm not sure you meet a form like this on a real web-site =), but I hope // it'll do for the example
?> <form action="<?php echo $PHP_SELF?>" method="POST"> Username: <?php new TextInput($this, 'Name', '', 'size="30" maxlength="100"')?> <?php $this->ErrorReport('Name')?>
Email: <?php new TextInput($this, 'Email', '', 'size="30" maxlength="100"')?> <?php $this->ErrorReport('Email')?> <br><br> Subscription type:<br> <?php new RadioButtons($this, 'SubscrType', array('P'=>'Preview', 'M'=>'Membership'), 'P')?> <?php $this->ErrorReport('SubscrType')?> <br> <br> <?php $this->Additional()?> <input type="submit" name="Submit" value="Submit"> </form> <?php
} } $form = new RegForm01('RegForm01', 'reg_form01.php'); ?> This code can also be downloaded at the end of this article. Next: Conclusion >>
More PHP Articles More By Yuri Makassiouk |