tags:

views:

70

answers:

5

Ok, I am programming a website and I need to do a lot of html forms everywhere. How can I reduce amount of my time doing that? Any ideas? I guess it should be done with functions.
I don't use neither any frameworks nor OOP yet.
Thank you very much.

+2  A: 

My suggestion is to start using a framework sooner as you'll find a lot of your work is already done for you. CodeIgniter or Zend aren't bad ones. If not I'd write a few classes myself that given a number of parameters can render the html needed. Personally getting a framework is a much more compelling choice in the long run.

Am
+3  A: 

Please google "Zen Coding". I think it is what you want. For example:

If you input div#content>h1+p , the following html will be generated:

<div id="content">
<h1></h1>
<p></p>
</div>

Zen Coding is supported by a lot of editors.

whentp
+3  A: 

Unfortunately, there is no magic FormBuilder::readMyMind() function yet, so you will spend some time on it. Here is some FormBuilders you can use without having to use a framework:

Note that Zend_Form is part of Zend Framework, but can be used standalone. It does have a number of dependencies on other ZF components though.

Gordon
A: 

May be have a look at http://pear.php.net/package/HTML_QuickForm2

The greater the abstraction (the easier it is to use) then the less control your going to have over the final output. So it may depend on how complex your forms are going to be that will determine the tools you can use.

w3d
A: 

I wrote a small class to to create a form based on a DB table, a few years ago.

Here is a method to grab all the fields & field types from a database table:

public function getDatabaseFields($db_name, $tbl, $ignoredFields)
    {
        $db = mysqli_select_db($this->connect, $db_name);
        $sql = "DESCRIBE $tbl";
        $result = mysqli_query($this->connect, $sql);
        if ($result !== false)
        {
            $i = 0;
            while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
            {
                if (!in_array($row[Field], $ignoredFields))
                {
                    $formItems[$i][lbl] = $row[Field];
                    $formItems[$i][type] = $row[Type];
                    $formItems[$i][nul] = $row["Null"];
                }
                $i++;
            }
            return $formItems;
        }
        else
        {
            return false;
        }
    }

And here is a method to generate forms based on that data:

/**
 * This function gets the details of a table and
 * creates a form to insert values in that table
 * $ignoredFields is an array of fields which should not be in the form
 * $specialFields contain complete fields ready to output, (useful if you need fields not in the table)
 * $existingData are data that should be displayed in the fields
 * $options[formTitle] displays a title above the form in a separate <div>
 * $options[errors][fieldName] display the field's label in bold red letters
 * $options[hidden][fieldName] set field as hidden and the value is $options[hidden][fieldName][value]
 * @param <string> $db_name
 * @param <string> $tbl
 * @param <array> $ignoredFields
 * @param <array> $specialFields
 * @param <array> $existingData
 * @param <array> $options
 */
function form_db_table($db_name, $tbl, $ignoredFields, $specialFields, $existingData, $options)
{
# Get all the database fields that must be filled out.
$formItems = $this->getDatabaseFields($db_name, $tbl, $ignoredFields);

    # Generate the form fields and load them in variables
    foreach ($formItems as $key=>$value)
    {
       # $fieldName is the actual field name in the database.
       # $fieldLbl is the name displayed in the form before the field
       $fieldName = $value[lbl];
       $pattern = array('/([a-z])([A-Z])/','/[_-]/');
       $replacement = array('$1 $2', ' ');
       $fieldLbl = ucfirst(strtolower(preg_replace($pattern, $replacement, $fieldName)));

       # if $fieldName is in $options[hidden], an hidden input is created
       if (is_array($options[hidden]))
       {
      if (array_key_exists($fieldName, $options[hidden]))
      {
        $val = $options[hidden][$fieldName];
        $formEntries .= "<input type='hidden' name='$fieldName' value='$val' />";
        continue;
      }
       }
       if($value[nul] == "YES")
       {
            $mandatory = "";
       }
       else
       {
            $mandatory = "*";
            $mandatoryFields .= $value[lbl] . ";";
       }
       // from type, decide which form item to use: varchar = <input> ...
       if (stripos($value[type],"varchar") !== false)
       {
            $varcharLimit = substr($value[type], 8, -1);
            if ($varcharLimit < 71)
            {
            $inputItem = "<input type=\"text\" size=\"38\" maxlength=\"$varcharLimit\"".
            " name=\"$fieldName\" value=\"$existingData[$fieldName]\" class=\"entryField\"/>";
        }
        else
        {
            $inputItem = "<textarea cols=\"35\" rows=\"3\" wrap=\"VIRTUAL\"" .
            " name=\"$fieldName\" class=\"entryField\">$existingData[$fieldName]</textarea>";
        }
   }
       else if (stripos($value[type],"text") !== false)
       {
       $inputItem = "<textarea cols=\"35\" rows=\"8\" wrap=\"VIRTUAL\"" .
       " name=\"$fieldName\" class=\"entryField\">$existingData[$fieldName]</textarea>";
       }
       else if (stripos($value[type],"date") !== false)
       {
           $inputItem = "<input type=\"text\" size=\"38\" maxlength=\"50\"".
           " name=\"$fieldName\" value=\"$existingData[$fieldName]\" class=\"entryField\"/>";
       }
       else if (stripos($value[type],"enum") !== false)
       {

       $inputItem = "<select size=\"1\" name=\"$fieldName\">\r\n";
       if (isset($existingData[$fieldName]))
       {
            $inputItem .= "<option value=\"$existingData[$fieldName]\">$existingData[$fieldName]</option>";
       }
       $enumVal = explode(",",substr($value[type], 6, -1));
       foreach($enumVal as $key => $value)
       {
            $val= trim(str_replace("'", "", $value));
            $inputItem .= "<option value=\"$val\">$val</option>";
           }
       $inputItem .= "</select>";
    }
      ## !!! COMPLETE THE LIST OF TYPES !!!

      $error = $options[error][$fieldName];

      $formEntries .= "<div class=\"entry\">\r\n";
      $formEntries .= "<label class=\"lbl_regular\" style=\"$error\">\r\n";
      $formEntries .= "$fieldLbl$mandatory</label>\r\n$inputItem \r\n";
      $formEntries .= "</div>\r\n";

    }

    # Sends the list of mandatory fields
    if ($mandatoryFields != "")
    {
        $mandatoryFields = substr($mandatoryFields, 0, -1);
        //- Explode to determine which fields can't be blank -\\
        $mandatoryFields = "<input type='hidden' name='mandatory' value='$mandatoryFields'>\r\n";
    }

    # Extract special fields - fields and labels ready for output
    if (is_array($specialFields))
    {
    foreach ($specialFields as $key=>$value)        
    {
      if($value[where]="before")
      {
        $specFieldsBefore .= "$value[openField] $value[lbl] $value[field]\r\n $value[closeField] \r\n";
      }
      else
      {
        $specFieldsAfter .= "$value[openField] $value[lbl] $value[field]\r\n $value[closeField] \r\n"; 
      }
    }
    }
    # Error message
    if (isset($options[errMsg]))
    {
      echo "<div class=\"errorMsg\">$options[errMsg]</div>";
    }
    # Output the top of the form
    echo $this->formTag;
    if (isset($options[formTitle]))
    {
    echo "\r\n<div class=\"formTitle\">$options[formTitle]</div>\r\n";
    }
    echo "<fieldset class=\"formFieldSet\">\r\n";

    #output the the actual fields
    echo $mandatoryFields;
    echo $specFieldsBefore;
    echo $formEntries;
    echo $specFieldsAfter;

    # Close fieldset, add a validate button and close the form
    echo "</fieldset>";
    echo "<center><input type=\"submit\" value=\"Submit\" name=\"submit\" /></center>";
    echo "</form>";

}

No doubt there must be more elegant solutions out there, but if the form's purpose is to fill out a database table, it makes it pretty easy to generate a form.

Sylverdrag