In reality, coding within the previous web form helper class a method that constructs input elements is a pretty straightforward process that you’ll grasp in a snap, trust me. To demonstrate that my claim is true, below I listed the improved version of the helper, this time including the method in question. Take a close look at the following code fragment, please: (Form.php) class Form { private static $instance = NULL;
// get Singleton instance of Form class public static function getInstance() { if (self::$instance === NULL) { self::$instance = new self; } return self::$instance; }
// render <form> opening tag public static function open(array $attributes) { $html = '<form'; if (!empty($attributes)) { foreach ($attributes as $attribute => $value) { if (in_array($attribute, array('action', 'method', 'id', 'class', 'enctype')) and !empty($value)) { // assign default value to 'method' attribute if ($attribute === 'method' and ($value !== 'post' or $value !== 'get')) { $value = 'post'; } $html .= ' ' . $attribute . '="' . $value . '"'; } } } return $html . '>'; }
// render <input> tag public static function input(array $attributes) { $html = '<input'; if (!empty($attributes)) { foreach ($attributes as $attribute => $value) { if (in_array($attribute, array('type', 'id', 'class', 'name', 'value')) and !empty($value)) { $html .= ' ' . $attribute . '="' . $value . '"'; } } } return $html . '>'; }
// render </form> closing tag public static function close() { return '</form>'; } }// End Form class There you have it. Now the helper has a new static method called “input(),” which can be used for creating text boxes and password fields, radio and submit buttons, and other common controls. To be frank, after adding to the “Form” class the method that renders input elements, it’s starting to look a bit more functional. Naturally, there’s plenty of room to extend the class’ capabilities, but for the moment I’m going to keep its driving logic this basic, you can spot more clearly how it fits into the schema of this example framework. Feel free to tweak the source code of all the classes developed so far. Final thoughts Over this fifth episode of the series, I started building an HTML form helper class with the purpose of adding to this sample MVC framework the ability to render some basic form elements. At this point, this helper class is capable only of constructing input controls, including text and password boxes, radio and file buttons, and so forth. This isn’t enough functional for the purposes of this series. In the next tutorial I’m going to put the final touches on this helper class by enabling it to create HTML text areas. Want to see how this will be accomplished? Then don’t miss the upcoming tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|