PHP code example of tobento / service-form

1. Go to this page and download the library: Download tobento/service-form library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tobento / service-form example snippets


use Tobento\Service\Form\Form;
use Tobento\Service\Form\InputInterface;
use Tobento\Service\Form\TokenizerInterface;
use Tobento\Service\Form\ActiveElementsInterface;
use Tobento\Service\Message\MessagesInterface;

$form = new Form(
    input: null, // null|InputInterface
    tokenizer: null, // null|TokenizerInterface
    activeElements: null, // null|ActiveElementsInterface
    messages: null // null|MessagesInterface
);

use Tobento\Service\Form\FormFactoryInterface;
use Tobento\Service\Form\ResponserFormFactory;
use Tobento\Service\Form\ActiveElementsInterface;
use Tobento\Service\Form\Form;
use Tobento\Service\Responser\ResponserInterface;

$formFactory = new ResponserFormFactory(
    responser: $responser, // ResponserInterface
    tokenizer: null, // null|TokenizerInterface
    activeElements: null, // null|ActiveElementsInterface
);

var_dump($formFactory instanceof FormFactoryInterface);
// bool(true)


$form = $formFactory->createForm();

var_dump($form instanceof Form);
// bool(true)

<?= $form->form() 

<?= $form->form(attributes: ['method' => 'GET']) 

<?= $form->input(
    name: 'name',
    type: 'text',
    value: 'value',
    attributes: [],
    selected: null,
    withInput: true,
) 

<?= $form->input(
    name: 'colors[]',
    type: 'checkbox',
    value: 'red',
    attributes: ['id' => 'colors_red'],
    selected: ['red'], // or 'red'
) 

<?= $form->checkboxes(
    name: 'colors',
    items: ['red' => 'Red', 'blue' => 'Blue'],
    selected: ['blue'],
    attributes: [],
    labelAttributes: [],
    withInput: true,
    wrapClass: 'form-wrap-checkbox'
) 

$items = ['red' => 'Red', 'blue' => 'Blue'];

<?= $form->checkboxes(
    name: 'colors',
    items: $form->each(items: $items, callback: function($item, $key): array {
        // value:string, label:string|null, array-key:string|null
        return [$key, strtoupper($item), $key];
    }),
    selected: ['blue'],
) 

<?= $form->input(
    name: 'colors',
    type: 'radio',
    value: 'red',
    attributes: ['id' => 'colors_red'],
    selected: 'red',
) 

<?= $form->radios(
    name: 'colors',
    items: ['red' => 'Red', 'blue' => 'Blue'],
    selected: 'blue',
    attributes: [],
    labelAttributes: [],
    withInput: true,
    wrapClass: 'form-wrap-radio'
) 

$items = ['red' => 'Red', 'blue' => 'Blue'];

<?= $form->radios(
    name: 'colors',
    items: $form->each(items: $items, callback: function($item, $key): array {
        // value:string, label:string|null
        return [$key, strtoupper($item)];
    }),
    selected: 'blue',
) 

<?= $form->label(
    text: 'Text',
    for: 'colors',
    attributes: [],
    

<?= $form->label(
    text: 'Text',
    

<?= $form->label(
    text: 'Text',
    optionalText: 'optional',
) 

<?= $form->select(
    name: 'colors[]',
    items: ['red' => 'Red', 'blue' => 'Blue'],
    selected: ['blue'],
    selectAttributes: ['multiple'],
    optionAttributes: [],
    optgroupAttributes: [],
    emptyOption: null,
    withInput: true,
) 

<?= $form->select(
    name: 'roles',
    items: [
        'Frontend' => [
            'guest' => 'Guest',
            'registered' => 'Registered',
        ],
        'Backend' => [
            'editor' => 'Editor',
            'administrator' => 'Aministrator',
        ],        
    ],
) 

$items = ['red' => 'Red', 'blue' => 'Blue'];

<?= $form->select(
    name: 'colors',
    items: $form->each(items: $items, callback: function($item, $key): array {
        // value:string, label:string|null
        return [$key, strtoupper($item)];
    }),
    selected: 'blue',
) 

<?= $form->select(
    name: 'colors',
    items: ['red' => 'Red', 'blue' => 'Blue'],
    emptyOption: ['none', '---'],
) 

<?= $form->textarea(
    name: 'description',
    value: 'Lorem ipsum',
    attributes: [],
    withInput: true,
) 

<?= $form->button(
    text: 'Submit Text',
    attributes: [],
    escText: true,
) 

<?= $form->fieldset(
    legend: 'Legend',
    attributes: [],
    legendAttributes: [],
) 

<?= $form->datalist(
    name: 'colors',
    items: ['red', 'blue'],
    attributes: [],
) 

$items = ['red' => 'Red', 'blue' => 'Blue'];

<?= $form->datalist(
    name: 'colors',
    items: $form->each(items: $items, callback: function($item, $key): array {
        // value:string
        return [strtoupper($item)];
    })
) 

<?= $form->option(
    value: 'red',
    text: 'Red',
    attributes: [],
    selected: ['red'], // or 'red'
) 

use Tobento\Service\Form\InputInterface;
use Tobento\Service\Form\Input;

$input = new Input(array_merge(
    $_GET ?? [],
    $_POST ?? [],
));

var_dump($input instanceof InputInterface);
// bool(true)

use Tobento\Service\Form\Form;
use Tobento\Service\Form\Input;

$form = new Form(
    input: new Input(['color' => 'red']),
);

$value = $form->getInput(
    name: 'color',
    default: 'blue',
    withInput: true, // default
);

var_dump($value);
// string(3) "red"

$value = $form->getInput(
    name: 'color',
    default: 'blue',
    withInput: false,
);

var_dump($value);
// string(4) "blue"

use Tobento\Service\Form\Form;
use Tobento\Service\Form\Input;

$form = new Form(
    input: new Input(['color' => 'red']),
);

var_dump($form->hasInput('color'));
// bool(true)

use Tobento\Service\Form\Form;
use Tobento\Service\Form\Input;
use Tobento\Service\Form\InputInterface;

$form = new Form(
    input: new Input(['color' => 'red']),
);

$form = $form->withInput(
    input: null, // null|InputInterface
);

use Tobento\Service\Form\TokenizerInterface;
use Tobento\Service\Form\SessionTokenizer;
use Tobento\Service\Session\SessionInterface;
use Tobento\Service\Session\Session;

$session = new Session(name: 'sess');

$tokenizer = new SessionTokenizer(
    session: $session, // SessionInterface
    tokenName: 'csrf', // default
    tokenInputName: '_token' // default
);

var_dump($tokenizer instanceof TokenizerInterface);
// bool(true)

$tokenizer->setTokenName('csrf');

var_dump($tokenizer->getTokenName());
// string(4) "csrf"

$tokenizer->setTokenInputName('_token');

var_dump($tokenizer->getTokenInputName());
// string(6) "_token"

var_dump($tokenizer->get('csrf'));
// Null or string

var_dump($tokenizer->generate('csrf'));
// string(40) "token-string..."

$tokenizer->delete('csrf');

$isValid = $tokenizer->verifyToken(
    inputToken: 'input token string', // string
    name: 'csrf', // null|string The name of the token to verify.
);

// or set a token.
$isValid = $tokenizer->verifyToken(
    inputToken: 'input token string', // string
    token: 'token string' // null|string
);

use Tobento\Service\Form\Middleware\VerifyCsrfToken;
use Tobento\Service\Form\InvalidTokenException;

$middleware = new VerifyCsrfToken(
    tokenizer: $tokenizer, // TokenizerInterface
    name: 'csrf', // default
    inputName: '_token', // default
    headerTokenName: 'X-Csrf-Token', // default. Null if not to use at all.
    onetimeToken: false, // default
);

$request = $request->withAttribute(
    VerifyCsrfToken::EXCLUDE_URIS_KEY,
    [
        'http://example.com/foo/bar',
    ]
);

use Tobento\Service\Form\Form;
use Tobento\Service\Form\TokenizerInterface;

$form = new Form(
    tokenizer: $tokenizer,
);

var_dump($form->tokenizer() instanceof TokenizerInterface);
// bool(true)

use Tobento\Service\Form\Form;

$form = new Form(
    tokenizer: $tokenizer,
);

var_dump($form->generateToken());
// string(40) "token string..."

use Tobento\Service\Form\Form;

$form = new Form(
    tokenizer: $tokenizer,
);

echo $form->generateTokenInput();
// <input name="_token" type="hidden" value="token string...">

use Tobento\Service\Message\MessagesInterface;
use Tobento\Service\Message\Messages;

$messages = new Messages();

var_dump($messages instanceof MessagesInterface);
// bool(true)

use Tobento\Service\Form\Form;
use Tobento\Service\Message\MessagesInterface;

$form = new Form();

var_dump($form->messages() instanceof MessagesInterface);
// bool(true)

use Tobento\Service\Form\Form;
use Tobento\Service\Message\MessagesInterface;

$form = new Form();

$form = $form->withMessages(
    input: null, // null|MessagesInterface
);

use Tobento\Service\Form\Form;

$form = new Form();

var_dump($form->getMessage('key'));
// string(0) ""

use Tobento\Service\Form\Form;

$form = new Form();

var_dump($form->getRenderedMessageKeys());
// array(0) { }

use Tobento\Service\Form\Form;

$form = new Form();

$form->messages()->add(
    level: 'error',
    message: 'Please accept our terms.',
    key: 'terms',
);

<?= $form->input('terms', 'checkbox', 'terms') 

<?= $form->form() 

<?= $form->form(['method' => 'PUT']) 

use Tobento\Service\Form\Form;
use Tobento\Service\Form\ActiveElements;
use Tobento\Service\Form\ActiveElementsInterface;

$form = new Form(
    activeElements: new ActiveElements(),
);

var_dump($form->getActiveElements() instanceof ActiveElementsInterface);
// bool(true)

use Tobento\Service\Form\Form;

$form = new Form();

$isActive = $form->isActive(
    name: 'colors',
    value: 'red', // the value to be active.
    default: null,
);

use Tobento\Service\Form\Form;

$form = new Form();

var_dump($form->nameToArray('user.firstname'));
// string(15) "user[firstname]"

use Tobento\Service\Form\Form;

$form = new Form();

var_dump($form->nameToNotation('user[firstname]'));
// string(14) "user.firstname"

use Tobento\Service\Form\Form;

$form = new Form();

var_dump($form->nameToId('user[firstname]'));
// string(14) "user_firstname"

use Tobento\Service\Form\Form;

$form = new Form();

var_dump($form->hasArrayNotation('user.firstname'));
// bool(true)

<?= $form->input(
    name: 'name',
    type: 'text',
    attributes: [
        'd is 

<?= $form->input(
    name: 'name',
    type: 'text',
    attributes: [
        'pattern' => '[a-zA-Z]+',
        'data-validation-messages' => [
            'pattern' => 'The name must only contain letters [a-zA-Z].',
        ],
    ]
) 

<?= $form->input(
    name: 'name',
    type: 'number',
    attributes: [
        'min' => '0',
        'max' => '100',
        'step' => '10',
        'data-validation-messages' => [
            'min' => 'The name must be at least 1.',
            'max' => 'The name must be at most 100.',
            'step' => 'The name must be in steps of 10.',
        ],
    ]
) 

<?= $form->input(
    name: 'name',
    type: 'text',
    attributes: [
        'minlength' => '5',
        'maxlength' => '10',
        'data-validation-messages' => [
            'minlength' => 'The name must be at least 5 letters long.',
            'maxlength' => 'The name must be at most 10 letters long.',
        ],
    ]
) 

<?= $form->input(
    name: 'email',
    type: 'email',
    attributes: [
        'minlength' => '5',
        'maxlength' => '10',
        'data-validation-messages' => [
            'mismatch' => 'Please enter a valid email address.'
        ],
    ]
)