Download the PHP package popphp/pop-form without Composer
On this page you can find all versions of the php package popphp/pop-form. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download popphp/pop-form
More information about popphp/pop-form
Files in popphp/pop-form
Package pop-form
Short Description Pop Form Component for Pop PHP Framework
License BSD-3-Clause
Homepage https://github.com/popphp/pop-form
Informations about the package pop-form
pop-form
- Overview
- Install
- Quickstart
- Field Elements
- Field Configurations
- Fieldsets
- Legends
- Field Containers
- Accessibility
- Filtering
- Validation
- CSRF Protection
- File Uploads
- Dynamic Fields
- ACL Forms
Overview
pop-form is a robust component for managing, rendering and validating HTML forms.
With it, you can have complete control over how a form looks and functions as well
as granular control over field validation. Features include:
- Field element creation and configuration
- Validation
- Use any callable validation object, such as
pop-validatoror custom validators
- Use any callable validation object, such as
- Filtering
- Dynamic field generation based on the fields of a database table
pop-formis a component of the Pop PHP Framework.
Top
Install
Install pop-form using Composer.
composer require popphp/pop-form
Or, require it in your composer.json file
"require": {
"popphp/pop-form" : "^5.0.0"
}
Top
Quickstart
The most basic way to wire up a form object is through a simple configuration.
The form rendered will look like:
Upon submit, if the form values do not pass validation, the form will re-render with the errors
(note the error div under the username field):
Note the aria-invalid/aria-describedby on the input and the role="alert" on the error div — these are
wired automatically whenever a field has errors or a hint. See Accessibility below.
The form object will default to POST as the method and the current REQUEST_URI
as the action, but those values can be changed in a number of ways:
(Note: new Form(...)'s first argument expects an array of already-built field element objects, not a
config array — see Field Elements below for that form of construction.)
Top
Field Elements
A form can be wired up by interfacing directly with form element objects and the form object itself.
There are number of different concepts happening in the above example:
- We created the form object and gave it an
idattribute. - We created the individual field elements setting their name, label, attributes, validators, etc.
- We added the field elements to the form object.
- We checked for a
$_POSTsubmission. If not detected, we just render the form for the first time. - If a
$_POSTsubmission is detected:- Set the field values with the values in the $_POST array (a bad idea without any filtering)
- Check if the form object passes validation. If not, re-render the form with the errors. If it does pass, then you're good to go.
On the first pass, the form will render like this:
If it fails validation, it will render with the errors. In this case, the username was not alphanumeric (note that the submitted value is echoed back into the field, which is exactly why filtering submitted values matters):
Top
Field Configurations
We can do the same thing as above with a field configuration array, which helps streamline the process:
Top
Fieldsets
Multiple fieldset configurations can be used to generate a larger form with more organized elements. This requires the config to contain multiple arrays of field configurations:
Which produces the following HTML with the appropriate fieldset grouping:
Top
Legends
If you'd like to label each of the multiple fieldsets, that can be done by using legend values
as the array keys in the config:
Which produces the following HTML with the appropriate fieldset grouping:
Top
Field Containers
The default fieldset HTML containers for the form elements is a combination of dl, dt and dd tags.
If alternate container tags are needed, you can set them like these examples below.
Using table:
Using div (or any other single element container):
Top
Accessibility
Whenever a field has a hint and/or validation errors, pop-form automatically wires up the ARIA attributes
that connect them for assistive technology — there's nothing extra to configure. Given a required field with
a hint that fails validation:
it renders like this once it has an error:
- The hint and error containers get predictable, stable ids (
{name}-hint/{name}-error). - The field itself gets
aria-describedby, listing whichever of those ids apply, andaria-invalid="true"while it has errors — both are removed again once the field is valid, so a corrected field doesn't keep announcing itself as invalid on re-render. - The error container gets
role="alert", so screen readers announce it as soon as it appears. aria-invalidis intentionally left offCheckboxSet/RadioSet(they render as a<fieldset>, andaria-invalidisn't a valid ARIA state for a grouping element) —aria-describedbyis still applied there.
Top
Filtering
As mentioned above, when dealing user-submitted values, it's a bad idea to use them or
display them back on the screen without filtering them. A common set a filters to employ
would be strip_tags and htmlentities. So in the first example, we would add filters
to the $_POST block:
Of course, the strip_tags filter will strip out any possible malicious tags. The htmlentities
filter is useful if the form has to render with the values in it again:
Without the htmlentities filter, the quotes within the value would break the HTML of the input field.
Of course, if you want to use the values after the form is validated, then you have to call clearFilters()
and filter the values with html_entity_decode.
Top
Validation
Of course, one of the main reasons for using a form component such as this one is the leverage
the validation aspect of it. You've already seen the use of a basic validator from the pop-validator
component and those are easy enough to use. But, you can create your own custom validators by
either extending the pop-validator component with your own or just writing your own custom
callable validators. The only real rule that needs to be followed is that the custom validator
must return null on success or a string message on failure that is then used in error display.
Here are some examples:
Using a closure
Using a validator
Using a custom class
Validation-only forms
There is a FormValidator class that is available for only validating a set of field values. The benefit
of this feature is to not be burdened with the concern of rendering an entire form object, and to only
return the appropriate validation messaging. This is useful for things like API calls, where the form
rendering might be handled by another piece of the application (and not the PHP server side).
If the field values are bad, the $form->getErrors() will return an array of errors like this:
Top
CSRF Protection
A CSRF token field can be added to a form just like any other field, using the csrf type:
This renders as a hidden input whose value is a cryptographically random token, stored server-side in the
session (starting one automatically, if needed) and validated on submission with a timing-safe comparison —
a mismatched or missing token fails validation with the message The security token does not match..
A few things worth knowing:
- Tokens are namespaced in the session by the field's name, so multiple CSRF-protected forms/fields can coexist in the same session (and page) without clobbering each other's token.
- Tokens expire after 300 seconds by default; pass a different number of seconds via the
expireconfig key (or theCsrfelement's constructor) to change that. A value of0or less disables expiration entirely. - Call
$form->clearTokens()to clear all stored CSRF tokens from the session — a reasonable thing to do after a successful, sensitive submission. - There is no
captchafield type. A math/image CAPTCHA is trivial for modern bots to defeat and offers little real protection; if you need to filter out unsophisticated form spam, a honeypot field (a hidden input real users never fill in) is a lighter-weight, more effective alternative to build at the application level.
Top
File Uploads
The file field type accepts two optional, purpose-built validation options beyond the standard config keys:
allowed-typesis an extension allowlist (case-insensitive; a leading dot is optional, so'jpg'and'.jpg'are equivalent). It's checked against the client-submitted filename's extension only — not the file's actual content, so it's not a hard content-type guarantee (a client can rename any file). Pair it with real content validation (e.g.finfo/magic-byte sniffing) at the point you actually store the file, if that distinction matters for your use case.max-sizeis the maximum allowed upload size in bytes, checked against the size PHP itself reports for the upload. The resulting error message is human-readable (e.g.The file size must be less than or equal to 2 MB.) rather than a raw byte count.Formautomatically setsenctype="multipart/form-data"on the<form>tag at render time whenever it contains afilefield — there's nothing extra to configure for that.
Both of these can also be set directly on the element itself, via setAllowedTypes(array $extensions) and
setMaxSize(int $bytes).
Top
Dynamic Fields
The pop-form comes with the functionality to very quickly wire up form fields that are mapped
to the columns in a database. It does require the installation of the pop-db component to work.
Consider that there is a database table class called Users that is mapped to the users table
in the database. It has six fields: id, username, password, first_name, last_name and email.
(For more information on using pop-db click here.)
This will render like:
You can set element-specific attributes and values, as well as set fields to omit, like
the 'id' parameter in the above examples. Any TEXT column type in the database is
created as textarea objects and then the rest are created as input text objects.
Top
ACL Forms
ACL forms utilize the pop-acl component and are an extension of the regular form class
that take an ACL object with its roles and resources and enforce which form fields can
be seen and edited. Consider the following code below:
The $admin has no restrictions. However, the $editor role does have restrictions and
cannot edit the username field and cannot view the password field. Setting the $editor
as the form role and rendering the form will look like this:
There is no password field and the username field has been made readonly. Switch the
role to $admin and the entire form will render with no restrictions:
All versions of pop-form with dependencies
popphp/pop-acl Version ^5.0.0
popphp/pop-dom Version ^5.0.0
popphp/pop-filter Version ^5.0.0
popphp/pop-utils Version ^3.0.0
popphp/pop-validator Version ^5.0.0