PHPackages                             simplon/form - 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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. simplon/form

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

simplon/form
============

Data validation &amp; flexible form rendering incl. semantic-ui structure.

2.5.1(8y ago)46.6k23MITPHPPHP &gt;=7.1

Since Sep 26Pushed 7y ago1 watchersCompare

[ Source](https://github.com/fightbulc/simplon_form)[ Packagist](https://packagist.org/packages/simplon/form)[ Docs](https://github.com/fightbulc/simplon_form)[ RSS](/packages/simplon-form/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (5)Versions (119)Used By (3)

```
     _                 _                __
 ___(_)_ __ ___  _ __ | | ___  _ __    / _| ___  _ __ _ __ ___
/ __| | '_ ` _ \| '_ \| |/ _ \| '_ \  | |_ / _ \| '__| '_ ` _ \
\__ \ | | | | | | |_) | | (_) | | | | |  _| (_) | |  | | | | | |
|___/_|_| |_| |_| .__/|_|\___/|_| |_| |_|  \___/|_|  |_| |_| |_|
                |_|

```

Simplon/Forms
=============

[](#simplonforms)

`Simplon/Forms` helps to validate data and, if needed, to build a form view with a couple of widgets by leveraging `Semantic-UI` library.

---

1. [**Quick example**](#1-quick-example)
    1.1 [Fields](#11-fields)
    1.2 [Validation](#12-validation)
    1.3 [View](#13-view)
2. [**Fields**](#2-fields)
    2.1 [General fields](#21-general-fields)
    2.2 [Fields with options](#22-fields-with-options)
    2.3 [Rules](#23-rules)
    2.4 [Filters](#24-filters)
3. [**View**](#3-view)
    3.1 [Simple example](#31-simple-example)
    3.2 [Blocks &amp; Rows](#32-blocks--rows)
    3.3 [Elements](#33-elements)
4. [**Block fields cloning**](#4-block-fields-cloning)
    4.1 [Building fields](#41-building-fields)
    4.2 [Building view](#41-building-view)
    4.3 [Building templates](#41-building-templates)
5. [**Settings**](#5-settings)
    5.1 [Field required/optinal label](#51-field-requiredoptional-label)
6. [**Examples**](#6-examples)

---

1. Quick example
================

[](#1-quick-example)

1.1 Fields
----------

[](#11-fields)

In order to validate data we need to create at least one field which can hold any number of rules to define its validity. A field can also hold any number of filters which will be applied to the field value.

### Some field examples

[](#some-field-examples)

```
//
// easiest setup
//

(new FormFields())->add(
	new FormField('email')
);

//
// another way with a filter
//

(new FormFields())->add(
	(new FormField('email'))->addFilter(new CaseLowerFilter()) // lower case field value
);

//
// fields can also have rules
//

(new FormFields())->add(
	(new FormField('email')->addRule(new EmailRule()) // make sure that we get an email address
);

//
// we can also combine these things
//

(new FormFields())->add(
	(new FormField('email')
		->addRule(new EmailRule())
		->addFilter(new CaseLowerFilter())
);
```

### Pre-populating your fields

[](#pre-populating-your-fields)

We can pre-poluate our fields with data we already have - not `request` data:

```
//
// our fields
//

$fields = (new FormFields())->add(
	(new FormField('email'))->addRule(new EmailRule())
);

//
// set our data
//

$fields->applyInitialData(
	['email' => 'foo@bar.com']
);

//
// testing ...
//

$fields->get('email')->getInitialValue(); // foo@bar.com
$fields->get('email')->getValue(); // foo@bar.com

//
// these values change if we enter for instance
// "hello@bar.com" in our form and hit submit ...
//

$fields->get('email')->getInitialValue(); // foo@bar.com
$fields->get('email')->getValue(); // hello@bar.com
```

1.2 Validation
--------------

[](#12-validation)

`FormValidation` is expecting at least one set of `FormFields`. Let's pick up the example from above with an additional `name` field. We set an empty array for our `request data`. You can take the value from any source as long as its organised as an array.

```
//
// request data
//

$requestData = [
	'name' => 'Johnny',
	'email' => '',
];

//
// define fields
//

$fields = new FormFields();

$fields->add(
	new FormField('name')
);

$fields->add(
	(new FormField('email'))->addRule(new EmailRule())
);

//
// validation
//

$validator = new FormValidator($requestData);

if($validator->hasBeenSubmitted()) // any request data?
{
    if($validator->validate()->isValid())
    {
	    // all validated field data as array
    	var_dump($fields->getAllData());
    }
    else
    {
	    // array of error messages
    	var_dump($validator->getErrorMessages());

		// OR ...

    	// array of error fields
    	var_dump($validator->getErrorFields());
    }
}
```

`FormValidator::hasBeenSubmitted` checks if our received data are empty or filled. In case we received data we can go ahead and run all applied rules over our defined fields by `FormValidator::validate` and `FormValidator::isValid` tells us if all fields passed their requirements.

In case of success we can collect all field values by `FormFields::getAllData`. Otherwise you can check for errors by collecting the error messages via `FormValidator::getErrorMessages` or by collecting all error fields `FormValidator::getErrorFields`. The latter also holds all error messages by field.

1.3 View
--------

[](#13-view)

In order to render your fields we need to apply them to `Elements`. These elements can be applied to the `FormView` directly or to a `FormBlock` which renders our form automatically in a set structure. We will continue with our before defined fields:

```
//
// define fields
//

$nameElement = (new InputTextElement($fields->get('name')))
	->setLabel('Email address')
	->setDescription('Required in order to send you a confirmation');

$emailElement = (new InputTextElement($fields->get('email')))
	->setLabel('Email address')
	->setDescription('Required in order to send you a confirmation');

//
// apply to a block w/ one row
//

$block = (new FormViewBlock('default')) // set block ID to default
    ->addRow(
	    (new FormViewRow())
	    	->autoColumns($nameElement)
	    	->autoColumns($emailElement)
    )
;

//
// set view
//

$formView = (new FormView())->addBlock($block);
```

We could set much more options but that should do it for now. Let's pass on our view to a template. For the following example we assume that we have access to the `$formView` variable. We simply pass on a form template to the `FormView::render` method and include all `core assets`:

```

    simplon/form

        body {
            padding: 0;
            background: #fff;
        }
