PHP code example of monolyth / formulaic

1. Go to this page and download the library: Download monolyth/formulaic 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/ */

    

monolyth / formulaic example snippets




use Monolyth\Formulaic\Get;
use Monolyth\Formulaic\Search;
use Monolyth\Formulaic\Button\Submit;

class MyForm extends Get
{
    public function __construct()
    {
        $this[] = (new Search('q'))->isRequired();
        $this[] = new Submit('Go!', 'submit');
    }
}



$form = new MyForm;
echo $form;



$form = new MyForm;




$form = new MyForm;
if ($form->valid()) {
    // ...Perform the search...
}



$form = new MyForm;
if ($errors = $form->errors()) {
    // ...Do error handling, or give feedback...
}



use Monolyth\Formulaic\Get;
use Monolyth\Formulaic\Fieldset;
use Monolyth\Formulaic\Search;
use Monolyth\Formulaic\Button\Submit;

class MyForm extends Get
{
    public function __construct()
    {
        $this[] = new Fieldset('Global search', function($fieldset) {
            $fieldset[] = new Search('q');
        });
        $this[] = new Fieldset('Search by ID', function($fieldset) {
            $fieldset[] = new Search('id');
        });
        $this[] = new Submit('Go!');
    }
}

<form method="get">
    <?=$form['Global search']



// ...
class Form extends Get
{
    public function __construct()
    {
        $this[] = new Radio('foo');
        $this[] = '<h1>custom HTML element!</h1>';
    }
}



use Monolyth\Formulaic\{ Get, Element\Group, Text };

class Form extends Get
{
    public function __construct()
    {
        $this[] = new Group('foo', function ($group) {
            $group[] = new Text('bar');
        });
    }
}



$input = new Text('foo');
$input->addTest(fn ($value) => $value == 'bar');



class MyFrom extends Post
{
    //... define the form
    public function __construct()
    {
        $this[] = new Text('foo');
    }
}

$model = new stdClass;
$model->foo = 'bar';
$form = new MyForm;
$form->bind($model);



class MyModel
{
    public Foo $foo;
}

class MyForm extends Post
{
    public function __construct()
    {
        $this[] = (new Text('foo'))
            ->withTransformer(fn(string $value) => new Foo($value));
    }
}

$model = new MyModel;
$form = new MyForm;
$form->bind($model);
echo get_class($model->foo); // Foo