2017 © Pedro Peláez
 

library htform

Library for building html forms without pain

image

flsouto/htform

Library for building html forms without pain

  • Sunday, June 4, 2017
  • by flsouto
  • Repository
  • 0 Watchers
  • 0 Stars
  • 7 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 3 Versions
  • 0 % Grown

The README.md

HtForm

Installation

To install this package use composer:, (*1)

composer require flsouto/htform

Overview

Forget about everything you've seen so far regarding form building tools and libraries. The approach you are going to see here is something totally new and straightforward:, (*2)

  • No need to instantiate and/or configure tons of objects.
  • No need to define and connect the form to a model.
  • No need to have xml or yml files defining how the form is supposed to behave.
  • No need to define your own form and field classes.
  • No need to setup a "renderer engine" before the form can be rendered.
  • No need to get the form builder from a DIC (Dependency Injection Container)

Usage

All you have to do is this: create a form object, add some fields and echo it:, (*3)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$form = new HtForm();
$form->textin('email');
$form->button('Submit');

echo $form;

Outputs:, (*4)




That is pretty easy, huh?, (*5)

Adding labels to fields

By default fields don't have a label but you can add one by calling the label setter on a field instance:, (*6)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$form = new HtForm();
$form->textin('email')->label('E-mail: ');
$form->button('Submit');

echo $form;

Outputs:, (*7)




Making field labels inline

By default a field's label is a block level element. You can change that by passing the inline => true flag:, (*8)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$form = new HtForm();
$form->textin('email')->label(['text'=>'E-mail:','inline'=>true]);
$form->button('Submit');

echo $form;

Outputs:, (*9)




Defining Placeholders

You can use the placeholder setter which is really just a shortcut for setting the field's 'placeholder' attribute:, (*10)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$form = new HtForm();
$form->textin('email')->placeholder('user@domain.com');
$form->button('Submit');

echo $form;

Outputs:, (*11)




Other attributes can be set by passing an associative array to the field's attrs method., (*12)

Adding different types of fields

A form is all about attaching a bunch of fields for taking user input. Different field types are available in this library:, (*13)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$form = new HtForm();

$form->textin('email')->label('Email:')->size(50)->attrs(['class'=>'email']);
$form->textar('comment')->label('Comment:')->cols(50)->rows(10);
$form->checkb('newsletter','Receive Newsletter?')->fallback(1); // checked by default
$form->hidden('key','value');
$form->select('gender')->options(['M'=>'Male','F'=>'Female'])->caption('Choose Gender: ');
$form->upload('portfolio',__DIR__)->label('Choose a pdf file')->required('Please provide a portfolio')->accept(['application/pdf']);
$form->button('Submit');
$form->button('Cancel'); // more than one button can be added

echo $form;

Outputs:, (*14)




Each field type is defined in its own class. These classes have a repostory of their own too. For more info on the fields API, take a look in the following repositories:, (*15)

  • HtField - Abstract base class for all fields, (*16)

  • HtWidget - Base class for all widget types (extends HtField), (*17)

    • HtTextin - Widget for single-line text input
    • HtTextar - Widget for multi-line text input
    • HtCheckb - Widget for boolean input (checkbox)
    • HtSelect - Widget for choosing an option from a list
    • HtUpload - Widget for uploading a file

Notice: when adding the "upload" field the form will automatically have enctype=multipart/form-data and method=POST, (*18)

Make all fields inline at once

Sometimes you need to build "quick search" type of forms in which all fields are rendered in a single line. For this you can use the inline method on the form instance:, (*19)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$form = new HtForm();
$form->inline(true);
$form->textin('fst_name')->label('First Name');
$form->textin('lst_name')->label('Last Name');
$form->button('Submit');

echo $form;

Outputs:, (*20)




Make all fields readonly at once

Sometimes you want to reuse the same form layout/structure but in readonly mode. In this case you can call the readonly method of the form object in order to disable editing on all fields:, (*21)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$form = new HtForm();
$form->readonly(true);
$form->textin('fst_name')->label('First Name');
$form->textin('lst_name')->label('Last Name');
$form->button('Submit');

echo $form;

Outputs:, (*22)




Changing Form Attributes

By default, the form is rendered with the following attributes:, (*23)

  • method: GET
  • action: ?
  • id: random id

But these can be changed easily by calling the corresponding setters on the form instance:, (*24)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$form = new HtForm();
$form->method('POST')
    ->action('some_script.php')
    ->attrs(['class'=>'some_class','id'=>'my_form']);

$form->textin('email');
$form->button('Submit');

echo $form;

Outputs:, (*25)




Populate form with data

In order to populate the form with data you have to call the context method on the form object and pass an associative array to it. The keys of the associative array must match the names of the fields you added to the form:, (*26)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$form = new HtForm();
$form->textin('name')->label('Name');
$form->textin('email')->label('Email');
$form->select('job')->caption("Job:")->options([1=>'Secretary',2=>'Manager',3=>'Programmer']);
$form->button('Submit');

$form->context([
    'name' => 'Mary',
    'email' => 'dontmaryme@doman.com',
    'job' => 1
]);

echo $form;

Outputs:, (*27)




Processing form submission

Processing a form is all about populating it with incoming data and calling the process method. It is also good practice to check if a flag is present indicating that the form has been sent. Check this out:, (*28)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

// Simulate form submition
$_REQUEST = [
    'name' => 'Mary',
    'email' => 'dontmaryme@doman.com',
    '_submit' => 1
];

$form = new HtForm();
$form->textin('name')->label('Name');
$form->textin('email')->label('Email');
$form->button('_submit','Submit');

// Populate form with data sent from request
$form->context($_REQUEST);

// Check if there is a flag
if($form->value('_submit')){

    // Extract all fields, except those prefixed with underscore
    $result = $form->process();

    print_r($result);

}

Outputs:, (*29)

FlSouto\HtFormResult Object
(
    [data] => Array
        (
            [name] => Mary
            [email] => dontmaryme@doman.com
        )

    [errors] => Array
        (
        )

)

Validate form submission

You can add validation rules to be checked upon form submission. Validation rules are added on a per-field basis and yield error messages when something is wrong. These errors are available in the result object returned by the process method. Take a look:, (*30)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

// Simulate INVALID form data
$_REQUEST = [
    'name' => '',
    'email' => 'dontmaryme__doman.com',
    '_submit' => 1
];

$form = new HtForm();
$form->textin('name')->label('Name')->required();
$form->textin('email')->label('Email')
    ->required()
    ->filters()->ifnot('@', "Invalid email address");

$form->button('_submit','Submit');

$form->context($_REQUEST);

if($form->value('_submit')){

    // Extract data and check for errors
    $result = $form->process();
    print_r($result);
}

Outputs:, (*31)

FlSouto\HtFormResult Object
(
    [data] => Array
        (
            [name] => 
            [email] => dontmaryme__doman.com
        )

    [errors] => Array
        (
            [name] => This field is required
            [email] => Invalid email address
        )

)

Namespacing form fields

The data structure behind your form doesn't have to be flat. You can group fields into logical sections, see example below:, (*32)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

// The data is sent by the form in the following structure:
$_REQUEST = [
    'user' => [ // these fields are in the "user" section
        'name' => 'Mary',
        'email' => '' // this should result in an error
    ],
    'person' => [ // these fields are in the "person" section
        'number' => 666,
        'city' => 'Nowhereland'
    ],
    '_submit' => 1 // this field is in the "root" section
];

$form = new HtForm();
// Namespacing is achieved using square brackets:
$form->textin('user[name]')->label('Username');
$form->textin('user[email]')->label('E-mail')->required("Email is required!");
$form->textin('person[number]')->label('Number');
$form->textin('person[city]')->label('City');
$form->button('_submit','Submit');

$form->context($_REQUEST);

if($form->value('_submit')){

    $result = $form->process();

    print_r($result);

}

Outputs:, (*33)

FlSouto\HtFormResult Object
(
    [data] => Array
        (
            [user[name]] => Mary
            [user[email]] => 
            [person[number]] => 666
            [person[city]] => Nowhereland
        )

    [errors] => Array
        (
            [user[email]] => Email is required!
        )

)

Unfold form data

As you may have seen in the last example, even though we can process complex data structures sent over a request, the data is extracted in a flat format. Luckily, the result object provides a method called unfold which can be used to reconstruct the data into a multidimensional array:, (*34)

<?php
require 'vendor/autoload.php';
use FlSouto\HtForm;

$_REQUEST = [
    'user' => [
        'name' => 'Mary',
        'email' => ''
    ],
    '_submit' => 1
];

$form = new HtForm();
$form->textin('user[name]')->label('Username');
$form->textin('user[email]')->label('E-mail')->required("Email is required!");
$form->button('_submit','Submit');

$form->context($_REQUEST);

if($form->value('_submit')){
    $result = $form->process()->unfold();
    print_r($result);
}

Outputs:, (*35)

FlSouto\HtFormResult Object
(
    [data] => Array
        (
            [user] => Array
                (
                    [name] => Mary
                    [email] => 
                )

        )

    [errors] => Array
        (
            [user] => Array
                (
                    [email] => Email is required!
                )

        )

)

The Versions

04/06 2017

dev-master

9999999-dev

Library for building html forms without pain

  Sources   Download

The Requires

 

by Fabio Souto

html http request forms data processing

04/06 2017

1.0.1

1.0.1.0

Library for building html forms without pain

  Sources   Download

The Requires

 

by Fabio Souto

html http request forms data processing

09/04 2017

1.0.0

1.0.0.0

Library for building html forms without pain

  Sources   Download

The Requires

 

by Fabio Souto

html http request forms data processing