Saving time on forms.

Reading time ~1 minute

As the saying goes, “Work smarter, not harder.” Here’s how I saved quite a bit of tedious HTML form work on one of my recent database-driven website projects.

For one of my recent projects, the Jamaica Football Database, I needed to create many forms for different types of records for players, staff, referees, teams, parishes, and so on. Each type of record has a corresponding database table within the MySQL database. Instead of writing all of that HTML by hand, I created two PHP classes to handle the generation of the forms and the processing of their submission. I used code generated by the PHP Object Generator for this project, which was the glue between these two classes and the database.

The first class, which I named ‘Form’, reads the field types from the selected table in the database and outputted HTML input, select, or textarea elements based on the field type. The class constructor accepts several other optional parameters. This class could also handle file uploads for fields with the VARCHAR type and a specific suffix in the field name.

  • A primary key value, to identify the record to retrieve default values from.
  • An array of the fields wanted from the table. This was added so that I could arrange different parts of the form separately.
  • An array of fields from the table that should be hidden fields in the form.
  • An array of text descriptions for the form fields.
  • An array of fields that should be ignored (so I could get all fields except for specific ones).

The second class, which was named ‘FormSubmit’, handles adding or editing records within the database. It reads the field list from the selected table and retrieves POST parameters that match the field names. It’s constructor also accepted an optional array of required fields, and an array of field descriptions (for error message purposes).

Writing these classes instead of writing the forms and form handing code by hand ended up saving quite a bit of time and was simpler that I initially thought it would be.

Tin Khan

After five months of working at Saltbox in early 2012, funds ran out. I seriously considered taking a gamble with a work-for-equity offer...… Continue reading

A Comeback for Another Drink

Published on September 25, 2016

Fanonic Update

Published on July 26, 2012