SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2004
    Location
    Michigan
    Posts
    96
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Form Generation and Validation

    Hello there!

    I'm trying to find a completed class or ideas on how I should make my own class for generating forms and then validating them. What do you guys use? I'm trying to stay away form PEAR here so QuickForm won't be of much help unless I decide to use a system similar to theirs, which I dislike.

    I am starting to think I would like the interface to be like so, but not sure on the exact specifics or how using classes like this would effect performance:

    PHP Code:
    $form = new Form();

    //Not sure of the best method here
    $form->addField('username', new Textbox());

    //Or here
    $form->addRule('username', new Required());
    $form->addRule('username', new MaxLength(10));
    //other rules

    if($form->valid())
    {
         
    //process
    } else {
        
    $form->display();

    This was just typed and the first time I put my ideas down on screen, but I'm not too sure. I want each rule to generate an error if its not met and that displayed on the form automatically. The form class should also know if its the first time visiting the page (so no errors could be generated) or if its been submitted before (which should generate errors).

    Any ideas/suggestions?

  2. #2
    SitePoint Enthusiast
    Join Date
    Apr 2004
    Location
    Michigan
    Posts
    96
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In fact I was also thinking of some kind of XML parsing in order to peice togeather the form. I would love this much more then any kind of system as I have described above. However, I am using and will need to use PHP4 with this. Any ideas perhaps? I'm going to start searching now but I would like the opinion of the people here first.

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2005
    Location
    Sydney
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I am working on an XML form set up. Essentially it doesn't take full advantage of XML yet, but hopefully one day it will. At the moment I describe my form in XML and use XSL to transform it. The validation, etc are all done in PHP. Using PHPTAL I pass the errors and values back to the XML form before passing it on to the XSL.

    It works very well, but I would prefer to use relaxng and just be able to validate on that.

    Yes XML can work very well, it also allows you to build a web interface to build forms online very easily. One XSL file should be needed to cover any form and you can also use it to build different kinds of forms, from Web Forms 1 or 2 to XForms.

  4. #4
    SitePoint Evangelist ClickHeRe's Avatar
    Join Date
    Mar 2005
    Location
    Ottawa, Canada
    Posts
    580
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I can give you a general idea of my solution: FormHandler and InputValidation

    FormHandler:

    The form is an XHTML file loaded with DOM so I can manage dynamically the contents of the items by their name (populate a select, change a value of input, hide/show certain fields, etc...). To that, I can input an optionnal "error paramater array" containing the names of the fields in error (I get this from my validation class) so these will be "marked" using a class attribute so they can be colored different to indicate they are in error.

    InputValidation:

    Rules are stored in an XML file which are loaded in DOM again and you input the validation array of values to be tested (so I can use it in $_GET params validation too, or even on a custum array of values too). For forms, I have added a special rule which is always placed first in order and checks if the form was submitted or not. If not, it simply invalidates the form and stops processing further the rules (don't need to parse all the rules if the form isin't sent).

    In the XML rule file, you can have conditionals (for example, test a set of sub-rules only if one rule is met) as well as regular rules. Each rule is based on a basic rule interface so thet the system can load them and use everyone in the same way.

    Both classes aren't done yet, still in adding a couple features and testing them.

    The basic goal for me when building these was that I didn't want to be attached to a particular method of form layout (cf. PEAR_QuickForm) and wanted the validation to be useful for other kinds of validation processes, like URL parameters, custom data validation, etc... You can also view your form separately to arrange it how you wish without fussing around with "components" in the code.

  5. #5
    SitePoint Addict mx2k's Avatar
    Join Date
    Jan 2005
    Posts
    256
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    but what is the overhead so far in using xml with the php4 enviroment with what you currently have?

  6. #6
    Scary's On The Wall
    Join Date
    Apr 2003
    Location
    PA
    Posts
    518
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's mine. It's not a *perfect* set of classes, but it gets the job done well:

    PHP Code:
    <?php

    /*

        classForm.php
        
        Form handler
        
                                    */
                                    
    // This is to make sure we are being called by a valid page
    if ( !defined('IN_SCRIPT') )
    {
        die(
    "Hacking attempt");
    }

        class 
    Form {

            
    // Variables used in class
            
    var $title;
            var 
    $header;
            var 
    $footer;
            var 
    $method;
            var 
    $action;
            var 
    $sections;
            var 
    $content;
            var 
    $requiredFields;
            var 
    $upload;
            var 
    $keepValues;
            var 
    $styleClass 'form';

                function 
    Form($formName$method 'POST'$action '')
                {
                
    // Constructor

                    // Set objects
                    
    $this->title $formName;
                    
    $this->method $method;

                        if (
    $action == '') {
                            
    $this->action $_SERVER['PHP_SELF'];
                        } else {
                            
    $this->action $action;
                        }
                        
                    
    // Create general section
                    
    $this->addSection(new Section);
                                                    
                }

                function 
    setHeader($content) {
                    
    $this->header .= $content;
                }

                function 
    setFooter($content) {
                    
    $this->footer $content $this->footer;
                }

                function 
    createHeader()
                {
                    
    // Create the form header
                    
    $content .= $this->header;
                    
                    if (
    $this->hasErrors()) {
                        
                        
    $content .= message('There were some errors with the data you entered. Please review and re-submit.') . '<br>';
                        
                    }

                    
    $content .= '
                        <form action="' 
    $this->action '"' . ($this->upload()?' enctype="multipart/form-data"':'') . ' method="' $this->method '">
                        <table class="' 
    $this->styleClass '">
                            <tr>
                                <td colspan="2" class="formHeader">
                                    ' 
    $this->title '
                                </td>
                            </tr>
                    '
    ;

                        if (
    $this->requiredFields === true)
                        {
                            
    $content .= '
                                <tr>
                                    <td colspan="2" class="formComment">
                                        Required fields are marked with a <font class="required">*</font>
                                    </td>
                                </tr>
                            '
    ;
                        }

                    return 
    $content;
                }



                function 
    createFooter()
                {
                    
    // Create the form footer
                    
    $content .= '
                            <tr>
                                <td colspan="2" class="formSubmit">
                                    <input type="submit" name="submit" value="Submit">
                                </td>
                            </tr>
                        </table>
                    </form>
                    '
    ;

                    
    $content .= $this->footer;

                    return 
    $content;
                }

                function 
    addSection(&$section) {
                    
                    
    // Add a field grouping section
                    
    $this->sections[] = &$section;
                    
                }

                function 
    addField(&$field)
                {
                    
    // Add field to the first (invisible) section
                    
    $this->sections[0]->addField($field);
                }
                
                function 
    keepValues() {
                    
                    
    // Keep (posted) field values even if there are no errors
                    
    $this->keepValues true;
                    
                }
                
                function 
    upload() {
                    
                    if (
    $this->upload === true) {
                        
                        return 
    true;
                        
                    } else {
                        
                        return 
    false;
                        
                    }
                    
                }

                function 
    createContent() {
                    
                    foreach (
    $this->sections as $section) {
                        
                        if (!empty(
    $section->title)) {
                            
                            
    // Display title                        
                            
    $content .= '
                            <tr>
                                <td class="sectionHeader" colspan="2">
                                    ' 
    $section->title;    
                        
                            if (!empty(
    $section->description)) {
                                
                                
    // Display description
                                
    $content .= '<br>
                                        <font class="tiny">' 
    $section->description '</font>';
                                
                            }
                            
                            
    $content .= '
                                </td>
                            </tr>
                            '
    ;
                            
                        }
                        
                        if (
    count($section->fields) > 0) {
                            
                            
    // Display fields
                            
    foreach ($section->fields as $field) {
            
                                
    // Creates a row using inputs
                                
                                
    $error false;
                                
                                if (
    count($field->errors) > 0) {
                                    
                                    
    $error true;
                                    
                                    
                                    
    $content .= '
                                    <tr>
                                        <td class="fieldNameError" colspan="2">
                                            <font class="formComment">
                                            <img src="images/downarrow.gif" style="float: left;">'
    ;
                                            
                                    foreach (
    $field->errors as $error) {
                                        
                                        
    $content .= '<b>Error:</b> ' $error->display() . '<br>';
                                        
                                    }
                                            
                                    
    $content .= '
                                            </font>
                                        </td>
                                    </tr>'
    ;
                                    
                                }
                                
                                switch (
    $field->type) {
                                    
                                    case 
    'textarea':
                                        
                                        
    /*    <tr>
                                                <td class="fieldName" colspan="2">
                                                    Field Name: *<br>
                                                    <font class="formComment">
                                                        Description of the field
                                                    </font>
                                                    <textarea cols="20" rows="6" name="name">
                                                    value
                                                    </textarea>
                                                </td>
                                            </tr>
                                        */
                                        
                                        
    $content .= '
                                            <tr>
                                                <td class="' 
    . ($error?'fieldNameError':'fieldName') . '" colspan="2">
                                                    <font class="fieldName">' 
    $field->dispName ': ';
                                                    
                                        if (
    $field->required === true)
                                        {
                                            
    $content .= '<font class="required">*</font>';
                                            
    $this->requiredFields true;
                                        }
                                        
                                        
    $content .= '
                                                    </font><br>
                                                    <font class="formComment">
                                                    ' 
    $field->description '
                                                    </font><br>
                                                    <textarea cols="45" rows="6" name="' 
    $field->varName '">';
                                                    
                                                                                        
    // Display a value if there are errors
                                        
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true) {
                                            
    $content .= postdata_to_form($_POST[$field->varName]);
                                        } else  if (!empty(
    $field->value)) {
                                               
    // Or if a default value is provided
                                               
    $content .= $field->value;
                                           }
                                        
                                        
    $content .= '</textarea>
                                                </td>
                                            </tr>
                                        '
    ;
                                        
                                        break;
                                    
                                    default:

                                        
    /*    <tr>
                                                <td class="fieldName">
                                                    <font class="fieldName">
                                                        Field Name: *
                                                    </font><br>
                                                    <font class="formComment">
                                                        Description of the field
                                                    </font>
                                                </td>
                                                <td class="fieldInput">
                                                    <input type="type" name="name" value="value">
                                                </td>
                                            </tr>
                                        */
            
                                        
    $content .= '
                                            <tr>
                                                <td class="' 
    . ($error?'fieldNameError':'fieldName') . '">
                                                    <font class="fieldName">' 
    $field->dispName ': ';
                    
                                            if (
    $field->required === true)
                                            {
                                                
    $content .= '<font class="required">*</font>';
                                                
    $this->requiredFields true;
                                            }
                    
                                        
    $content .= '</font><br>';
                                            
    // Display description only if it is supplied
                                            
    if (!empty($field->description))
                                            {
                                                
    $content .= '
                                                    <font class="formComment">' 
    $field->description '</font>
                                                '
    ;
                                            }
                    
                                         
    $content .= '
                                                </td>
                                                <td class="' 
    . ($error?'fieldInputError':'fieldInput') . '">';
                                        
                                        switch (
    $field->type) {
                                            
                                            case 
    'date':
                                                
                                                
    // Month
                                                
    $content .= '<select name="' $field->monthVar '">';
                                                
                                                
    $months = array('January''February''March''April''May''June''July''August''September''October''November''December');
                                                
                                                
    $content .= '<option value="0">--Month--</option>';
                                                
    $content .= "\n";
                                                
                                                foreach (
    $months as $key => $month) {
                                                    
                                                    
    $i $key+1;
                                                
                                                    
    $content .= '<option value="' $i '"';
                                                    
                                                    
    // Selected?
                                                    
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->monthVar] == $i) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    } else if( 
    $field->value && (date('n'$field->value) == $i) && !(($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->monthVar] != $i)) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    }
                                                    
                                                    
    $content .= '>' $month '</option>';
                                                    
    $content .= "\n";
                                                    
                                                }
                                                
                                                
    $content .= '</select><br>';
                                                
                                                
    // Day
                                                
    $content .= '<select name="' $field->dayVar '">';

                                                
    $content .= '<option value="0">--Day--</option>';
                                                
    $content .= "\n";
                                                
                                                for (
    $i 1$i <= 31$i++) {
                                                
                                                    
    $content .= '<option value="' $i '"';
                                                    
                                                    
    // Selected?
                                                    
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->dayVar] == $i) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    } else if(( 
    $field->value && (date('j'$field->value) == $i)) && !(($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->dayVar] != $i)) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    }
                                                    
                                                    
    $content .= '>' $i '</option>';
                                                    
    $content .= "\n";
                                                    
                                                }
                                                
                                                
    $content .= '</select><br>';
                                                
                                                
    // Year
                                                
    $content .= '<select name="' $field->yearVar '">';

                                                
    $content .= '<option value="0">--Year--</option>';
                                                
    $content .= "\n";
                                                
                                                
    $start date('Y') - 5;
                                                
                                                for (
    $i $start$i >= 1900$i--) {
                                                
                                                    
    $content .= '<option value="' $i '"';
                                                    
                                                    
    // Selected?
                                                    
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->yearVar] == $i) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    } else if( 
    $field->value && (date('Y'$field->value) == $i) && !(($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->yearVar] != $i)) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    }
                                                    
                                                    
    $content .= '>' $i '</option>';
                                                    
    $content .= "\n";
                                                    
                                                }
                                                
                                                
    $content .= '</select>';
                                                
                                                break;
                                            
                                            case 
    'timezone':
                                                
                                                
    $content .= '<select name="' $field->varName '">';
                                                
                                                
    // -12 to +13
                                                
    for ($i = -12$i <= 13$i++) {
                                                
                                                    
    $content .= '<option value="' $i '"';
                                                    
                                                    
    // Selected?
                                                    
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->varName] == $i) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    } else if(
    $field->value == $i && !(($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->varName] != $i)) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    }
                                                    
                                                    
    $content .= '>GMT';
                                                    
                                                    if (
    $i != 0) {
                                                        
                                                        
    $content .= ' ' . (($i 0)?'+':'-') . ' ' abs($i) . ' ';
                                                        
                                                        if (
    abs($i) == 1) {
                                                            
                                                            
    $content .= 'Hour';
                                                            
                                                        } else {
                                                            
                                                            
    $content .= 'Hours';
                                                            
                                                        }
                                                        
                                                    }
                                                    
                                                    
    $content .= '</option>';
                                                    
                                                }
                                                
                                                
    $content .= '</select>';
                                                
                                                break;
                                                
                                            case 
    'option':
                                                
                                                
    $content .= '<select name="' $field->varName '">';
                                                
                                                foreach (
    $field->options as $value => $display) {
                                                    
                                                    
    $content .= '<option value="' $value '"';
                                                    
                                                    
    // Selected?
                                                    
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->varName] == $value) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    } else if(
    $field->value == $value && !(($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->varName] != $value)) {
                                                        
                                                        
    $content .= ' selected';
                                                        
                                                    }
                                                    
                                                    
    $content .= '>' $display '</option>';
                                                    
                                                }
                                                
                                                
    $content .= '</select>';
                                                
                                                break;
                                                
                                            case 
    'checkbox':
                                                
                                                
    $content .= '<input ' . ($error?'class="error" ':'') . 'type="' $field->type '" name="' $field->varName '" value="1"';
                            
                                                    
    // Display a value if there are errors
                                                    
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->varName] == 1) {
                                                        
    $content .= ' checked';
                                                    } else  if (
    $field->value == 1) {
                                                           
    // Or if a default value is provided
                                                           
    $content .= ' checked';
                                                       }
                                                       
                                                   
    $content .= '"> Yes';
                                                   
                                                   break;
                                            
                                            case 
    'yesno':
                                                
                                                
    // 0->no 1->yes
                                                
                                                // Yes or no radio buttons
                                                
                                                //Yes
                                                
    $content .= '<input ' . ($error?'class="error" ':'') . 'type="radio" name="' $field->varName '" value="1"';
                                                
                                                
    // Determine if checked
                                                
                                                
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->varName] == "1") {
                                                    
                                                    
    $content .= ' checked';
                                                    
                                                } else if(
    $field->value == "1" && !(($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->varName] == "0")) {
                                                    
                                                    
    $content .= ' checked';
                                                    
                                                }
                                                
                                                
    $content .= '> Yes &nbsp;&nbsp; ';
                                                
                                                
    // No
                                                
    $content .= '<input ' . ($error?'class="error" ':'') . 'type="radio" name="' $field->varName '" value="0"';
                                                
                                                
    // Determine if checked
                                                
                                                
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->varName] == "0") {
                                                    
                                                    
    $content .= ' checked';
                                                    
                                                } else if(
    $field->value == "0" && !(($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true && $_POST[$field->varName] == "1")) {
                                                    
                                                    
    $content .= ' checked';
                                                    
                                                }
                                                
                                                
    $content .= '> No';
                                                
                                                break;
                                                
                                            case 
    'smackurl':
                                                
                                                if (
    $field->type == 'file') {
                                                    
                                                    
    $this->upload true;
                                                    
                                                }
                                                
                                                
    $content .= 'http://<input ' . ($error?'class="error" ':'') . 'type="' $field->type '" name="' $field->varName '"';
                            
                                                    
    // Display a value if there are errors
                                                    
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true) {
                                                        
    $content .= ' value="' postdata_to_form($_POST[$field->varName]);
                                                    } else  if (!empty(
    $field->value)) {
                                                           
    // Or if a default value is provided
                                                           
    $content .= ' value="' $field->value;
                                                       }
                                                       
                                                   
    $content .= '" size="12">.smackjeeves.com';
                                                    
                                                break;
                                            
                                            default:
                                                
                                                if (
    $field->type == 'file') {
                                                    
                                                    
    $this->upload true;
                                                    
                                                }
                                                
                                                
    $content .= '<input ' . ($error?'class="error" ':'') . 'type="' $field->type '" name="' $field->varName '"';
                            
                                                    
    // Display a value if there are errors
                                                    
    if (($this->hasErrors() || $this->keepValues === true) && $field->keepOnError === true) {
                                                        
    $content .= ' value="' postdata_to_form($_POST[$field->varName]);
                                                    } else  if (!empty(
    $field->value)) {
                                                           
    // Or if a default value is provided
                                                           
    $content .= ' value="' $field->value;
                                                       }
                                                       
                                                   
    $content .= '">';
                                                    
                                                break;
                                            
                                        }
                                           
                                           
    $content .= '
                                                </td>
                                            </tr>
                                        '
    ;
                                        
                                        break;
                                        
                                }
                                
                            }
                            
                        }
                        
                    }

                    return 
    $content;
                }
                
                function 
    hasErrors() {
                    
                    foreach (
    $this->sections as $section) {
                        
                        if (
    count($section->fields) > 0) {
                        
                            foreach (
    $section->fields as $field) {
                            
                                if (
    count($field->errors) > 0) {
                                    
                                    return 
    true;
                                    
                                }
                                
                            }
                            
                        }
                        
                    }
                    
                    return 
    false;
                    
                }

                function 
    display()
                {
                
    // Returns the HTML form

                    // Create content
                    
    $formContent $this->createContent();

                    
    // Construct the form
                    
    $content $this->createHeader() . $formContent $this->createFooter();

                    return 
    $content;
                }
        }

        class 
    MiniForm extends Form {

            var 
    $styleClass 'miniForm';
            var 
    $fields;

            function 
    MiniForm($formName$method 'POST'$action '')
            {
            
    // Constructor

                // Set objects
                
    $this->title $formName;
                
    $this->method $method;

                    if (
    $action == '') {
                        
    $this->action $_SERVER['PHP_SELF'];
                    } else {
                        
    $this->action $action;
                    }

                
    // Center the form
                
    $this->setHeader('<center>');
                
    $this->setFooter('</center>');

            }
            
            function 
    addField(&$field)
            {
                
    // Add another field to the field array
                
    $this->fields[] = &$field;
            }
            
            function 
    hasErrors() {
                    
                foreach (
    $this->fields as $field) {
                
                    if (
    count($field->errors) > 0) {
                        
                        return 
    true;
                        
                    }
                    
                }
                
                return 
    false;
                    
            }

            function 
    createContent() {

                foreach (
    $this->fields as $field) {

                    
    // Creates a row using inputs
                    /*    <tr>
                            <td class="miniFieldInput">
                                fieldName<br>
                                <input type="type" name="name" value="value">
                            </td>
                        </tr>
                    */

                        
    $content .= '
                            <tr>
                                <td class="miniFieldInput">
                                    ' 
    $field->dispName '<br>
                                    <input type="' 
    $field->type '" name="' $field->varName '"';

                            
    // Display a value only if it is supplied
                               
    if (!empty($field->value))
                            {
                                   
    $content .= ' value="' $field->value;
                               }

                           
    $content .= '">
                                </td>
                            </tr>
                        '
    ;
                }

                return 
    $content;
            }

        }
        
        class 
    Section {
            
            var 
    $title;
            var 
    $description;
            var 
    $fields;
            
            function 
    Section($title=''$description='') {
                
                
    $this->title $title;
                
    $this->description $description;
                
            }
            
            function 
    addField(&$field) {
                
                
    $this->fields[] = &$field;
                
            }
            
        }
        
        class 
    Field {
            
            var 
    $varName;
            var 
    $dispName;
            var 
    $type;
            var 
    $required;
            var 
    $keepOnError;
            var 
    $description;
            var 
    $value;
            var 
    $errors;
            
            function 
    Field($varName$dispName$type='text'$required=false$keepOnError=true$description ''$value '') {
                
                
    $this->varName $varName;
                
    $this->dispName $dispName;
                
    $this->type $type;
                
    $this->required $required;
                
    $this->keepOnError $keepOnError;
                
    $this->description $description;
                
    $this->value $value;
                
            }
            
            function 
    addError($error) {
                
                
    $this->errors[] = $error;
                
            }
            
        }
        
        class 
    DateField extends Field {
            
            var 
    $monthVar;
            var 
    $dayVar;
            var 
    $yearVar;
            
            function 
    DateField($monthVar$dayVar$yearVar$dispName$required=false$keepOnError=true$description ''$value '') {
                
                
    $this->varName 'a_date';
                
    $this->monthVar $monthVar;
                
    $this->dayVar $dayVar;
                
    $this->yearVar $yearVar;
                
    $this->dispName $dispName;
                
    $this->type 'date';
                
    $this->required $required;
                
    $this->keepOnError $keepOnError;
                
    $this->description $description;
                
    $this->value $value;
                
            }
            
        }
        
        class 
    OptionField extends Field {
            
            var 
    $options;
            
            function 
    OptionField($varName$dispName$required=false$keepOnError=true$description ''$value '') {
                
                
    $this->varName $varName;
                
    $this->dispName $dispName;
                
    $this->type 'option';
                
    $this->required $required;
                
    $this->keepOnError $keepOnError;
                
    $this->description $description;
                
    $this->value $value;
                
            }
            
            function 
    addOption($value$display) {
                
                
    $this->options[$value] = $display;
                
            }
            
        }


    ?>
    And here's an example implementation of it:

    Viewable @ http://www.smackjeeves.com/register.php

    PHP Code:
    <?php
    /**

        register.php
        
        Registration page
        
                                    **/
                                    
    define("IN_SCRIPT"1);
    $root_path './';

    include(
    $root_path 'common.php');
    require_once(
    'includes/classForm.php');

    //
    // Form
    //

    $regForm = &new Form('Registration');

    // Registration Information
    $regFields = &new Section("Registration Information");
    $regForm->addSection($regFields);

    $fields['reg']['user'] = &new Field('user''User Name''text'truetrue'Choose a name to log in with.');
    $fields['reg']['pass1'] = &new Field('pass1''Password''password'truefalse'4-30 characters');
    $fields['reg']['pass2'] = &new Field('pass2''Confirm Password''password'truefalse'Re-type password');
    $fields['reg']['email'] = &new Field('email''E-Mail''text'truetrue'Valid E-Mail required for account confirmation');

    foreach (
    $fields['reg'] as $key => $val) {
        
        
    $regFields->addField($fields['reg'][$key]);

    }

    // Profile Information
    $profileFields = &new Section("Profile Information""Notice: All of this information is viewable by other users and also optional");
    $regForm->addSection($profileFields);

    $fields['profile']['real_name'] = &new Field('real_name''Real Name''text'falsetrue'Your real name (viewable by others)');
    $fields['profile']['gender'] = &new OptionField('gender''Gender'falsetrue'Male or Female');
    $fields['profile']['gender']->addOption(GENDER_NONE'None');
    $fields['profile']['gender']->addOption(GENDER_MALE'Male');
    $fields['profile']['gender']->addOption(GENDER_FEMALE'Female');
    $fields['profile']['birth_date'] = &new DateField('birth_month''birth_day''birth_year''Birth Date'falsetrue'The day of your birth');
    $fields['profile']['description'] = &new Field('description''Description''textarea'falsetrue'A short description of yourself, your likes, hobbies, occupation, etc.');
    $fields['profile']['icq'] = &new Field('icq''ICQ Number''text'falsetrue'<a href="http://www.icq.com/" target="_messangers">ICQ Messanger</a>');
    $fields['profile']['aim'] = &new Field('aim''AIM Username''text'falsetrue'<a href="http://www.aim.com/" target="_messangers">AOL Instant Messanger</a>');
    $fields['profile']['msn'] = &new Field('msn''MSN Messanger''text'falsetrue'<a href="http://messenger.msn.com/" target="_messangers">MSN Messanger</a>');
    $fields['profile']['yahoo'] = &new Field('yahoo''Yahoo Messanger''text'falsetrue'<a href="http://messenger.yahoo.com/" target="_messangers">Yahoo Messanger</a>');
    $fields['profile']['website'] = &new Field('website''Web Site''text'falsetrue'URL of your Web Site''http://');

    foreach (
    $fields['profile'] as $key => $val) {
        
        
    $profileFields->addField($fields['profile'][$key]);

    }

    // Preferences
    $profileFields = &new Section("Preferences");
    $regForm->addSection($profileFields);

    $fields['prefs']['email_public'] = &new Field('email_public''Publicize E-Mail''yesno'falsetrue'Show your E-Mail address to others? (Bot-Protected)'"0");
    $fields['prefs']['hide_status'] = &new Field('hide_status''Hide Online Status''yesno'falsetrue'Prevent others from seeing when you\'re online'"0");
    $fields['prefs']['email_notify'] = &new Field('email_notify''E-Mail Notification''yesno'falsetrue'Send an E-Mail to your address when you recieve a private message?'"0");
    $fields['prefs']['popup_notify'] = &new Field('popup_notify''Pop-Up Notification''yesno'falsetrue'Alert with a Pop-Up on new Private Messages?'"1");
    $fields['prefs']['date_format'] = &new Field('date_format''Date Format''text'falsetrue'The syntax used is identical to the PHP <a href="http://www.php.net/date" target="_php">date()</a> function.'"d M Y h:i a");
    $fields['prefs']['timezone'] = &new Field('timezone''Time Zone''timezone'falsetrue'<a href="http://www.travel.com.hk/region/timezone.htm" target="_timezone">Global Time Zone Map</a>'"0");

    foreach (
    $fields['prefs'] as $key => $val) {
        
        
    $profileFields->addField($fields['prefs'][$key]);

    }


    //
    // Post Processing
    //

    if (isset($_POST['submit'])) {
        
        
    // Trim 'user' and 'pass' for safety
        
    $_POST['user'] = trim($_POST['user']);
        
    $_POST['pass1'] = trim($_POST['pass1']);
        
    $_POST['pass2'] = trim($_POST['pass2']);
        
        
    //
        // Check For Errors
        //
        
        // User Name
        
    if ( $errors not_validpostdata_to_original($_POST['user']), 'username') ) {
            
            foreach (
    $errors as $error) {
            
                
    $fields['reg']['user']->addError($error);
                
            }
            
        }
        
        
    // Check to see if User Name is available
        
    $user postdata_to_query($_POST['user']);
        
        
    $sql "SELECT COUNT(*) as count FROM users WHERE name='$user'";
        
        if ( !(
    $result $db->sql_query($sql)) ) {
            
            
    message_die(GENERAL_ERROR'Could not query users table'''__LINE____FILE__$sql);
            
        }
        
        
    $countdata $db->sql_fetchrow($result);

        if (
    $countdata['count'] > 0) {
            
            
    $fields['reg']['user']->addError(new Error('Sorry, this name is already taken.'));
            
        }
        
        
    // Password
        
    if ( $errors not_validpostdata_to_original($_POST['pass1']), 'password') ) {
            
            foreach (
    $errors as $error) {
            
                
    $fields['reg']['pass1']->addError($error);
                
            }
            
        }
        
        if (
    postdata_to_original($_POST['pass1']) != postdata_to_original($_POST['pass2'])) {
            
            
    // Confirm Password match Original Password
            
    $fields['reg']['pass2']->addError(new Error('Confirmation Password does not match Original.'));
            
        }
        
        
    // E-Mail
        
    if ( $errors not_validpostdata_to_original($_POST['email']), 'email') ) {
            
            foreach (
    $errors as $error) {
            
                
    $fields['reg']['email']->addError($error);
                
            }
            
        }
        
        
    // All profile information error checking right here
        
    foreach ($fields['profile'] as $key => $val) {
            
            switch (
    $fields['profile'][$key]->varName) {
                
                case 
    'description':
                    
                    if ( 
    $errors not_validpostdata_to_original($_POST$fields['profile'][$key]->varName ]), 'description') ) {
                        
                        foreach (
    $errors as $error) {
                        
                            
    $fields['profile'][$key]->addError($error);
                            
                        }
                        
                    }
                    
                    break;
                    
                case 
    'a_date':
                    
                    
    // No special checking
                    
                    
    break;
                
                default:
            
                    if ( 
    $errors not_validpostdata_to_original($_POST$fields['profile'][$key]->varName ])) ) {
                        
                        foreach (
    $errors as $error) {
                        
                            
    $fields['profile'][$key]->addError($error);
                            
                        }
                        
                    }
                    
                    break;
                    
            }
            
        }
        
        
    // User Preferences error checking
        // (nothing, revert to default preferences on loading if format is invalid)
        
        //
        // Actual User Creation
        //
        
    if ( !$regForm->hasErrors() ) {

            
    // (Database Crap)

        
    }

    }

    $page_content .= $regForm->display();

    //
    // Page Display
    //

    include($root_path 'includes/page_header.php');

    echo 
    $page_content;

    include(
    $root_path 'includes/page_footer.php');

    ?>
    For better viewing, copy/paste the code into an actual PHP editor, because SitePoint wraps the code and makes it look kinda messy.

    EDIT: Note that not_valid returns an array of errors if the specified data is not valid. Here's my not_valid function:

    PHP Code:
    function not_valid($var$type='') {
        
        
    $errors = array();
        
        
    // Universal Vars
        
    $accepted_imagetypes = array('jpg''gif''png');
        
        switch (
    $type) {
            
            case 
    'username':
                
                if ( !
    allowed_chars($var) ) {
                    
    $errors[] = &new Error('Can only contain normal (keyboard) characters.');
                }
        
                if ( (
    strlen($var) < 4) || (strlen($var) > 30) ) {
                    
    $errors[] = &new Error('Must be between 4 and 30 characters long.');
                }            
                
                break;
                
            case 
    'password':
        
                if ( !
    allowed_chars($var) ) {
                    
    $errors[] = &new Error('Can only contain normal (keyboard) characters.');
                }
                
                if ( (
    strlen($var) < 4) || (strlen($var) > 30) ) {
                    
    $errors[] = &new Error('Must be between 4 and 30 characters long.');
                }
                
                break;
                
            case 
    'email':
                
                if ( 
    strlen($var) > 42 ) {
                    
    $errors[] = &new Error('Must be less than 42 characters long.');
                }
        
                if ( !
    ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+' '@' '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.' '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$'$var) ) {
                    
    $errors[] = &new Error('Invalid E-Mail address.');
                }
                
                break;
                
            case 
    'description':
                
                if ( 
    strlen($var)  > 1200 ) {
                    
    $errors[] = &new Error('Must be less than 1200 characters long.');
                }
                
                break;
                
            case 
    'upload_avatar':
                
                
    $info getimageinfo($var);
        
                if (
    $info['width'] > USER_AVATAR_MAX_WIDTH || $info['height'] > USER_AVATAR_MAX_HEIGHT) {
                    
                    
    $errors[] = &new Error('Image must be ' USER_AVATAR_MAX_WIDTH 'x' USER_AVATAR_MAX_HEIGHT ' pixels large or less.');
                    
                }
                
                if (
    $_FILES['upload_avatar']['size'] > USER_AVATAR_MAX_SIZE) {
                    
                    
    $errors[] = &new Error('File size cannot exceed ' USER_AVATAR_MAX_SIZE ' bytes.');
                    
                }
                
                if (!
    in_array($info['mime'], $accepted_imagetypes)) {
                    
                    
    $types implode(', '$accepted_imagetypes);
                    
    $errors[] = &new Error('Image must be one of the following file types: ' $types);
                    
                }
                
                break;
                
            case 
    'remote_avatar':
                
                if ( !(
    $info getimageinfo($var)) ) {
                
                    
    $errors[] = &new Error('Invalid file URL');
                    
                }
        
                if (
    $info['width'] > USER_AVATAR_MAX_WIDTH || $info['height'] > USER_AVATAR_MAX_HEIGHT) {
                    
                    
    $errors[] = &new Error('Image must be ' USER_AVATAR_MAX_WIDTH 'x' USER_AVATAR_MAX_HEIGHT ' pixels large or less.');
                    
                }
                
                if (!
    in_array($info['mime'], $accepted_imagetypes)) {
                    
                    
    $types implode(', '$accepted_imagetypes);
                    
    $errors[] = &new Error('Image must be one of the following file types: ' $types);
                    
                }
                
                break;
                
            case 
    'upload_banner':
                
                
    $info getimageinfo($var);
        
                if (
    $info['width'] > SITE_BANNER_MAX_WIDTH || $info['height'] > SITE_BANNER_MAX_HEIGHT) {
                    
                    
    $errors[] = &new Error('Image must be ' SITE_BANNER_MAX_WIDTH 'x' SITE_BANNER_MAX_HEIGHT ' pixels large or less.');
                    
                }
                
                if (
    $_FILES['upload_banner']['size'] > SITE_BANNER_MAX_SIZE) {
                    
                    
    $errors[] = &new Error('File size cannot exceed ' SITE_BANNER_MAX_SIZE ' bytes.');
                    
                }
                
                if (!
    in_array($info['mime'], $accepted_imagetypes)) {
                    
                    
    $types implode(', '$accepted_imagetypes);
                    
    $errors[] = &new Error('Image must be one of the following file types: ' $types);
                    
                }
                
                break;
                
            case 
    'remote_banner':
                
                if ( !(
    $info getimageinfo($var)) ) {
                
                    
    $errors[] = &new Error('Invalid file URL');
                    
                }
        
                if (
    $info['width'] > SITE_BANNER_MAX_WIDTH || $info['height'] > SITE_BANNER_MAX_HEIGHT) {
                    
                    
    $errors[] = &new Error('Image must be ' SITE_BANNER_MAX_WIDTH 'x' SITE_BANNER_MAX_HEIGHT ' pixels large or less.');
                    
                }
                
                if (!
    in_array($info['mime'], $accepted_imagetypes)) {
                    
                    
    $types implode(', '$accepted_imagetypes);
                    
    $errors[] = &new Error('Image must be one of the following file types: ' $types);
                    
                }
                
                break;
                
            case 
    'comic_name':
                
                if ( !
    allowed_chars($var) ) {
                    
    $errors[] = &new Error('Can only contain normal (keyboard) characters.');
                }
        
                if ( (
    strlen($var) < 4) || (strlen($var) > 30) ) {
                    
    $errors[] = &new Error('Must be between 4 and 30 characters long.');
                }
                
                break;
                
            case 
    'comic_url':
                
                
    $letnum 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';
                
                if (!
    allowed_chars($var$letnum)) {
                    
                    
    $errors[] = &new Error('Can only contain letters, numbers and underscores.');
                    
                }
                
                if ( (
    strlen($var) < 4) || (strlen($var) > 30) ) {
                    
    $errors[] = &new Error('Must be between 4 and 30 characters long.');
                }
                
                break;
                
            default:
                
                if ( 
    strlen($var)  > 64 ) {
                    
    $errors[] = &new Error('Must be less than 64 characters long.');
                }
                
                break;
                
        }
        
        if (
    count($errors) > 0) {
        
            return 
    $errors;
            
        } else {
            
            return 
    false;
            
        }



  7. #7
    SitePoint Enthusiast ZainyFX's Avatar
    Join Date
    Apr 2005
    Location
    Sydney Australia
    Posts
    52
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    haleden thats some good work, thanks

  8. #8
    SitePoint Enthusiast
    Join Date
    Jun 2003
    Location
    Ljubljana, Slovenia
    Posts
    83
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I made me a form builder .. mail me if you want the source .. it was written in PHP 4 but i'm to lazy to rewrite it in PHP 5 in full, have a working version though, but since PHP4 was really a foobar for OO I only made a couple of changes for PHP5 compatibility .. not much ..

    I'm handling parent, child, and many many relations but not handling the one - one relation .. so give me a slack there .. it was all written in 14 day ...
    to make a form just edit the config file you get the input form and the output of a record set for that form .. all relations included ..

    I did not make this so called project public since its not even close to what I really want to do with it .. but for quick forms with simple relations its cool ..

    ohh.. I forgot .. since It was written in a super fast must work mode .. you get no comments with the code since there is none .. and please dont even think about giving me a hard time about class paterns .. I know its not how it should be done .. but consider .. the "must work super fastest possible way "

    my mail

    armandoxxx@siol.net

    bye

    Armando


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •