Programming forms is fairly easy, but it can certainly be one of the most tedious things to program. Anyone who’s programmed something like an application form with a decent amount of fields will tell you that it takes forever to make all of the form elements, and add the necessary code to pre-populate with values or pre-check radio buttons etc. (This is a good practice when programming forms, so a user doesn’t have to fill the form out again if it’s submitted with errors.) Whether you’re smart or just lazy, you’ll definitely want to make a simple PHP function to expedite this otherwise-boring process. Enter: the formElement() function.
/** * form elements */ function formElement($type, $name, $value = '',$extra = '') { global $_POST; if ($type=='text') { $val = (!empty($_POST[$name])) ? $_POST[$name] : $value ; $o = '<input type="text" name="'.$name.'" value="'.$val.'"'.$extra.' />'; } elseif ($type=='radio') { $checked = ($_POST[$name]==$value) ? 'checked="checked"' : ''; $o = '<input type="radio" name="'.$name.'" value="'.$value.'" '.$checked.' '.$extra.' />'; } elseif ($type=='checkbox') { $checked = ($_POST[$name]==$value) ? 'checked="checked"' : ''; $o = '<input type="checkbox" name="'.$name.'" value="'.$value.'" '.$checked.' '.$extra.' />'; }
return $o; }
It’s pretty straight-forward, but I’ll break it down parameter-by-parameter.
$type – in my example, this is the same as the type attribute in the html input tag. You could expand the function to include textareas too, or whatever you need.
$name – same as the name attribute.
$value – For checkbox and radio types, it uses this value to check against the item in the $_POST array, and adds checked=”checked” where appropriate. For text types, it pre-populates the textbox with this value if the form hasn’t been submitted yet.
$extra – I use this for any other attributes you may need to add to your form elements. Things such as CSS inline styles, event handlers like onclick, and id or class attributes could go here.
So with our new formElement function, this;
<input type="radio" name="fav_food" value="pizza" <?=($_POST['fav_food'] == 'pizza') ? 'checked="checked"' : '';?> /> Pizza <input type="radio" name="fav_food" value="souvlaki" <?=($_POST['fav_food'] == 'souvlaki') ? 'checked="checked"' : '';?> /> Souvlaki
becomes this:
<?=formElement('radio','fav_food','pizza');?> Pizza <?=formElement('radio','fav_food','souvlaki');?> Souvlaki