# Formidable: PHP forms made simple

2013-11-04 #php #forms

Forms are doubtless one of the most important part of writing a web application, because it deals with how the user interact with it.

Handling a form “manually” with pure-PHP is boring and repetitive, that’s why it’s really important to have a good form library to rely on (more than a templating engine IMO).

With most of the form libraries out there, the problem is that you have to learn the API to build fields. Hence, when you will render it, if you want to do something custom, it may be complex.

## So, what’s new?

The approach of Formidable is different. Instead of using a PHP API to build your form, you can write it directly in HTML, like this:

And give it to Formidable:

This way, the form will be parsed and an internal representation is constructed. You can interract with your form using PHP. Formidable is able to recognize all the input types, radios, selects, textarea etc.

The output form will look like this:

Note that a security token is automatically injected in the form.

## Enjoy the magic!

Now, you can manipulate your form using PHP, for instance, you can set field value:

And, of course, you can handle the form when its posted:

The handle() method will call its clalback if the form was posted and is valid. This way, if the field name has a maxlength constraint, Formidable will check that the length of the posted value is smaller than maxlength. If there is errors, Formidable will re-populate the form with posted data automatically to avoid re-typing everything.

Moreover, it provides extra attributes that doesn’t exists in HTML:

The minlength attribute doesn’t exist in HTML, and thus won’t be displayed in the form. However, Formidable will use this information for checking data.

## Play with inputs

Formidable recognizes all inputs, for instance:

As you can see, the select is parsed and available with setValue and getValue exactly the same way as other inputs.

## Sourcing

Imagine you want to populate your form choices with data from your database, or anything else, you can then use sourcing:

“Huh, but, Formidable constructor takes a file or a form string, I don’t get it”: actually, both works, Formidable will guess wheter its first constructor argument is the form data or a filename. If there is a line break \n, it will consider the input as a form, else as a filename.

The example above will populate the select series with an array from the outside of the form. Note that the resulting option values will be 0, 1 and 2 here.