Form subclass example.
Form subclass exampleIt's also possible to override the HtmlForm class and add elements in the constructor. This way we can build reusable form classes or add custom rules to the form validation.
<?php
require_once '../../HtmlForm.php';
class HtmlFormSubclass extends HtmlForm
{
public function __construct(string $name, array $parameters = [], HtmlForm|null $form = null)
{
parent::__construct($name, $parameters);
$this->addText('username', ['label' => 'User name']);
$this->addEmail('email', ['label' => 'Email address']);
}
protected function onValidate(): bool
{
if (!$this->getElement('username')->isEmpty()) {
$this->getElement('email')->setRequired();
}
return parent::onValidate();
}
}
$form = new HtmlFormSubclass('exampleSubclass');
$form->process();
if ($form->validate()) {
echo('<a href="">back</a>');
echo('<pre>');
var_dump($form->getValues());
echo('</pre>');
$form->clearSession();
} else {
?>
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="../../lib/css/depage-forms.css">
</head>
<body>
<?php echo($form); ?>
</body>
<?php
}