Ejemplo n.º 1
0
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
// include the class file
include __DIR__ . '/../FormData/FormData.php';
$FormData = new FormData();
try {
    // create the form fields and set parameters
    $FormData->setFields([['type' => 'text', 'label' => 'First name', 'name' => 'first-name', 'required' => '1', 'required_message' => 'We\'d love to know your first name!', 'max_length' => '50'], ['type' => 'select', 'label' => 'Favourite colour', 'name' => 'colour', 'required' => '1', 'option' => ['1' => 'Red', '2' => 'Yellow', '3' => 'Blue']], ['type' => 'checkbox', 'label' => 'Are you OK?', 'name' => 'ok', 'checkbox_value' => 'yes', 'checkbox_value_alt' => 'no']]);
    // check for form submission
    if ($_POST['submit'] == 'submit') {
        // search POST array for all fields that were set above and check submitted data
        $FormData->checkPost();
        /* ********************************* Adding some custom error messages ********************************* */
        // add a generic error that is not linked to any fields, these will always be added to the end of the list
        $FormData->setError(NULL, 'A generic error message');
        // perform further, custom checks on submitted data, for example - create an error if 'first-name' is Paul
        if (!$FormData->hasError('first-name')) {
            $submitted = $FormData->getClean('first-name');
            if (strtolower($submitted) == 'paul') {
                $FormData->setError('first-name', 'cannot be Paul, sorry');
                // message will be prefixed with field label
            }
        }
        // assign an error to a field without generating a message - for example - create an error if the 'colour' is yellow (ID = 2) but the checkbox is not checked
        if ($FormData->getClean('colour') == '2' && $FormData->getClean('ok') == 'no') {
            $FormData->setError('colour');
            // this field will be highlighted as having an error but no message will be logged, the next line will create the message for both fields
            $FormData->setError('ok', 'If your favourite colour is yellow then you must be OK', false);
            // to disable the field label being prefixed, add a 3rd argument 'false'
        }