• Stars
    star
    152
  • Rank 244,685 (Top 5 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 12 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP library to create and validate html forms

FormManager

Build Status Scrutinizer Code Quality

Note: this is the documentation of FormManager 6.x

For v5.x version Click here

Installation:

This package requires PHP>=7.1 and is available on Packagist:

composer require form-manager/form-manager

Create a field

FormManager is namespaced, but you only need to import a single class into your context:

use FormManager\Factory as F;

Use the imported factory to create all form elements:

//Create an input type="text" element
$name = F::text();

//Create the input with a label
$name = F::text('Please, introduce your name');

//Or with extra attributes
$name = F::text('Please, introduce your name', ['class' => 'name-field']);

//Add or remove attributes
$name->setAttribute('title', 'This is the name input');
$name->removeAttribute('class');
$name->setAttributes([
    'required',
    'readonly',
    'tabindex' => 2,
    'maxlength' => 50
]);

//Set the value
$name->setValue('MyName');

//Use magic properties to get/set/remove attributes
$name->class = 'name-field';
$name->required = false;
unset($name->readonly);

List of all available inputs:

All HTML5 field types are supported:

  • F::checkbox($label, $attributes)
  • F::color($label, $attributes)
  • F::date($label, $attributes)
  • F::datetimeLocal($label, $attributes)
  • F::email($label, $attributes)
  • F::file($label, $attributes)
  • F::hidden($value, $attributes)
  • F::month($label, $attributes)
  • F::number($label, $attributes)
  • F::password($label, $attributes)
  • F::radio($label, $attributes)
  • F::range($label, $attributes)
  • F::search($label, $attributes)
  • F::select($label, $options, $attributes)
  • F::submit($label, $attributes)
  • F::tel($label, $attributes)
  • F::text($label, $attributes)
  • F::textarea($label, $attributes)
  • F::time($label, $attributes)
  • F::url($label, $attributes)
  • F::week($label, $attributes)

Note that all inputs accepts the same arguments except hidden and select.

Validation

This library uses internally symfony/validation to perform basic html5 validations and error reporting. HTML5 validation attributes like required, maxlength, minlength, pattern, etc are supported, in addition to intrinsic validations assigned to each input like email, url, date, etc.

$email = F::email();

$email->setValue('invalid-email');

//Validate the value
if ($email->isValid()) {
    return true;
}

//Get errors
$error = $email->getError();

//Print the first error message
echo $error;

//Iterate through all messages
foreach ($error as $err) {
    echo $err->getMessage();
}

//You can also customize/translate the error messages
$email->setErrorMessages([
    'email' => 'The email is not valid',
    'required' => 'The email is required',
    'maxlength' => 'The email is too long, it must have {{ limit }} characters or less',
]);

//And add more symfony validators
$ip = F::text();
$ip->addConstraint(new Constraints\Ip());

See all constraints supported by symfony

Render html

$name = F::text('What is your name?', ['name' => 'name']);

echo $name;
<label for="id-input-1">What is your name?</label> <input id="id-input-1" type="text" name="name">

Set a custom template using {{ label }} and {{ input }} placeholders:

$name->setTemplate('{{ label }} <div class="input-content">{{ input }}</div>');
echo $name;
<label for="id-input-1">What is your name?</label> <div class="input-content"><input id="id-input-1" type="text" name="name"></div>

If you want to wrap the previous template in a custom html, use the {{ template }} placeholder:

$name->setTemplate('<fieldset>{{ template }}</fieldset>');
echo $name;
<fieldset><label for="id-input-1">What is your name?</label> <div class="input-content"><input id="id-input-1" type="text" name="name"></div></fieldset>

Grouping fields

Group the fields to follow a specific data structure:

Group

Groups allow to place a set of inputs under an specific name:

$group = F::group([
    'name' => F::text('Username'),
    'email' => F::email('Email'),
    'password' => F::password('Password'),
]);

$group->setValue([
    'name' => 'oscar',
    'email' => '[email protected]',
    'password' => 'supersecret',
]);

Radio group

Special case for radios where all inputs share the same name with different values:

$radios = F::radioGroup([
    'red' => 'Red',
    'blue' => 'Blue',
    'green' => 'Green',
]);

$radios->setValue('blue');

Submit group

Special case to group several submit buttons under the same name but different values:

$buttons = F::submitGroup([
    'save' => 'Save the row',
    'duplicate' => 'Save as new row',
]);

$buttons->setName('action');

Group collection

Is a collection of values using the same group:

$groupCollection = F::groupCollection(
    f::group([
        'name' => F::text('Name'),
        'genre' => F::radioGroup([
            'm' => 'Male',
            'f' => 'Female',
            'o' => 'Other',
        ]),
    ])
]);

$groupCollection->setValue([
    [
        'name' => 'Oscar',
        'genre' => 'm'
    ],[
        'name' => 'Laura',
        'genre' => 'f'
    ],
])

Multiple group collection

Is a collection of values using various groups, using the field type to identify which group is used by each row:

$multipleGroupCollection = F::multipleGroupCollection(
    'text' => f::group([
        'type' => F::hidden(),
        'title' => F::text('Title'),
        'text' => F::textarea('Body'),
    ]),
    'image' => f::group([
        'type' => F::hidden(),
        'file' => F::file('Image file'),
        'alt' => F::text('Alt text'),
        'text' => F::textarea('Caption'),
    ]),
    'link' => f::group([
        'type' => F::hidden(),
        'text' => F::text('Link text'),
        'href' => F::url('Url'),
        'target' => F::select([
            '_blank' => 'New window',
            '_self' => 'The same window',
        ]),
    ]),
]);

$multipleGroupCollection->setValue([
    [
        'type' => 'text',
        'title' => 'Welcome to my page',
        'text' => 'I hope you like it',
    ],[
        'type' => 'image',
        'file' => 'avatar.jpg',
        'alt' => 'Image of mine',
        'text' => 'This is my photo',
    ],[
        'type' => 'link',
        'text' => 'Go to my webpage',
        'href' => 'https://oscarotero.com',
        'target' => '_self',
    ],
]);

Datalist

Datalist are also allowed, just use the createDatalist() method:

$input = F::search();

$datalist = $input->createDatalist([
    'female' => 'Female',
    'male' => 'Male'
]);

echo $input;
echo $datalist;

Forms

We need a form to put all this things together.

$loginForm = F::form([
    'username' => F::text('User name'),
    'password' => F::password('Password'),
    '' => F::submit('Login'),
]);

$loginForm->setAttributes([
    'action' => 'login.php',
    'method' => 'post',
]);

//Load data from globals $_GET, $_POST, $_FILES
$loginForm->loadFromGlobals();

//Load data passing the arrays
$loginForm->loadFromArrays($_GET, $_POST, $_FILES);

//Or load from PSR-7 server request
$loginForm->loadFromServerRequest($serverRequest);

//Get loaded data
$data = $loginForm->getValue();

//Print the form
echo $loginForm;

//Access to specific inputs:
echo $loginForm->getOpeningTag();
echo '<h2>Login:</h2>';

echo $loginForm['username'];
echo '<hr>';
echo $loginForm['password'];
echo '<hr>';
echo $loginForm[''];
echo $loginForm->getClosingTag();

//Iterate with all inputs
echo $loginForm->getOpeningTag();
echo '<h2>Login:</h2>';

foreach ($loginForm as $input) {
    echo "<div>{$input}</div>";
}
echo $loginForm->getClosingTag();

More Repositories

1

Embed

Get info from any web service or page
PHP
2,045
star
2

psr7-middlewares

[DEPRECATED] Collection of PSR-7 middlewares
PHP
672
star
3

node-sketch

💎 Javascript library to manipulate sketch files
JavaScript
306
star
4

imagecow

PHP library to manipulate and generate responsive images
PHP
240
star
5

simple-crud

PHP library to provide magic CRUD in MySQL/Sqlite databases with zero configuration
PHP
237
star
6

jquery-cheatsheet

jQuery interactive cheatsheet
CSS
137
star
7

awesome-design

A collection of open resources for web designers
97
star
8

social-links

Simple library to count shares and generate share buttons
PHP
95
star
9

env

Simple library to read environment variables and convert to simple types.
PHP
81
star
10

bookmarklets

Simple framework to build bookmarklets easily
JavaScript
68
star
11

keep-a-changelog

Node & Deno package to parse and generate changelogs
TypeScript
56
star
12

deno-cheatsheet

Deno cheat sheet with APIs and tools
CSS
53
star
13

stylecow

[deprecated] CSS preprocessor written in PHP
PHP
46
star
14

vento

🌬 A template engine for Deno & Node
TypeScript
44
star
15

middleland

Simple PSR-15 middleware dispatcher
PHP
34
star
16

jQuery.media

jQuery based library to manage video and audio html5 elements
JavaScript
30
star
17

php-server-manager

Manage PHP built-in server in node
JavaScript
28
star
18

semantic-html

Collection of semantic HTML use cases
23
star
19

inline-svg

Insert svg in the html so you can use css to change the style
PHP
19
star
20

css-style-guide

My own css style guide
HTML
15
star
21

nginx-snippets

Custom snippets for nginx
14
star
22

html-parser

Simple utility to parse html strings to DOMDocument
HTML
13
star
23

fly-crud

Basic crud system built on top of flysystem
PHP
12
star
24

nodedeno

Script to convert Node libraries to Deno
JavaScript
11
star
25

folk

Universal CMS to use with any web
PHP
10
star
26

html

PHP library to generate HTML code
PHP
9
star
27

gpm

Git-based package manager for Deno
TypeScript
9
star
28

uploader

Basic php library to upload files
PHP
7
star
29

d.js

DOM manipulation micro library (~4Kb)
JavaScript
7
star
30

dbin

Library to download binary files from GitHub releases detecting the correct platform.
TypeScript
7
star
31

typofixer

Fix microtypography issues in html code
PHP
7
star
32

server

Simple class to emulate Apache's "mod_rewrite" functionality from the built-in PHP web server
PHP
5
star
33

psr7-unitesting

Test your psr-7 http messages easily
PHP
5
star
34

server-style-guide

Step-by-step instructions to install and configure a web server
CSS
5
star
35

polyfills

List of polyfills to use modern things safely
4
star
36

awesome-talks

Collection of design talks in galician and spanish
4
star
37

zume

A static-site generator built on top of gulp.
JavaScript
4
star
38

memes-da-vida

Xerador de memes con debuxos de Castelao
HTML
3
star
39

vscode-vento

Vento for Visual Studio Code
3
star
40

fol

Base app to build websites
PHP
3
star
41

ha

Código público de historia-arte.com
PHP
3
star
42

gist-runner

Simple script to run github gist files in localhost
JavaScript
3
star
43

jose

Feed reader
PHP
3
star
44

history-navigator

Minimalist js library to navigate across the browser history
JavaScript
3
star
45

jquery.lazyscript

Simple jquery plugin to load or transform elements in lazy mode
HTML
3
star
46

view-helpers

Collection of useful functions to use in your templates
PHP
2
star
47

form-manager-bootstrap

Simple FormManager extension to create bootstrap-like forms
PHP
2
star
48

simple-crud-extra-fields

Extra fields for simple-crud package
PHP
2
star
49

php-cs-fixer-config

My own custom php-cs-fixer config
PHP
2
star
50

matomo-tracker

Generate Matomo tracker urls that you can use to insert tracking images in your site
PHP
2
star
51

netlify_cms_config

Netlify CMS config generator
TypeScript
1
star
52

chipi-client

JavaScript
1
star
53

domplates

Easy HTML <template>
JavaScript
1
star
54

how-to-do-it

cli utility to help me to remember other cli commands
JavaScript
1
star
55

icona

1 svg + 1 css = multiple icons
CSS
1
star
56

designtokens

A Deno/Node library to parse, manipulate and transform design tokens
TypeScript
1
star