-
-
Save Ocramius/02c3a9e6db97ca4a018a to your computer and use it in GitHub Desktop.
<?php | |
$formHtml = <<<'HTML' | |
<form action="%s" method="post"> | |
<label for="email">Email:</label> | |
<input | |
type="email" | |
id="email" | |
name="email" | |
value="" | |
aria-describedby="email-description" | |
data-reuse-submitted-value="true" | |
data-validator="email-address" | |
required="required" | |
/> | |
<span id="email-description" class="help">Enter a valid email address</span> | |
<input type="submit"/> | |
</form> | |
HTML; | |
$form = $formFactory->fromHtml($formHtml); | |
var_dump($form->validate($_POST)); // returns form validion result VO | |
echo $form->asString(); |
@Fedik that is kinda useless: what I want to get rid of is a DSL for forms that is NOT an HTML form. The HTML forms specification includes loads of stuff that already covers most use-cases of forms, therefore we should just stop re-implementing it from scratch.
@Ocramius nice idea. Probably I would use 3 different validation methods: validateFromGlobals()
($_POST
or $_GET
depending on form method) validateArray()
and validateRequest()
for PSR-7 request object.
Also, you probably need to know when form is submitted and when not.
/** @var FormLib\FormtInterface $validation */
$form = $formFactory->fromHtml($formHtml);
/** @var FormLib\ValidationObjectInterface $validation */
$validation = $form->validateFromGlobals();
/** @var string[] $messages */
$messages = $form->isSubmitted() ? $validation->getErrorMessages() : [];
/** @var array $data */
$data = $form->data(); // strips any information in globals that is not provided by form, empty when form not submitted
if ($messages) {
vprintf(
'<ul class="form-errors">'.str_repeat('<li>%s</li>', count($messages)).'</ul>',
array_map('htmlentities', $messages)
);
} elseif(!$form->isSubmitted()) {
echo $form; // __toString()
}
if ($data) {
$success = do_something_with_data($data);
echo $success ? '<p>Thank You!</p>' : '<p>Something bad happened.</p>';
}
Regarding implementation, using https://github.com/Level-2/Transphporm should be quite simple.
Those are controller concerns imo, not form's.
How about this: https://github.com/xtreamwayz/html-form-validator
@xtreamwayz that kinda resembles my thoughts. I forgot to mention that @jstoone already started work on this at jstoone/HTMLFormValidator#1
Opened https://github.com/xtreamwayz/html-form-validator/issues/1 to avoid you folks stumbling on each other by accident (do it on purpose!)
there is https://github.com/joomla-framework/form not exactly what you dreams about, but close ... on some points :)
it works with "XML forms"
but there is no
asString()
, all fields need to render "manually" :/