Keith Donegan Keith Donegan - 1 month ago 19
PHP Question

How to build a PHP form Dynamically with OOP?

How would I go about creating a real world form creation class that I can use to display a new form with fields of different types, as how many fields I want, I can use drop downs and I can do all of this by using OOP?

Answer

You definitely can. Consider a Form class which stores information about the form itself: the method, action, enctype attributes. Also throw in stuff like an optional heading and/or description text at the top. Of course you will also need an array of input elements. These could probably be put into their own class (though subclassing them for InputText, InputCheckbox, InputRadio maybe be a bit over the top). Here's a vague skeleton design:

class Form {
    var $attributes,    // array, with keys ['method' => 'post', 'action' => 'mypage.php'...]
        $heading,
        $description,
        $inputs        // array of FormInput elements
    ;

    function render() {
        $output = "<form " . /* insert attributes here */ ">"
              . "<h1>" . $this->heading . "</h1>"
              . "<p>" . $this->description . "</p>"
        ;
        // wrap your inputs in whatever output style you prefer:
        // ordered list, table, etc.
        foreach ($this->inputs as $input) {
            $output .= $input->render();
        }
        $output .= "</form>";
        return $output;
    }
}

The FormInput class would just need to store the basics, such as type, name, value, label. If you wanted to get tricky then you could apply validation rules which would then be converted to Javascript when rendering.

Comments