Skip to content

Instantly share code, notes, and snippets.

@kalinchernev
Created January 20, 2014 11:14
Show Gist options
  • Save kalinchernev/8518409 to your computer and use it in GitHub Desktop.
Save kalinchernev/8518409 to your computer and use it in GitHub Desktop.
Basic class to build a form from an array
<?php
/**
* Form Class
*
* Responsible for building forms
*
* @param array $elements renderable array containing form elements
*
* @return void
*/
class Form {
public $elements;
public $form_number = 1;
public function __construct($elements){
$this->elements = $elements;
}
/**
* Form class method to dump object elements
*
* The method just dumps the elements of the form passed to the instantiation.
*
* @return void
*
*/
public function dumpElements() {
var_dump($this->elements);
}
/**
* Form class method to build a form from an array
*
*
* @return string $output contains the form as HTML
*
*/
function build() {
$output = '';
// For multiple forms, create a counter.
$this->form_number++;
// Loop through each form element and render it.
foreach ($this->elements as $name => $elements) {
$label = '<label>' . $elements['title'] . '</label>';
switch ($elements['type']) {
case 'textarea':
$input = '<textarea name="' . $name . '" ></textarea>';
break;
case 'submit':
$input = '<input type="submit" name="' . $name . '" value="' . $elements['title'] . '">';
$label = '';
break;
default:
$input = '<input type="' . $elements['type'] . '" name="' . $name . '" />';
break;
}
$output .= $label . '<p>' . $input . '</p>';
}
// Wrap a form around the inputs.
$output = '
<form action="' . $_SERVER['PHP_SELF'] . '" method="post">
<input type="hidden" name="action" value="submit_' . $this->form_number . '" />
' . $output . '
</form>';
// Return the form.
return $output;
}
}
<?php
/**
* This files contains the list of forms defined
*
*/
// Renderable array with a form elements.
$contact_form = array(
'name' => array(
'title' => 'Name',
'type' => 'text',
'validations' => array('not_empty'),
),
'email' => array(
'title' => 'Email',
'type' => 'email',
'validations' => array('not_empty', 'is_valid_email'),
),
'comment' => array(
'title' => 'Comments',
'type' => 'textarea',
'validations' => array('not_empty'),
),
'submit' => array(
'title' => 'Submit me!',
'type' => 'submit',
),
);
<?php
require_once 'formsList.php';
require_once 'classes/Form.class.php';
$form = new Form($contact_form);
$form_html = $form->build();
?>
<!DOCTYPE html>
<html>
<head>
<title>The index file</title>
</head>
<body>
<?php echo $form_html; ?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment