Forms
Forms - this is actually the center of our work and sometimes it could be a bit of a boring routine. Of course, forms are not only about their display. Their capture is also important - i.e. capture of input data and their validation and subsequent transfer of data. And this does not apply only to those forms that 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. So capture and validation is a general problem that concerns forms, even though perhaps when you say the word form, the first thing you associate is the form visible on the page.
Therefore, Jet Form must solve the following circuits:
- Defining forms
- Capturing, validating and working with data
- Displaying forms
Before we discuss everything in detail in the following chapters, let's show an example of the form right away. This is a simple example of, say, a registration form for entering a name and date of birth, with the fact that the data is mandatory and the date must be entered using an input field with a calendar and to validate whether the input really contains a 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_required: true
);
$name_field->setErrorMessages([
Form_Field_Input::ERROR_CODE_EMPTY => 'Please enter your name'
]);
$birthdate_field = new Form_Field_Date(
name: 'birthdate',
label: 'Birthdate:',
is_required: true
);
$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);
View - 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 do it all. That is, the definition of the form, its capture and validation, as well as display. In addition, everything is automatically connected to the translator . Everything is of course fully customizable - this demo is really just a bare minimum. We will show everything in the following chapters. I recommend continuing to form definitions .