PHPackages                             regulus/formation - 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. [Templating &amp; Views](/categories/templating)
4. /
5. regulus/formation

ActiveLibrary[Templating &amp; Views](/categories/templating)

regulus/formation
=================

A powerful form building and model data transforming package for Laravel 5 - 8.

v1.6.0(1y ago)356.5k6[1 PRs](https://github.com/Regulus343/Formation/pulls)1MITPHPPHP ^8.1

Since Jul 25Pushed 1y ago4 watchersCompare

[ Source](https://github.com/Regulus343/Formation)[ Packagist](https://packagist.org/packages/regulus/formation)[ RSS](/packages/regulus-formation/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (73)Used By (1)

Formation
=========

[](#formation)

**A powerful form building and model data transforming package for Laravel 11 (with supported versions since Laravel 5).**

[![Latest Stable Version](https://camo.githubusercontent.com/90d60c97e757a47778383515c646fbb4494781eea5f005f47c526b44a8676fda/68747470733a2f2f706f7365722e707567782e6f72672f726567756c75732f666f726d6174696f6e2f762f737461626c652e737667)](https://packagist.org/packages/regulus/formation) [![License](https://camo.githubusercontent.com/b285ae08b85b8a55f4efd7a060614644a61982d553b2b49835e1ddc910f91149/68747470733a2f2f706f7365722e707567782e6f72672f726567756c75732f666f726d6174696f6e2f6c6963656e73652e737667)](https://packagist.org/packages/regulus/formation)

Formation consists of two separate but complementary systems, each useable independently of each other:

1. [A powerful form builder](#form-builder) which makes it really easy to build forms with PHP form building methods that automatically:
2. [An easy-to-use data transformer base model](#data-transformer) that extends Eloquent (or optionally an `Extended` trait to use in a model that extends something else) that offers many features for transforming data, either when serving from a web server to a client, or for saving form data to your database.

- [Installation](#installation)
- [**1. Form Builder**](#form-builder)
- [Example Routes](#example-routes)
- [Opening a Form](#opening-form)
- [Default Form Values](#default-values)
- [Validation Rules](#validation-rules)
- [Labels](#labels)
- [Text, Text Area, Password &amp; Hidden Fields](#basic-fields)
- [File Input](#file-input)
- [Checkboxes and Radio Buttons](#checkbox-radio)
- [Checkbox and Radio Button Sets](#checkbox-radio-sets)
- [Drop-Down Lists](#drop-down-lists)
- [File Input](#file-input)
- [Buttons](#buttons)
- [Field Method](#field-method)
- [**2. Data Transformer Base Model &amp; Extended Trait**](#data-transformer)
- [Array-Included Methods and Attribute Sets](#array-included-methods-attribute-sets)
- [Formatting Data for Saving to a Database](#formatting-data-for-db)

> **Note:** All input data displayed within form elements are filtered through the entities method.

Installation
------------

[](#installation)

To install Formation, run `composer require regulus/formation` or add `regulus/formation` to Laravel's `composer.json` file:

```
"require": {
	"regulus/formation": "1.6.*"
},

```

Then run `php composer.phar update` from the command line. Composer will install the Formation package. Now, all you have to do is register the service provider and set up Formation's alias in `config/app.php`. Add this to the array in `bootstrap/providers.php`:

```
Regulus\Formation\FormationServiceProvider::class,

```

And add this line to `register()` in `app/Providers/AliasServiceProvider.php`:

```
$loader->alias('Form', \Regulus\Formation\Facade::class);

```

Formation is now ready to go. Now, just publish the config file, `form.php`, as well as the views and JS file if you need them, from the command line:

```
php artisan vendor:publish

```

1. Form Builder
===============

[](#1-form-builder)

A select set of features for the form builder are as follows: - populate forms with data (both default values and data provided by the POST array) - add an `error` class to labels and form fields - add IDs to form fields based on their names and add matching `for` attributes to the fields' labels - provides the ability to validate specific arrays in the POST array as well as the entire form - set up by default to use Twitter Bootstrap 4 classes for form elements but can be easily customized for other CSS frameworks - allows use of combination of PHP and JS to allow automatic creation of Handlebars JS form templates

All of this can be achieved with a minimal amount of code:

```
{!! Form::field('first_name') !!}

{!! Form::field('password') !!}

{!! Form::field('user.item', 'select', [
	'options' => prep_options(Item::all(), ['id', 'name'])
]) !!}

```

Simply echoing `Form::field('first_name')` is the same as the following code:

```

	{!! Form::label('first_name') !!}

	{!! Form::text('first_name') !!}

	{!! Form::error('first_name') !!}

```

The above code may produce the following markup:

```

	First Name

	The First Name field is required.

```

The above code is an example of how simple and versatile Formation is. The top 3 fields make use of Formation's simplified `field()` method, the middle section shows the long way to achieve the same markup as the first two text fields, and the final section shows the markup that may be produced from the above two examples (assuming a "required" form validation rule has been set for the "first\_name" field and the form has been submitted). You may notice that the markup is quite comprehensive and complete. Accesskeys are automatically employed (unless you specify otherwise) and an "access" class is applied to the accesskey letter in the label. The label, field, and possibly error are all wrapped in a div tag with a Twitter Bootstrap "form-group" class. The IDs are based on the names but use hyphens instead of underscores and the labels are automatically created from the names as well (but can, again, be specified manually). All of the fields will be automatically repopulated when form data is posted to the page. The classes for fields, labels, errors, containers, and ID / class prefixes are customizable in the config file.

```

```

With this form, we can validate just the fields in the user array with `Form::isValid('user')`, the final field with `Form::isValid('root')`, or all of the fields in the form with `Form::isValid()`.

Example Routes
--------------

[](#example-routes)

If you set `example_routes` in `config/form.php` to `true` or you leave it set to `null` and set your `APP_ENV` variable in `.env` to anything other than `production`, you can go to `/formation` to load the examples view and see Formation in action. It is recommended you review this along with the documentation to better understand what is possible with Formation and how it works.

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

[](#opening-a-form)

**Opening a form to POST to the current URL:**

```
{!! Form::open() !!}

```

**Opening a form using a given URI and request method:**

```
{!! Form::open(['url' => user/profile']) !!}

```

**Opening a form that accepts file uploads:**

```
{!! Form::openForFiles(['url' => 'user/profile', 'files' => true]) !!}

```

**Opening a form for a resource controller:**

```
{!! Form::openResource() !!}

```

> **Note:** This method automatically creates the correct route for the form action, assuming a resource controller is being used.

**Closing a form:**

```
{!! Form::close() !!}

```

Default Form Values
-------------------

[](#default-form-values)

One of the most useful features of Formation is its ability to take an array, object, or Eloquent model and use it to populate form fields automatically. When the form is posted, it will automatically make use of the values in the POST array instead.

```
$defaults = [
	'name'   => 'Ron Paul',
	'email'  => 'ron@paul.com',
	'active' => true,
];

Form::setDefaults($defaults);
```

> **Note:** If you want to use array fields names instead, use, for example, `user.name` and `user.email` instead of `name` and `email`.

**Forcing default values even after form POST:**

```
Form::resetDefaults();

```

**Set defaults with relationships:**

```
$user = User::find(1);

Form::setDefaults($user, ['posts']);
```

This will automatically set the defaults for the user's `posts` relationship defined in the model.

**Set defaults with relationships based on specific attribute:**

```
$user = User::find(1);

Form::setDefaults($user, [
	'posts' => '*',
	'roles' => 'id',
]);
```

The `posts` item will work just like the above example (though this is the associative array version of the same thing) whereas the `roles` item will select only the `id` attributes in the relations to add to the defaults array. This could be used by a checkbox set with a `roles.` name prefix for managing record selections in a `belongsToMany()` relationship. There is an example in the [Checkbox and Radio Button Sets](#checkbox-radio-sets) section below.

Validation Rules
----------------

[](#validation-rules)

Formation makes use Laravel's Validator class. Using `Form::setValidation()` will create an instance of the Validator class (or many instances if array field names are used in the form setup). The reason the form's validation rules are passed through Formation to Validator is because Formation automatically adds an "error" class to the label and form field if an error is triggered. To do this, Formation needs a copy of the validation rules that have been set.

```
$rules = [
	'user.name' => ['required'], // 'user.name' can be used for an array field like "user[name]"
	'email'     => ['required', 'email']
];

Form::setValidationRules($rules);
```

**Validating all fields:**

```
if (Form::isValid())
{
	return true;
}
```

**Validating fields in an array:**

```
if (Form::isValid('user')) // validates array fields with names like "user[name]" and "user[email]"
{
	return true;
}

if (Form::isValid('user.')) // ending with a "." allows us to validate fields like "user[0][name]" and "user[1][name]"
{
	return true;
}
```

The last example can be used when you have many instances of an array field like `user` above. That example will validate all sub fields of `Input::get('user')`. Ending your name with a period lets Formation know that `user` is an array that may contain many sets of the same sub fields.

Labels
------

[](#labels)

**Setting up labels with an array:**

```
$labels = [
	'name'  =>  'Name',
	'email' => 'Email Address',
];

Form::setLabels($labels);
```

By setting up your labels with an array, you will be able to leave the second argument `null` in `Form::label()`.

**Generating a label element:**

```
{!! Form::label('email', 'Email Address') !!}

```

If you do not pass a label for the second argument, it will be checked for in Formation's `$labels` array that can be set with `Form::setLabels()`. If it is not found here, it will be inferred from the field name in the first argument.

**Specifying extra HTML attributes for a label:**

```
{!! Form::label('email', 'Email Address', ['class' => 'email']) !!}

```

> **Note:** After creating a label, any form element you create with a name matching the label name will automatically receive an ID matching the label name as well.

Text, Text Area, Password &amp; Hidden Fields
---------------------------------------------

[](#text-text-area-password--hidden-fields)

**Generate a text input element:**

```
{!! Form::text('username') !!}

```

**Specifying a default value for a text input element:**

```
{!! Form::text('email', ['value' => 'example@gmail.com']) !!}

```

**Setting attributes for a text field:**

```
{!! Form::text('user.first_name', ['class' => 'short']) !!}

```

By using `Form::setDefaults()`, you will not need to pass a default value and can instead pass a `null` value or none at all as the second argument to let the field take advantage of the preset default value. When a form is posted, the values in the POST array will be used instead unless `Form::resetDefaults()` is used.

> **Note:** A field with a name attribute of `first_name` is automatically given an ID of `first-name`. Underscores in names are always replaced with dashes in IDs.

**Naming a text field with an unspecified array index while retaining a unique ID:**

```
{!! Form::text('user.(0).username') !!}

```

The above example will create a text field with a name of `user[][username]` and an ID of `user-0-username`. If you wish to explicitly specify the index for the name, simply leave out the round brackets:

```
{!! Form::text('user.0.username') !!}

```

**Generating a password input element:**

```
{!! Form::password('password') !!}

```

Checkboxes and Radio Buttons
----------------------------

[](#checkboxes-and-radio-buttons)

**Generating a checkbox input element:**

```
{!! Form::checkbox('name', ['value' => 'X']) !!}

```

**Generating a checkbox input element with a label:**

```
{!! Form::checkbox('name', ['label' => true]) !!}

{!! Form::checkbox('name', ['label' => 'Custom Label']) !!}

{!! Form::checkbox('name', ['label' => 'Custom Label', 'label-first' => true]) !!}

```

**Generating a checkbox that is checked by default:**

```
{!! Form::checkbox('name', ['checked' => true]) !!}

```

Please keep in mind that once again you will not need the second parameter to set the value if you set up your default values with `Form::setDefaults()`.

> **Note:** The radio method has the same signature as the checkbox method. Two for one!

Checkbox and Radio Button Sets
------------------------------

[](#checkbox-and-radio-button-sets)

**Creating a set of checkboxes:**

```
