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';
{
public function __construct($name, $parameters = [])
{
parent::__construct($name, $parameters);
$this->addText('username', ['label' => 'User name']);
$this->addEmail('email', ['label' => 'Email address']);
}
public function onValidate()
{
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
}