Forms

Forms - this is actually the heart of our work and sometimes it could be a bit of a boring routine. Of course, forms are not just about displaying them. Capturing them is also important - that is, capturing the input data and validating it and then passing the data on. And this doesn't just apply to the forms the user sees on the page. We can (and actually must) capture and validate data when processing API requests (e.g. REST), or in AJAX applications, and so on. Thus, capturing and validating is a general problem that applies to forms, even though perhaps the first thing one associates when saying the word form is the form visible on the page.

Thus, Jet Form must address the following topics:

  • Defining forms
  • Capture, validate and work with data
  • Displaying / rendering forms

Before we discuss everything in detail in the following chapters, let's show an example of a form. This is a simple example of, say, a registration form for entering a name and date of birth, with the data being mandatory and the date having to be entered using the calendar input field and validating that the input is indeed the date:

Controller
use Jet\Form;
use 
Jet\Form_Field_Date;
use 
Jet\Form_Field_Input;

$name_field = new Form_Field_Input(
    
name'name',
    
label'Name:',
    
is_requiredtrue
);
$name_field->setErrorMessages([
    
Form_Field_Input::ERROR_CODE_EMPTY => 'Please enter your name'
]);

$birthdate_field = new Form_Field_Date(
    
name'birthdate',
    
label'Birthdate:',
    
is_requiredtrue
);
$birthdate_field->setErrorMessages([
    
Form_Field_Date::ERROR_CODE_EMPTY => 'Please enter your birthday',
    
Form_Field_Date::ERROR_CODE_INVALID_FORMAT => 'Please valid date'
]);

$form = new Form(name:'registration_form'fields:[
    
$name_field,
    
$birthdate_field
]);

if(
$form->catch()) {
    
//Form has been sent and is valid
    
$name $form->field('name')->getValue();
    
$birthdate $form->field('birthdate')->getValue();
    
//...
}

$view->setVar('registration_form'$form);

Pohled - view
use Jet\MVC_View;
use 
Jet\Form;
use 
Jet\UI;

/**
 * @var MVC_View $this
 * @var Form $form
 */

$form $this->getRaw('registration_form');
?>

<?=$form->start()?>
    <?=$form->message()?>

    <?=$form->field('name')?>
    <?=$form->field('birthdate')?>

    <?=UI::button_save()?>

<?=$form->end()?>

These short pieces of sample code solve everything. That is, form definition, form capture and validation, and display. Besides, everything is automatically connected to the translator. Everything is of course fully customizable - this sample is really just a minimal primer. We'll demonstrate everything in the following sections. I recommend continuing on to form definitions.

Previous chapter
Jet\DataModel_Helper
Next chapter
Definition of forms