Old 11-19-2009, 03:46 PM   #1
imagined
Code Remixer
 
imagined's Avatar
Share your Form class

Hey guys! I'm writing a Form class with validation. I like what I'm doing but I think it can be improved. I'm hardly satisfied with what I do.

For example, the date field accepts from a drop-down menu the day, month and year. Now if you enter February 31, 2010 (invalid date) it will ask you to enter a valid date, but I know I can improve this with javascript, if a user selects February, only let him choose up to 28 or 29 days. But I would also like to add a little calendar select day things, just like when you are making a flight or hotel reservation. I guess I can do that with jQuery but I'm waiting for the book to arrive (Nov 28). Is there any solution you recommend?

What do you use as a Form class? Do you use any that you downloaded from the internet?

__________________
"You are playing a very dangerous game"
"Change always is"

CodeRemix
TutorialRemix
iPhonePaperStudio
imagined is offline   Reply With Quote

Sponsored Links (Guests Only) - Register | Need Help?
 

Old 11-19-2009, 08:07 PM   #2
Voetsjoeba
Tu n'es pas un robot!
 
Voetsjoeba's Avatar
Location Belgium, Ghent

Posts 11,537
I don't use a form class, I separate my view from my logic and so should you Take a look at the Smarty template engine.

For validation, I use a validator object with validation methods like validateNotEmpty, validateNumeric, validateMaxLength, etc. Every validation call may add an error internally, and I check for errors using an noErrors() method call. This allows me to perform validation in chunks, so that if eg. I need to do a query for validating a record ID, I can avoid even executing that query if there is already other stuff that didn't validate. Micro-optimization? Sure, but the point is doing the validation in chunks, which I've found to come in very handy many times. Additionally, grouping your errors in an object enables you to just pass it down to the view layer to enable it to display any error messages.

For the date input thing, I would definitely recommend using a Javascript datepicker. There are plenty elegant datepickers out there; it gets a bit harder if you also need time in there though. You don't really need a book on jQuery to add such a timepicker; the one I use simply requires you to include the JS file in your HTML head section, and then add some CSS classes to let the magic happen. Just read the documentation on it and view some examples and you should be well on your way. But, whatever the solution you choose, ensure that people without JS can still use it. Graceful degradation is key.

__________________
Wait, what?
Voetsjoeba is offline   Reply With Quote
Old 11-20-2009, 10:45 AM   #3
imagined
Code Remixer
 
imagined's Avatar
Ohhhhhhh..... I read about Smarty and I think I finally understand what you guys mean by separating logic from design. I mean, I know what it means, but now I know how much you were explaining I should separate it.

You meant just like WordPress right?

You create the custom PHP functions and just pass it to the designer and he can do with them whatever he wants and mix it up with HTML and CSS, rite?

__________________
"You are playing a very dangerous game"
"Change always is"

CodeRemix
TutorialRemix
iPhonePaperStudio
imagined is offline   Reply With Quote
Old 11-20-2009, 12:53 PM   #4
imagined
Code Remixer
 
imagined's Avatar
Quote:
Originally Posted by Voetsjoeba View Post
For validation, I use a validator object with validation methods like validateNotEmpty, validateNumeric, validateMaxLength, etc. Every validation call may add an error internally, and I check for errors using an noErrors() method call. This allows me to perform validation in chunks, so that if eg. I need to do a query for validating a record ID, I can avoid even executing that query if there is already other stuff that didn't validate. Micro-optimization? Sure, but the point is doing the validation in chunks, which I've found to come in very handy many times. Additionally, grouping your errors in an object enables you to just pass it down to the view layer to enable it to display any error messages.
I do have a Validation class. But if I were to use it separately from the HTML form, the error messages would display on top of the page as a bullet list.

I would like to print the error messages in line with the form fields for better usability. That's why I'm creating a function that generates the form and validates it on submission.

Here it is, it's not finished though.
PHP Code:
class Form{

    protected 
$_form;
    protected 
$_urlQuery '';
    protected 
$_required;
    protected 
$_submitted;
    protected 
$_errors;
    protected 
$_missing;

    
/**#@-*/
    /**
     * Constructs a form object for $_POST or $_GET input.
     * 
     * @param string  $formName Optional string containing the name attribute of the form tag
     * @return Form object
     */
    
public function __construct($formName='noname'$required=array()){
        
// Add URL query string
        
if(!empty($_SERVER['QUERY_STRING'])){
            
$_urlQuery='?'.$_SERVER['QUERY_STRING'];
        }

        
// Name the form
        
$formName=trim($formName);
        if(!
is_string($formName)){
            throw new 
Exception('The form name must be a string');
        }
        
$this->_form '<form name="'.$formName.'" action="'.$_SERVER['PHP_SELF'].$_urlQuery.'" method="post">';

        if(!
is_null($required) && !is_array($required)){
            throw new 
Exception('The names of required fields must be an array, even if only one field is required.');
        }
        
$this->_required $required;
        if(
$this->_required){
            
$this->checkRequired();
        }
        
$this->_errors = array();
        
$this->_submitted $_POST;
    }

    
########################################################################
    #                                                                       #
    # PUBLIC METHODS -- GENERATE FORM FIELDS                               #
    #                                                                       #
    ########################################################################
    /*
    
                text field
    
    */
    
public function addTextField($label$name){
        
$_POST[$name] = trim($_POST[$name]);
        
$formFeedback $this->formFeedback($name);
        
$hint $this->addHint($name);
        
$this->_form .= '<p><label for="'.$name.'">'.$label.' '.$hint.'</label><input type="text" name="'.$name.'" value="'.$_POST[$name].'" />'.$formFeedback.'</p>';
    }


    
/*
    
                email field
    
    */
    
public function addEmailField($label$name){
        
$_POST[$name] = trim($_POST[$name]);
//        if(!$this->isEmail($name)){
//            $formFeedback = '<span class="formFeedback">Please enter a valid email</span>';
//        }
        
$this->isEmail($name);
        
$formFeedback $this->formFeedback($name);
        
$hint $this->addHint($name);
        
$this->_form .= '<p><label for="'.$name.'">'.$label.' '.$hint.'</label><input type="text" name="'.$name.'" value="'.$_POST[$name].'" />'.$formFeedback.'</p>';
    }



    
/*

                select field

    */
    
public function addSelectField($label$name$values){
        if(!
is_array($values)){
            throw new 
Exception('The values of the select options must be an array consisting of option values as array keys and option names as array values.');
        }

        foreach(
$values as $key => $value){
            if(
$_POST[$name]==$key){$selected ' selected="selected" ';}
            
$select .= '<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
            
$selected '';
        }
        
$hint $this->addHint($name);
        
$formFeedback $this->formFeedback($name);
        
$this->_form .= '<p><label for="'.$name.'">'.$label.' '.$hint.'</label><select name="'.$name.'"><option value="">-- Select --</option>'.$select.'</select>'.$formFeedback.'</p>';
    }

    
/*

            date field

    */
    
public function addDateField($label$name$yearStart=1920$yearEnd='now')
    {
        
$selectedMonth '';
        
$displayMonth='';
        
$month='';            
        
$selectedDay '';
        
$day='';
        
$selectedYear '';
        
$year='';
        if(!
is_int($yearStart))
        {
            throw new 
Exception('The value for the yearStart parameter must be an integer.');
        }
        if(!
is_int($yearEnd))
        {
            if(
$yearEnd!='now')
            {
                throw new 
Exception('The value for the yearEnd parameter must be an integer or the word(string) "now".');
            }
        }
        if(
$yearEnd=='now')
        {
            
$yearEnd=date('Y');
        }

        
$hint $this->addHint($name);
        
$this->_form .= '<p><label>'.$label.' '.$hint.'</label>';

        
// Generate month fields
        
for($i=1;$i<=12;$i++)
        {
            if(
$_POST[$name.'Month']==$i){$selectedMonth='selected="selected"';}
            if(
$i=='1'){$displayMonth='January';}
            elseif(
$i==2){$displayMonth='February';}
            elseif(
$i==3){$displayMonth='March';}
            elseif(
$i==4){$displayMonth='April';}
            elseif(
$i==5){$displayMonth='May';}
            elseif(
$i==6){$displayMonth='June';}
            elseif(
$i==7){$displayMonth='July';}
            elseif(
$i==8){$displayMonth='August';}
            elseif(
$i==9){$displayMonth='September';}
            elseif(
$i==10){$displayMonth='October';}
            elseif(
$i==11){$displayMonth='November';}
            else{
$displayMonth='December';}
            
$month .= '<option value="'.$i.'" '.$selectedMonth.'>'.$displayMonth.'</option>';
            
$selectedMonth='';
        }
        
$this->_form .= '<select name="'.$name.'Month"><option value="00">month</option>'.$month.'</select>';

        
// Generate day fields
        
for($i=1;$i<=31;$i++)
        {
            if(
$_POST[$name.'Day']==$i){$selectedDay='selected="selected"';}
            
$day .= '<option value="'.$i.'" '.$selectedDay.'>'.$i.'</option>';
            
$selectedDay='';
        }
        
$this->_form .= '<select name="'.$name.'Day"><option value="00">day</option>'.$day.'</select>';

        
// Generate year fields
        
for($i=$yearEnd;$i>=$yearStart;$i--)
        {
            if(
$_POST[$name.'Year']==$i){$selectedYear='selected="selected"';}
            
$year .= '<option value="'.$i.'" '.$selectedYear.'>'.$i.'</option>';
            
$selectedYear='';
        }
        
$this->_form .= '<select name="'.$name.'Year"><option value="00">year</option>'.$year.'</select>';

        
$formFeedback $this->formFeedbackDate($name);
        
$this->_form .= $formFeedback.'</p>';
    }

    
/*

                fieldset
                    -text field
                    -select field
                    -date field
                    -password field

    */
/*    public function addFieldset($legend, $fields, $tablename)
    {
        $fieldset = '<fieldset><legend>'.$legend.'</legend>';
        foreach($fields as $key => $value)
        {
            $type        = $value[0];
            $label        = $value[1];
            $name        = $value[2];
            $values        = $value[3];

            if($type=='text')
            {
                $fieldset .= $this->addTextFieldProtected($label, $name);
            }
            elseif($type=='select')
            {
                 $fieldset .= $this->addSelectFieldProtected($label, $name, $values);
            }
            elseif($type=='date')
            {
                $fieldset .= $this->addDateFieldProtected($label, $name, $value[3], $value[4]);
            }
            elseif($type=='password')
            {
                $fieldset .= $this->addPasswordFieldProtected($label, $name);
            }

        }
        $fieldset .= '</fieldset>';
        $this->_form .=  $fieldset;
    } */

    /*

            submit button

    */
    
public function addSubmitButton($value){
        
$this->_form .= '<p><input type="submit" value="'.$value.'"></p>';
    }

    
/*

            actions

    */
    
public function insertAction($tables$connectingColumn=''){
        if(!
is_array($tables)){
            throw new 
Exception('The tables parameter must be an array, even if only one table will be used.');
        }

        
$columns = array();
        
$queries = array();
        foreach(
$tables as $key => $value){
            
$query_data '';
            
$result mysql_query('SHOW COLUMNS FROM '.$value);
            if(!
$result){
                throw new 
Exception('Query to find column names failed.');
            }
            if(
mysql_num_rows($result) > 0){
                while(
$row mysql_fetch_assoc($result)){
                    echo 
'<pre>';
                    
print_r($row);
                    echo 
'</pre>';
                    echo 
'<pre>';
                    
print_r($this->_submitted);
                    echo 
'</pre>';
                    if(
array_key_exists($row['Field'], $this->_submitted)){
                        if(
$row['Field']=='password'){
                            
$query_data .= $row['Field'].'="'.mysql_real_escape_string(md5($_POST[$row['Field']])).'", ';
                        }else{
                            
$query_data .= $row['Field'].'="'.mysql_real_escape_string($_POST[$row['Field']]).'", ';
                        }
                    }
                    
$columns[$key][] = $row['Field'];
                }
            }
            
$query_data substr($query_data0, -2);
            
$queries[] = 'INSERT INTO '.$tables[$key].' SET '.$query_data;
        }
        
        if(
$_SERVER['REQUEST_METHOD']=='POST'){
            if(
count($this->_errors)==0){
            echo 
'<pre>';
            
print_r($queries);
            echo 
'</pre>';
                
$first true;
                foreach(
$queries as $value){
                    if(
$first){
                        
// make first query
                        
if(!mysql_query($value)){
                            throw new 
Exception('Error trying to execute first query.');
                            echo 
'Query error: '.mysql_error();
                        }else{
                            echo 
'<p>new record inserted</p>';
                        }
                        
$last_inserted_id mysql_insert_id();
                        
$first false;
                    }else{
                        
// make query and use mysql_insert_id to insert into column that connects the tables, in this case it would be userID
                        
$value .= ', '.$connectingColumn.'="'.$last_inserted_id.'"';
                        if(!
mysql_query($value)){
                            throw new 
Exception('Error trying to execute query.');
                        }
                    }
                }
            }
        }

    }

    
########################################################################
    # PUBLIC VALIDATION METHODS
    ########################################################################
    /*

        public validation methods have to be declared before defining the form fields
        i think i need to change that
        
    
        add submission confirmation, redirection or disable fields and buttons
        
    
        check that sessions is enable and send an user-friendly error


    
    */

    /*

            captcha

    */
    
public function captcha()
    {
        if(!isset(
$_SESSION)){throw new Exception('SESSIONS must be enabled for the captcha to work.');}
        if(
$_SERVER['REQUEST_METHOD']=='POST' && empty($this->_submitted['securitycode']))
        {
            
$this->_errors['securitycode'] = '<span class="formFeedback">This field is required</span>';
        }
        elseif(
$_SERVER['REQUEST_METHOD']=='POST' && $this->_submitted['securitycode']!=$this->_submitted['code'])
        {
            
$this->_errors['securitycode'] = '<span class="formFeedback">The code entered did not match. Please try again.</span>';
        }
        if(isset(
$this->_errors['securitycode'])){ $formFeedback $this->_errors['securitycode']; }


        
$this->_form .=        '<fieldset>
                            <legend>Security Code</legend>
                            <p>
                            To ensure the security of our database, we ask that you type your code (displayed below) in the text box.
                            </p>
                            <p>
                            This code is an image that cannot be read by a machine. It prevents automated programs
                            from submitting information. If you have difficulty reading the code displayed, please refresh your browser.</p>
                            <img src="../includes/imgGen.inc.php" alt="Please type this word" style="margin:10px 0 5px 0;">
                            <p>
                            <input name="securitycode" type="text" maxlength="6" />'
.$formFeedback.'
                            </p>
                            <input type="hidden" name="code" value="'
.$_SESSION['crc'].'">
                            </fieldset>'
;
    }

    
/*
    
        prevent duplication
    

    */
    
public function preventDuplication($fieldName$tablename$column)
    {
        if(
$_SERVER['REQUEST_METHOD']=='POST')
        {
            
$query 'SELECT * FROM '.$tablename.' WHERE '.$column.'="'.$this->_submitted[$fieldName].'"';
            if( !(
$result mysql_query($query)) )
            {
                throw new 
Exception('Error trying to execute query to prevent duplication on '.$fieldName.'.'.$query);
            }
            if(
mysql_num_rows($result) >= 1)
            {
                
$this->_errors[$fieldName] = '<span class="formFeedback">'.$this->_submitted[$fieldName].' is already taken, please select another one.</span>';
                return 
false;
            }
        }
    }

    
/*

            email validation

    */
    
public function isEmail($fieldName)
    {
        if(
$_SERVER['REQUEST_METHOD']=='POST')
        {
            
$_POST[$fieldName] = filter_var($_POST[$fieldName], FILTER_SANITIZE_EMAIL);
            if(
filter_var($_POST[$fieldName], FILTER_VALIDATE_EMAIL))
            {
                return 
true;
            }
            else
            {
                
$this->_errors[$fieldName] = 'Please enter a valid email';
                return 
false;
            }
        }
    }

    
/*

            sanitize URL

    */
    
public function sanitizeURL($fieldName)
    {
        if(
$_SERVER['REQUEST_METHOD']=='POST' && !ctype_alnum($this->_submitted[$fieldName]))
        {
            
$this->_errors[$fieldName] = '<span class="formFeedback">This field only accept letters or numbers</span>';
            return 
false;
        }
    }

    
/*
    
            send email
    
    */
    
public function sendEmail($emailAddress$emailSubject$emailMessage$emailNameFrom$emailAddressFrom)
    {
        
$emailAddress filter_var($emailAddressFILTER_SANITIZE_EMAIL);
        if( !(
filter_var($emailAddressFILTER_VALIDATE_EMAIL)) )
        {
            throw new 
Exception('The value for the first parameter (email address) is not a valid email address.');
        }
        if(empty(
$emailSubject))
        {
            throw new 
Exception('The value for the second parameter (email subject) is empty.');
        }
        if(empty(
$emailMessage))
        {
            throw new 
Exception('The value for the third parameter (email message) is empty.');
        }
        
//        $domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);
//        $header = '';
//        $header = 'To: The Receiver <'.$sendto.'>\n';
//        $header .= 'From: The Sender <sender@hi-techtilt>\n';
//        $header .= 'From: The Sender <auto-confirm@'.$domain.'>\n';
//        $header .= 'MIME-Version: 1.0\n';
//        $header = 'Content-type: text/html; charset=iso-8859-1';
        
$header =    "From: ".$emailNameFrom." <".$emailAddressFrom.">\n".
                    
"Content-type: text/html; charset=iso-8859-1\n".
                    
"X-Mailer: PHP";
        
// This is the function to send the email 
        
if(!mail($emailAddress$emailDubject$emailMessage$header))
        {
            throw new 
Exception('Email could not be sent.');
        }
    }

    
/*

            check matches

    */
    
public function checkMatch($fieldName1$fieldName2)
    {
        if(empty(
$this->_submitted[$fieldName1]) && empty($this->_submitted[$fieldName2]))
        {
            
$this->_errors[$fieldName1] = '<span class="formFeedback">This field is required</span>';
            return 
false;
        }
        elseif(
$this->_submitted[$fieldName1] != $this->_submitted[$fieldName2] && !empty($this->_submitted[$fieldName1]) && !empty($this->_submitted[$fieldName2]) )
        {
            
$this->_errors[$fieldName1] = '<span class="formFeedback">Passwords do not match. Please type them again</span>';
            return 
false;
        }
    }

    
/**
     * Checks the number of characters in the submitted value.
     * 
     * The first two arguments are required: the name of the form field or URL variable,
     * and the minimum acceptable length. The optional third argument sets a maximum length.
     * To set a maximum with no minimum, set the second argument to 0.
     * 
     * This is the only test that can be applied to input in addition to another. It should
     * always be used in conjunction with one of the other tests, as it doesn't sanitize the
     * input or remove magic quotes. Since all input is regarded as strings, further tests
     * might be necessary if you want to limit input to a particular type.
     * 
     * If the submitted data falls outside the specified range, an error message is added to
     * the validator's $_errors property.
     * 
     * @param string  $fieldName  Name of submitted value to be checked
     * @param int     $min        Minimum number of characters expected
     * @param int     $max        Optional; sets the maximum number of characters permitted
     */
    
public function checkTextLength($fieldName$min$max null)
    {
        if(
$_SERVER['REQUEST_METHOD']=='POST')
        {
            
// Get the submitted value
            
$text trim($this->_submitted[$fieldName]);
            
// Make sure it's a string
            
if (!is_string($text)) {
                throw new 
Exception("The checkTextLength() method can only be applied to strings; $fieldName is the wrong data type.");
            }
            
// Make sure the second argument is a number
            
if (!is_numeric($min)) {
                throw new 
Exception("The checkTextLength() method expects a number as the second argument (field name: $fieldName)");
            }
            
// If the string is shorter than the minimum, create error message
            
if (strlen($text) < $min) {
                
// Check whether a valid maximum value has been set
                
if (is_numeric($max)) {
                    
$this->_errors[$fieldName] = 'This field must be between '.$min.' and '.$max.' characters.';
                } else {
                    
$this->_errors[$fieldName] = 'This field  must be a minimum of '.$min.' characters.';
                }
            }
            
// If a maximum has been set, and the string is too long, create error message
            
if (is_numeric($max) && strlen($text) > $max) {
                
                if (
$min == 0) {
                    
$this->_errors[$fieldName] = 'This field must be no more than '.$max.' characters.';
                } else {
                    
$this->_errors[$fieldName] = 'This field must be between '.$min.' and '.$max.' characters.';
                }
            }
        }
    }

    
############################################################################
    # PROTECTED METHODS                                                        #
    ############################################################################
    /**
     * Checks the submitted value of all required items to ensure that the field isn't 
     * blank.
     * 
     * If the item is a scalar (single) value, whitespace is stripped from both
     * ends to prevent users from entering a series of spaces. Populates the $_missing
     * property with the names of missing fields or variables. 
     */
    
protected function checkRequired()
    {
        
/*
        
        
            Note to self: modify function to check for nameMonth, nameDay, nameYear just like formFeedbackDate
        
        
        */
        
if($_SERVER['REQUEST_METHOD']=='POST')
        {
            
$OK = array();
            foreach (
$_POST as $name => $value)
            {
                
$value is_array($value) ? $value trim($value);
                if (!empty(
$value))
                {
                    
$OK[] = $name;
                }
            }
            
$this->_missing array_diff($this->_required$OK);
        }
    }
    
    protected function 
formFeedback($fieldName){

/*        echo '<pre>';
        print_r($this->_errors);
        print_r($this->_required);
        echo '</pre>'; */

        // if the field name is in the required array and the form has been submitted and the field is empty
        
if(in_array($fieldName$this->_required) && $_SERVER['REQUEST_METHOD']=='POST' && empty($_POST[$fieldName])){
            
$output =  '<span class="formFeedback">This field is required</span>';

        }
        
// if the array key is in the $this->errors array, then return the error message
        
if(array_key_exists($fieldName$this->_errors) && $_SERVER['REQUEST_METHOD']=='POST'){
            
$output '<span class="formFeedback">'.$this->_errors[$fieldName].'</span>';
        }
        return 
$output;
    }

    protected function 
formFeedbackDate($fieldName){
        if(
            
// if the field name is in the required array and the form has been submitted
            
(
                
in_array($fieldName$this->_required) &&
                
$_SERVER['REQUEST_METHOD']=='POST'
            
)
            &&
            
// if one of the date fields was not filled out
            
(
                ( isset(
$_POST[$fieldName.'Month']) && empty($_POST[$fieldName.'Month']) )
                ||
                ( isset(
$_POST[$fieldName.'Day']) && empty($_POST[$fieldName.'Day']) )
                ||
                ( isset(
$_POST[$fieldName.'Year']) && empty($_POST[$fieldName.'Year']) )
            )
        ){
            return 
'<span class="formFeedback">This field is required</span>';
        }
        elseif(
$_SERVER['REQUEST_METHOD']=='POST' && !checkdate($_POST[$fieldName.'Month'], $_POST[$fieldName.'Day'], $_POST[$fieldName.'Year'])){
            return 
'<span class="formFeedback">Please enter a valid date</span>';
        }
    }

    protected function 
addHint($fieldName)
    {
        if
        (
            (    
in_array($fieldName$this->_required)    )
            or
            (
                
in_array($fieldName.'Month'$this->_required) && in_array($fieldName.'Day'$this->_required) &&
                
in_array($fieldName.'Year'$this->_required)
            )
        )
        {
            return 
'<em class="required">(required)</em>';
        }
    }

    protected function 
addPasswordFieldProtected($label$name)
    {
        
$_POST[$name] = trim($_POST[$name]);
        if(
$_SERVER['REQUEST_METHOD']=='POST'){$formFeedback $this->checkMatch($name$name.'again');}
        
$hint $this->addHint($name);
        if(isset(
$this->_errors[$name])){ $formFeedback $this->_errors[$name]; }
        return    
'<p><label for="'.$name.'">'.$label.' '.$hint.'</label><input type="password" name="'.$name.'" value="'.$_POST[$name].'" />'.$formFeedback.'</p>
                <p><label for="'
.$name.'">'.$label.' again</label><input type="password" name="'.$name.'again" value="'.$_POST[$name.'again'].'" /></p>';
    }

    protected function 
addTextFieldProtected($label$name)
    {
        
$_POST[$name] = trim($_POST[$name]);
        
$formFeedback $this->formFeedback($name);
        
$hint $this->addHint($name);
        if(isset(
$this->_errors[$name])){ $formFeedback $this->_errors[$name]; }
        return 
'<p><label for="'.$name.'">'.$label.' '.$hint.'</label><input type="text" name="'.$name.'" value="'.$_POST[$name].'" />'.$formFeedback.'</p>';
    }

    protected function 
addSelectFieldProtected($label$name$values)
    {
        if(!
is_array($values))
        {
            throw new 
Exception('The values of the select options must be an array consisting of option values as array keys and option names as array values.');
        }

        foreach(
$values as $key => $value)
        {
            if(
$_POST[$name]==$key){$selected ' selected="selected" ';}
            
$select .= '<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
            
$selected '';
        }
        
$hint $this->addHint($name);
        
$formFeedback $this->formFeedback($name);
        return 
'<p><label for="'.$name.'">'.$label.' '.$hint.'</label><select name="'.$name.'"><option value="">-- Select --</option>'.$select.'</select>'.$formFeedback.'</p>';
    }

    protected function 
addDateFieldProtected($label$name$yearStart=1920$yearEnd='now')
    {
        
$selectedMonth '';
        
$displayMonth='';
        
$month='';            
        
$selectedDay '';
        
$day='';
        
$selectedYear '';
        
$year='';
        if(!
is_int($yearStart))
        {
            throw new 
Exception('The value for the yearStart parameter must be an integer.');
        }
        if(!
is_int($yearEnd))
        {
            if(
$yearEnd!='now')
            {
                throw new 
Exception('The value for the yearEnd parameter must be an integer or the word(string) "now".');
            }
        }
        if(
$yearEnd=='now')
        {
            
$yearEnd=date('Y');
        }

        
$hint $this->addHint($name);
        
$fields .= '<p><label>'.$label.' '.$hint.'</label>';

        
// Generate month fields
        
for($i=1;$i<=12;$i++)
        {
            if(
$_POST[$name.'Month']==$i){$selectedMonth='selected="selected"';}
            if(
$i=='1'){$displayMonth='January';}
            elseif(
$i==2){$displayMonth='February';}
            elseif(
$i==3){$displayMonth='March';}
            elseif(
$i==4){$displayMonth='April';}
            elseif(
$i==5){$displayMonth='May';}
            elseif(
$i==6){$displayMonth='June';}
            elseif(
$i==7){$displayMonth='July';}
            elseif(
$i==8){$displayMonth='August';}
            elseif(
$i==9){$displayMonth='September';}
            elseif(
$i==10){$displayMonth='October';}
            elseif(
$i==11){$displayMonth='November';}
            else{
$displayMonth='December';}
            
$month .= '<option value="'.$i.'" '.$selectedMonth.'>'.$displayMonth.'</option>';
            
$selectedMonth='';
        }
        
$fields .= '<select name="'.$name.'Month"><option value="">month</option>'.$month.'</select>';

        
// Generate day fields
        
for($i=1;$i<=31;$i++)
        {
            if(
$_POST[$name.'Day']==$i){$selectedDay='selected="selected"';}
            
$day .= '<option value="'.$i.'" '.$selectedDay.'>'.$i.'</option>';
            
$selectedDay='';
        }
        
$fields .= '<select name="'.$name.'Day"><option value="">day</option>'.$day.'</select>';

        
// Generate year fields
        
for($i=$yearEnd;$i>=$yearStart;$i--)
        {
            if(
$_POST[$name.'Year']==$i){$selectedYear='selected="selected"';}
            
$year .= '<option value="'.$i.'" '.$selectedYear.'>'.$i.'</option>';
            
$selectedYear='';
        }
        
$fields .= '<select name="'.$name.'Year"><option value="">year</option>'.$year.'</select>';

        
$formFeedback $this->formFeedbackDate($name);
        
$fields .= $formFeedback.'</p>';
        return 
$fields;
    }

    
/* --------------------------------------------------------------------
    
                            --- Getter ---

    -------------------------------------------------------------------- */
    
public function getErrors()
    {
        return 
$this->_errors;
    }

    public function 
getMissing()
    {
        return 
$this->_missing;
    }

    public function 
getForm()
    {
        
$this->_form .= '</form>';
        return 
$this->_form;
    }

What I'm trying to figure out now, it's how to build a query from the form results. If you have some suggestion I will really appreciate it.

__________________
"You are playing a very dangerous game"
"Change always is"

CodeRemix
TutorialRemix
iPhonePaperStudio
imagined is offline   Reply With Quote
Old 11-26-2009, 10:30 PM   #5
timberland378
Banned
Cheap Louis Vuitton handbags

You can find latest news of full Cheap Louis Vuitton products; learn latest information of Louis Vuitton handbags cheap sale events and price adjustment. Serving as your most helpful shopping guide and providing the most comprehensive and detailed buying tips. Cheap designer handbags
timberland378 is offline   Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 05:14 PM.

SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple. flash components
Creative web apps. Make your own free flash banners and photo slideshows.
Check out the great, high-quality flash extensions. Buy or sell stock flash, video, audio and fonts for as little as 50 cents at FlashDen.

Flash Transition Effects

Flash Effect Tutorials

Digicrafts Components
Flash effects. Art without coding. Upload, publish, deliver. Secure hosting for your professional or academic video, presentations & more. Screencast.com
Streamsolutions Content Delivery Networks Flipping Book - page flip flash component.
Flash-Gallery.com - Get your flash photo gallery (flash component or swf gallery Learn how to advertise on kirupa.com
 

cdn
content delivery network (cdn)

Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd. Copyright 2010 - kirupa.com Copyright 2010 - kirupa.com