- Saved searches
- Use saved searches to filter your results more quickly
- License
- FormHandler/FormHandler
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Dealing with Forms
- User Contributed Notes 3 notes
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
FormHandler is a PHP module which allows you to easily create a working form with validation
License
FormHandler/FormHandler
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This FormHandler is a PHP solution to generate form fields and validate them. Making forms is in general a time-taking job. In this package we try to offer a solution so that making forms is easy.
FormHandler implements the PSR-1 and PSR-2 coding standards. FormHandler implements the PSR-4 autoloading standard.
To create a form you have to:
- Define the form and its fields
- Check if the form is submitted and if it’s valid
- Parse the form’s fields in your HTML / view
FormHandler requires PHP 7.4 or higher.
You can install FormHandler by downloading the latest zip file and include this in your project.
We are working on availability for composer.
FormHandler has a few assumptions:
- A form is always submitted to itself. That means, to the same script/page where the form is defined.
- We assume that when you create a SubmitButton or ImageButton , that you don’t use own HTML tag buttons.
# # This code defines your form and what to do with it when it's valid. # This code is probably defined in your controller. # // Create the form $form = new Form(); // Create a field in the form. Fluent method chaining is supported. $form->textField('name') ->addValidator(new StringValidator(2, 50, true, 'You have to supply your name (between 2 and 50 characters)')) ->setPlaceholder('Enter your name'); // Check if the form is submitted if ($form->isSubmitted()) < // Check if the form is valid. if ($form->isValid()) < // Do your stuff here with the form, for example, store something in a database. > > else < // Here, the form is not yet submitted! // You could for example set some predefined values in the form. > # # Then, in your view, you can use your form fields. # // This will display the html tag. echo $form; // This will display the HTML tag for the "name" field. echo $form('name'); // You can mix plain old html with "dynamic" generated fields // Of course you could also generate a SubmitButton object and use that one. echo '';
So, this was our first basic example. Let’s see what happens here.
- First we create the form and add a textfield called «name». We append a StringValidator to the field where we allow values between 2 and 50 characters.
We define that this field is required and if the field is invalid, we use a custom error message. - Then we check if our form is submitted. If the form is not yet submitted, you could prefill your fields with predefined values. This is usually the case for edit forms. On your first execution of this script, the form will not be submitted, so this part will be skipped.
- After checking if the form is submitted, we check if the form is valid. If the form is valid, you can use the submitted values and process them (for example, store them in a database). When the submitted form is invalid, you could just ignore the values. The form will be rendered again, which will display the error message to the user about incorrect form fields.
- Finally, in our view we render the HTML. You are self responsible to render the fields where you want. FormHandler does not mix with the design of your fields, except from some form related HTML tags like label for a radio button.
FormHandler implements a fluent interface. This means that you can use method chaining. It’s not required though.
$form = new Form(); // An example using method chaining. $form->textField('name') ->setSize(10) ->setId('myName') ->setTitle('Enter your name') ->setPlaceholder('') ->addValidator(new StringValidator(2, 50, true));
Most objects (the form, fields and the buttons) represent an HTML tag. All of these objects have some global attributes available. In FormHandler, these global attributes are also available through getters and setters. For example:
- setTabindex( $index )
- getTabindex()
- setAccesskey( $key )
- getAccesskey()
- setStyle( $style )
- addStyle( $style )
- getStyle()
- addClass( $class )
- getClass()
- setClass( $class )
- setTitle( $title )
- getTitle()
- setId()
- getId()
This object represents the Form. It allows you to create fields in this form, retrieve fields, ask the status of the form (submitted, valid) and set form specific attributes (like action , enctype , etc).
The form object has an «invoke» option which allows you to quickly retrieve a form by its name. You can use it like this:
// Create a new form $form = new Form(); // Create a field in the form $form->textField('name'); // Retrieve the form by it's name using the shorthand: $field = $form('name'); // Or use the "classic" way: $field = $form->getFieldByName('name'); // . Etc
In short, you have these fields available.
- textField( $name )
- hiddenField( $name )
- passField( $name )
- selectField( $name )
- radioButton( $name , $value = » )
- selectField( $name )
- textarea( $name , $cols = 40 , $rows = 7 )
- checkBox( $name , $value = 1 )
- uploadField( $name )
You also have these buttons available:
You can also render buttons with FormHandler. A button is not used for validation, but when you create a button we do expect the button to be present in the submitted form.
If you have created mutiple buttons, then only 1 button needs to be present. If this is not the case, we assume the form is not submitted.
FormHandler does only contain some default error messages which are shown when a field is incorrect. For each Validator you can overwrite this error message with a localized variant of the error message.
Only the UploadValidator and ImageUploadValidator contain some more translations, based on the reason why a file could not be uploaded. You can overwrite these also. See for more details the documentation for the UploadValidator and ImageUploadValidator .
Security is very important in web forms. Displaying non-safe data can create serious security issues. Therefore it needs to be absolutly clear how FormHandler displays strings and which data is HTML escaped or not.
There are two rules which you need to remember:
- The values of fields are always escaped, as they can be filled automatically from $_GET or $_POST .
- Other attributes are filled by you, and are thus NOT escaped.
This means that button values are thus also not escaped, as they cannot be filled from the $_GET or $_POST .
FormHandler tries to limit its functionality to what it should do: handle forms. However, displaying the forms is related to this topic. When displaying forms, you cannot limit yourself to only display the form fields. There are always elements which are related:
- Title of the field
- Label of checkboxes / radio buttons
- Displaying error messages
- Displaying «help» information
- Displaying if the field is required or not
FormHandler tries to not to interfere with the design part of your application. However, it should be clear that it’s thus inevitable that FormHandler has some responsibility of generating HTML content.
FormHandler comes with a class called a Renderer . This class is responsible for rendering the element (field/button/form) and all its related information (error messages, titles, etc).
A Renderer is a simple class which should have at least 1 method: render( Element $element) . This method is in control to generate the correct HTML for the given Element . This could be a field, button, form or option.
The XhtmlRenderer is the default renderer. This class will make sure that all elements are rendered as XHTML. This class will also make sure that:
You can change this logic to setting it to render them as an attribute, or not render them at all.
Because the Renderer is responsible for all rendering, it’s quite easy to create your own class which will render the elements in the way you expect them. The easiest way of doing this is by extending the XhtmlRenderer. For example please take a look at the CowSayRenderer , which will render all Fields with a nice CowSay around them.
About
FormHandler is a PHP module which allows you to easily create a working form with validation
Dealing with Forms
One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from external sources for more information and examples on using forms with PHP. Here is an example HTML form:
Example #1 A simple HTML form
There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:
Example #2 Printing data from our form
A sample output of this script may be:
Hi Joe. You are 22 years old.
Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can’t inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an int which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST[‘name’] and $_POST[‘age’] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data.
You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.
User Contributed Notes 3 notes
According to the HTTP specification, you should use the POST method when you’re using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click «Reload» or «Refresh» on a page that you reached through a POST, it’s almost always an error — you shouldn’t be posting the same comment twice — which is why these pages aren’t bookmarked or cached.
You should use the GET method when your form is, well, getting something off the server and not actually changing anything. For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.
Also, don’t ever use GET method in a form that capture passwords and other things that are meant to be hidden.