<?php
/**
 * Demo selbsreferenzierendes Formular mit Fehlerbehandlung
 */

define('BRLF', "<br/>\n");
$arrErrors = array();

if (count($_POST) > 0) {
	$arrErrors = validateForm($_POST);
	if (sizeof($arrErrors) > 0)
	showForm($arrErrors, $_POST);
	else
	processForm($_POST);
}
else {
	showForm($arrErrors, $_POST);
}

function showForm($arrErrors, $arrPostedData)
{
	echo <<<STARTHTML
	<html>
	<head>
	<meta http-equiv="Content-Language" content="en" />
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
	<title>Formular</title>
	<style type="text/css">
		.ok {margin:2px;}
		.error {border:solid 2px red;
				margin:4px;}
	</style>
	</head>
	<body>
	<h1>Kostenstelle</h1>
STARTHTML;

	if (sizeof($arrErrors) > 0) {
		echo 'Fehler in Eingabe:'.BRLF;
	}
	echo openForm($_SERVER['PHP_SELF'], 'POST');
	echo inputText('Name', 'name', $arrPostedData['name'], $arrErrors).BRLF;
	echo inputText('Vorname', 'vorname', $arrPostedData['vorname'], $arrErrors).BRLF;
	echo inputText('Kostenstelle', 'kostenstelle', $arrPostedData['kostenstelle'], $arrErrors).BRLF;
	echo submitForm();
	echo closeForm();

	echo <<<ENDHTML
	</body>
	</html>
ENDHTML;
}

function inputText($strLabel, $strName, $strValue, $arrErrors) {
	$strClass = 'ok';
	$strError = '';
	if (isset($arrErrors[$strName])){
		$strClass = 'error';
		$strError = ' ('.$arrErrors[$strName].')';
	}
	return "{$strLabel}: <input type='text' name='{$strName}' value='{$strValue}' class='{$strClass}' />{$strError}";
}

function openForm($strAction, $strMethod) {
	return "<form action='{$strAction}' method='{$strMethod}'>";
}

function submitForm($strValue = 'Absenden') {
	return "<input type='submit' value='{$strValue}'>";
}

function closeForm() {
	return '</form>';
}

function validateForm($arrPostData) {
	$arrErrors = array();
	if (!isset($arrPostData['name']) || (strlen($arrPostData['name']) == 0)) {
		$arrErrors['name'] = 'Kein Wert eingegeben.';
	}
	else {
		// weitere Checks
	}

	if (!isset($arrPostData['vorname']) || (strlen($arrPostData['vorname']) == 0)) {
		$arrErrors['vorname'] = 'Kein Wert eingegeben.';
	}
	else {
		// weitere Checks
	}

	if (!isset($arrPostData['kostenstelle']) || strlen($arrPostData['kostenstelle']) == 0) {
		$arrErrors['kostenstelle'] = 'Kein Wert eingegeben';
	}
	else {
		if(is_numeric($arrPostData['kostenstelle'])
		&& ($arrPostData['kostenstelle'] > 0)
		&& ((int) $arrPostData['kostenstelle']) == $arrPostData['kostenstelle']) {
			// Weitere Checks...
		}
		else 
			$arrErrors['kostenstelle'] = 'Falscher Wert. Muss ganze Zahl > 0 sein.';
	}

	return $arrErrors;
}

function processForm($arrPostedData) {
	echo 'Vielen Dank für die Eingabe:'.BRLF;
	echo 'Name: '.$arrPostedData['name'].BRLF;
	echo 'Vorname: '.$arrPostedData['vorname'].BRLF;
	echo 'Kostenstelle: '.$arrPostedData['kostenstelle'].BRLF;
	// ...weiter verarbeiten
}
?>