PHPackages                             craftsmancoding/formbuilder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. craftsmancoding/formbuilder

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

craftsmancoding/formbuilder
===========================

Generate form elements for forms everywhere.

10621[1 issues](https://github.com/craftsmancoding/formbuilder/issues)1PHP

Since Nov 21Pushed 11y ago3 watchersCompare

[ Source](https://github.com/craftsmancoding/formbuilder)[ Packagist](https://packagist.org/packages/craftsmancoding/formbuilder)[ RSS](/packages/craftsmancoding-formbuilder/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (1)Used By (1)

Formbuilder
===========

[](#formbuilder)

Formbuilder is a flexible framework-independent form-generation library for PHP, built to generate HTML forms.

I grew tired of repeating myself myself and of Symfonic noise with no docs. Why you no document your code?
This is inspired from the Laravel library of the same name, but I needed a low-brow solution that was not dependent on an underlying framework.

In memory of my dumb friends...

Supported Inputs
----------------

[](#supported-inputs)

You can use this class to generate the following types of inputs. Most of these are verbatim implementations of the supported HTML input types, but some (like "dropdown" or "multicheck") offer convenient interfaces.

- [checkbox](https://github.com/craftsmancoding/formbuilder/wiki/checkbox) - you can customize the values sent when the box is checked or unchecked.
- [color](https://github.com/craftsmancoding/formbuilder/wiki/color) - (HTML 5)
- [datalist](https://github.com/craftsmancoding/formbuilder/wiki/datalist) - a typeahead type dropdown (HTML 5)
- [date](https://github.com/craftsmancoding/formbuilder/wiki/date) - (HTML 5)
- [datetime](https://github.com/craftsmancoding/formbuilder/wiki/datetime) - (HTML 5)
- [datetime\_local](https://github.com/craftsmancoding/formbuilder/wiki/datetime_local) - (HTML 5)
- [dropdown](https://github.com/craftsmancoding/formbuilder/wiki/dropdown) - a select field, used to select a single option.
- [email](https://github.com/craftsmancoding/formbuilder/wiki/email) - (HTML 5)
- [file](https://github.com/craftsmancoding/formbuilder/wiki/file) - used to choose a local file for uploading
- [hidden](https://github.com/craftsmancoding/formbuilder/wiki/hidden) - hidden fields
- [keygen](https://github.com/craftsmancoding/formbuilder/wiki/keygen) - (HTML 5)
- [month](https://github.com/craftsmancoding/formbuilder/wiki/month) - (HTML 5)
- [multiselect](https://github.com/craftsmancoding/formbuilder/wiki/multiselect) - a select field used to select multiple options
- [multicheck](https://github.com/craftsmancoding/formbuilder/wiki/multiselect) - functionally the same as multiselect, but formatted as multiple checkboxes
- [number](https://github.com/craftsmancoding/formbuilder/wiki/number) - (HTML 5)
- [output](https://github.com/craftsmancoding/formbuilder/wiki/output) - used to store calculated values (HTML 5)
- [password](https://github.com/craftsmancoding/formbuilder/wiki/password) - a standard password field
- [radio](https://github.com/craftsmancoding/formbuilder/wiki/radio) - functionally equivalent to a dropdown, but uses radio options
- [range](https://github.com/craftsmancoding/formbuilder/wiki/range) - displays a slider for selecting number within a range (HTML 5)
- [search](https://github.com/craftsmancoding/formbuilder/wiki/search) - displays a search form (HTML 5)
- [submit](https://github.com/craftsmancoding/formbuilder/wiki/submit) - a standard submit button
- [text](https://github.com/craftsmancoding/formbuilder/wiki/text) - the original
- [textarea](https://github.com/craftsmancoding/formbuilder/wiki/textarea) - a standard textarea
- [And more](custom) - you can define custom callbacks for your own field types

Use in Composer
---------------

[](#use-in-composer)

This has not yet been added to Packagist, so for now your composer.json file would need to reference this repository (or your own fork):

```
"require": {
    "php": ">=5.3",
    "craftsmancoding/formbuilder": "dev-master"
},
"repositories": [
    {
        "type": "vcs",
        "url":  "git@github.com:craftsmancoding/formbuilder.git"
    }
]

```

Creating Form Elements
----------------------

[](#creating-form-elements)

In the simplest invocation, you just need to call the function corresponding to an input type. Each function has its own signature; some fields require different types of data, so review the documentation for each function.

**Code:**

```

```

**Output:**

```

```

Just make sure you've included the autoloader:

```

```

That's a bit cleaner if it works for you.

### Special Arguments

[](#special-arguments)

Each type of field can be passed an array of arguments. Mostly, these will simply correspond to any placeholders in the field's formatting template, but there are several special arguments that trigger special behavior. These are:

- **label**: if present, the label will get translated and formatted using the label template
- **description**: if present, the description will get translated and formatted using the description template.
- **error**: if present, the error message will get translated and formatted with the error template.
- **value** : this gets ignored! The field value comes from either the default passed to the field (usually the 2nd argument) or via the value set via setValues();

---

Input Types
===========

[](#input-types)

Text
----

[](#text)

**Syntax:** `text(string $name, string $default='',array $args=array(),string $tpl=null)`

- `$name` *string* the name of the field (required)
- `$default` *string* the default value for the field. This will get overridden by setValues(). (optional)
- `$args` *array* any additional arguments to pass to the field. (optional)
- `$tpl` *string* formatting string.

### Examples

[](#examples)

```

```

Set a default value:

```

```

Set other parameters via the $args array:

```

```

Textarea
--------

[](#textarea)

**Syntax:** `textarea(string $name,string $default='',array $args=array(),string $tpl=null)`

Simple example:

```

```

More beefy:

```

```

Textarea fields support a placeholders for "rows" and "cols".

Checkbox
--------

[](#checkbox)

A standard checkbox will pass either a 1 or 0 value:

```

```

If you want to pass values other than 1 and 0, then pass "checked\_value" and "unchecked\_value" as arguments:

```

```

Dropdown
--------

[](#dropdown)

A dropdown implements a `` field and allows you to select a single value.

**Syntax:** `dropdown(string $name, array $options=array(), string $default='', array $args=array(), string $tpl=null)`

### Simple Options

[](#simple-options)

Simple options can be supplied via a simple array:

```

```

If you require distinct options/values, then use an associative array:

```

```

When using an associative array, the array key is what is passed as the field value and the array value is used as the option label. E.g. in the above example, print $\_POST\['mydropdown'\] would print "y" if "Yes" had been selected.

### Example: Creating a range

[](#example-creating-a-range)

Use the [range](http://www.php.net/manual/en/function.range.php) function to generate numbers for you, e.g. 1 to 100 in increments of 5:

```

```

### Example: Option Groups

[](#example-option-groups)

By supplying a nested array as your options, you can generate option groups:

```

```

File
----

[](#file)

A file input will force the form to use the post method and the "enctype" to "multipart/form-data" so that the form can be submitted and processed properly.

**Syntax:** `file(string $name, string $default='', array $args=array(), string $tpl=null)`

Radio
-----

[](#radio)

Radio fields are functionally equivalent to dropdown fields, but the formatting is more problematic because of how the formatting strings need to be stacked on top of one another.

**Syntax**: `radio($name,$options=array(),$default='',$args=array(),$tpl=null)`

Simple options:

```

```

Complex options:

```

```

Multiselect
-----------

[](#multiselect)

Similar to the **dropdown** field element, but this element allows users to select an array of options.

**Syntax:** `multiselect($name,$options=array(),$values=array(),$args=array(),$tpl=null)`

Note that the default formatting template (tpl) for multiselect fields defines an array input: `name="[+name+][]"`so you do not need to include "\[\]" as part of your $name argument.

### Simple Multiselect

[](#simple-multiselect)

```

```

### Option Groups

[](#option-groups)

Just as with the **dropdown()** fields, you can pass nested data to a multiselect field to specify option groups:

```

```

Multicheck
----------

[](#multicheck)

The multicheck field is functionally equivalent to the multiselect field, but using multiple checkboxes offers an alternate user interface for the element.

**Syntax:** `multicheck($name,$options=array(),$values=array(),$args=array(),$tpl=null)`

Note that the default formatting template (tpl) for multicheck fields defines an array input: `name="[+name+][]"`so you do not need to include "\[\]" as part of your $name argument.

See the multiselect field for examples.

Hidden
------

[](#hidden)

Same signature as a text field.

Submit
------

[](#submit)

Same signature as a text field. Don't forget to add a submit button to your form -- Formbuilder will not add it for you.

---

Creating a Form
===============

[](#creating-a-form)

Opening a Form
--------------

[](#opening-a-form)

**Syntax:** `open($action='',$args=array(),$secure=true,$tpl=null)`

This handles creating the `` tag.

Building a simple Form
----------------------

[](#building-a-simple-form)

This package was designed to useable in various circumstances, including simple and advanced development flows.

Here's an example of some simple usage:

```

```

Here's a more advanced example:

```

```

### Repopulating form values

[](#repopulating-form-values)

To populate values, use the *setValues* method. This is useful if you are editing a database record or if you are repopulating the form after failed validation. It is important to set the values **before** you create your fields.

```

```

Or sometimes you may need to do this in non-contiguous parts on a page:

```

```

The principle works the same if you want to populate a form with values from a database record, just make sure the keys/values in your array line up with the names used in your form:

```

```

---

Ad Hoc Text
-----------

[](#ad-hoc-text)

The simplest option for injecting custom text/html into your form is to use your own formatting templates.
Consider the following low-brow hack:

```

```

By overriding the default template, you effectively neuter the method of any functionality. (Don't do this, by the way: please use the **html()** method instead).

Use the **html()** method to inject random bits of HTML into a form. You may find this useful when using method-chaining.

**Syntax:** `html($str,$args=array())`

```

```

If desired, you can use placeholders in your ad-hoc HTML.

---

Registering Custom Fields
-------------------------

[](#registering-custom-fields)

Although a majority of cases can be handled via custom formatting templates, CSS classes, and custom Javascript to go along with them, the need may arise to create your own types of fields or use your own logic in determining how they are drawn and repopulated. For this task, there is the **register()** and **unregister()** functions.

### Defining your Own Field Type

[](#defining-your-own-field-type)

**Syntax:** `register(string $fieldtype, mixed $callback)`

- `$fieldtype` *string* the name of your type of field. Must be valid as a function name.
- `$callback` *mixed* any valid callback

For example, let's say your form must sign a form submission with a value obtained from an API lookup.

```

```

The signature for your callback can be whatever you want it to be: the arguments are passed in exactly as they are called. Make sure your custom function returns the output via `return Formbuilder\Form::chain()` -- this is what allows a method to be chainable.

Overriding an existing Field Type
---------------------------------

[](#overriding-an-existing-field-type)

You can use the **register()** function to override built-in behavior for any field type. For example, if you wish to use Javascript to handle your date fields you could either specify a custom formatting template for your date fields using the **setTpl()** function or by registering your own custom callback for the date field:

```

```

When overriding built-in functionality, it can be a good idea to review the function you are overriding to make sure your new functionality covers the expected use cases.

REMEMBER: most of these types of customizations can be accomplished by using custom field templates. For example, an easier way to leverage a Javascript date selector might be to set an appropriate CSS class for the date fields in question:

```

    $(function() {
        $( ".datepicker" ).datepicker();
    });
