Flick
Guide Validation Services API Pro Examples GitHub

Examples

There are many ways in which you can create forms with Flick!

Creating Forms

Use a string

Add each field's label text in a comma separated string... and your form is ready!

$form = new Flick\Flick();

$form->create('Name, Email');

Assign element types

We can easily tell Flick what type of field element we want to use by adding a pipe | character and the type of element we want to use.

$form->create('Name, Email|email, Comments|textarea');

Add default values

We can assign a default value to our field by placing it inside curly braces {}

$form->create(
    'Name{Foo},
     Email{foo@bar.com}|email,
     Comments|textarea{Lorem ipsum dolor sit amet...}'
);

Add a prebuilt dropdown menu

Let's add a prebuilt dropdown menu with all 50 U.S. states. Use the select element type and put the name of the menu inside parentheses ().

$form->create(
    'Name,
     Email|email,
     State|select(states),
     Comments|textarea'
);

Tip

Name the element type. Omitting it (State|(states)) falls back to a text input, which is rarely what you meant.

Add default menu options and validation rules

  • Add a default menu option by preceding it with double colons ::
  • Validation rules are placed inside brackets []
  • Use the r shortcut to make a field required.
$string = '
    Name{Gern}[min:3, max:30, r],
    Email|email[r, email],
    Foo|select([one:One, two:Two]::Select Something...)[r],
    Date|date[before:yesterday],
    State{NV}|select(states::Select a State...)[required],
    Comments|textarea[required],
    I Agree to the Terms|checkbox{agree}
';

$form->create($string);

Use a Prebuilt Form

We can also load a form array from a file. This is literally all you have to do to have a production ready login form.

$form->create('/login');

Create a multipart form for uploading files

Flick adds enctype="multipart/form-data" to the <form> tag.

$form->createMultipart('Photo|file');

Create a form with an array

We can add dropdown options using a string or an array.

$array = [
    'fields' => [
        'name' => [
            'label' => 'Name',
        ],
        'email' => [
            'type' => 'email',
            'label' => 'Email',
        ],
        'state' => [
            'type' => 'select',
            'label' => 'State',
            'value' => 'FL',
            'options' => 'states'
        ],
        'boolean' => [
            'type' => 'select',
            'label' => 'Boolean',
            'options' => [
                'yes' => 'Yes',
                'no' => 'No'
            ]
        ]
    ]
];

$form->create($array);

A more in-depth array example

$array = [
    'action' => '/',
    'method' => 'POST',
    'attributes' => [
        'id' => 'kifflom',
        'class' => 'form-horizontal',
        'multipart' => true,
        'string' => ' novalidate',
    ],
    'button' => [
        'text' => 'Join the Cult!',
        'attributes' => [
            'class' => 'btn btn-default',
        ],
    ],
    'fields' => [
        'username' => [
            'type' => 'text',
            'name' => 'username',
            'label' => 'Username',
            'attributes' => [
                'help' => 'between 3-20 characters',
                'classes' => 'form-control',
            ],
            'rules' => [
                'required',
                'min:3'
            ],
            'messages' => [
                'required' => 'Please enter your username',
                'min' => 'Username must be at least 3 characters'
            ]
        ],
        'email' => [
            'type' => 'email',
            'name' => 'email',
            'label' => 'Email',
            'rules' => [
                'required',
                'email'
            ],
            'messages' => [
                'required' => 'Please enter your email',
                'email' => 'Please enter a valid email address'
            ]
        ],
        'referrer' => [
            'type' => 'select',
            'name' => 'referrer',
            'label' => 'Referred By',
            'options' => [
                '' => 'Who Sent You?',
                'chris' => 'Chris Formage',
                'Marnie' => 'Marnie Allen',
                'jimmy' => 'Jimmy Boston'
            ],
            'rules' => [
                'required',
            ],
            'messages' => [
                'required' => 'Select a referrer',
            ]
        ]
    ]
];

$form->create($array);

HTTP Requests

Let's take a look at how we can process and validate our forms.

Use a string

Like with the create() method above, all we have to do is add our field labels and assign the values to a variable.

$request = $form->request('Name, Email, Comments');

$name = $request['name'];
$email = $request['email'];
$comments = $request['comments'];

Add validation rules and messages

  • Rules and messages are placed inside their own brackets []
  • Rules go in the first set of brackets, messages go in the second.
  • [rule1, rule2][rule1_message, rule2_message]
$request = $form->request(
    'Name[min:2, required][min:Less than 2, required:name is required],
     Email[email],
     Comments'
);

Get the Request values for individual fields

You can also process and validate your fields one-by-one.

if ($form->submitted())
{
    $name = $form->request('name');
    $email = $form->request('email');
    $comments = $form->request('comments');
}

Add validation rules

The validation rules array goes in the request() method's second parameter.

$name = $form->request('name', ['required', 'max:60']);

Add custom validation messages

Your validation messages array goes in the request() method's third parameter.

$name = $form->request('name',
    ['required', 'max:60'],
    [
        'required' => 'Please enter your name',
        'max' => 'Cannot be more than 60 characters',
    ]
);

Get the Request values for a form created with an array

You can also pass the same array you used to build the form.

$array = [
    'fields' => [
        'name' => [
            'label' => 'Name',
            'rules' => [
                'required'
            ],
            'messages' => [
                'required' => 'Please enter your name',
            ],
        ]
    ]
];

if ($form->submitted())
{
    # validate the form
    $request = $form->request($array);
}

# create the form
$form->create($array);

The same goes for using a prebuilt form

Type a forward slash, then the name of the form. That's it!

# form files carry their own id ('form-login' here) — set it in the config so
# submitted() recognizes the POST when create('/login') hasn't run yet this request
$form = new Flick\Flick(['id' => 'form-login']);

if ($form->submitted())
{
    # validate the form
    $request = $form->request('/login');
}

# create the form
$form->create('/login');

Complete Workflows

Here are end-to-end examples showing how to build production-ready forms that do something useful.

Save to Database

Create a contact form that saves submissions to a database.

<?php
require 'vendor/autoload.php';

$form = new Flick\Flick([
    'views' => 'bootstrap',
    'services' => [
        'sql' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'myapp',
            'username' => 'root',
            'password' => 'secret'
        ]
    ]
]);

$db = $form->sql;

if ($form->submitted()) {
    $request = $form->request('
        Name[required, min:2],
        Email[required, email],
        Phone[phone],
        Message[required, min:10]
    ');

    if ($form->ok()) {
        // useTimestamps sets created_at/updated_at for you — a hand-supplied
        // created_at would be stripped by mass assignment protection
        $db->table('contacts')->useTimestamps()->save([
            'name' => $request['name'],
            'email' => $request['email'],
            'phone' => $request['phone'],
            'message' => $request['message']
        ]);

        $form->successMessage('Thank you! We will be in touch soon.');
    }
}

$form->create('Name, Email, Phone, Message|textarea');

Send Email Notification

Create a form that emails submissions to your team.

<?php
require 'vendor/autoload.php';

$form = new Flick\Flick([
    'views' => 'tailwind',
    'services' => [
        'mail' => [
            'fromAddress' => 'noreply@example.com',
            'fromName' => 'My Website',
            'mailer' => [
                'transport' => 'smtp',
                'host' => 'smtp.example.com',
                'port' => 587,
                'encryption' => 'tls',
                'username' => $_ENV['SMTP_USER'],
                'password' => $_ENV['SMTP_PASS']
            ]
        ]
    ]
]);

if ($form->submitted()) {
    $request = $form->request('
        Name[required],
        Email[required, email],
        Subject[required],
        Message[required, min:20]
    ');

    if ($form->ok()) {
        // Send notification to admin
        $form->mail->sendFormData(
            'team@example.com',
            'New Contact: ' . $request['subject'],
            $request,
            ['exclude' => ['_token']]
        );

        // Send confirmation to user
        $form->mail->send(
            $request['email'],
            'We received your message',
            "Hi {$request['name']},\n\nThank you for reaching out. We'll respond within 24 hours.\n\nBest regards,\nThe Team"
        );

        $form->successMessage('Message sent! Check your email for confirmation.');
    }
}

$form->create('Name, Email, Subject, Message|textarea');

File Upload with Metadata

Upload images and save their metadata to a database.

<?php
require 'vendor/autoload.php';

$form = new Flick\Flick([
    'views' => 'bootstrap',
    'services' => [
        'upload' => [
            'directory' => __DIR__ . '/uploads',
            'url' => 'https://example.com/uploads',
            'conversions' => [
                'thumbnail' => [
                    'width' => 200,
                    'height' => 200,
                    'resizeMode' => 'cover',
                    'format' => 'webp',
                    'quality' => 80
                ]
            ]
        ],
        'sql' => [
            'driver' => 'sqlite',
            'path' => __DIR__ . '/database.sqlite'
        ]
    ]
]);

$db = $form->sql;

if ($form->submitted()) {
    $request = $form->request('
        Title[required, min:3],
        Description[required, min:10]
    ');

    // Upload and process the image
    $files = $form->upload->image('photo', [
        'required',
        'maxFileSize:5MB',
        'conversions:thumbnail'
    ]);

    // $files is a FileCollection: ->original is the main processed file,
    // ->thumbnail is the conversion.

    if ($form->ok() && $files) {
        $db->table('gallery')->useTimestamps()->save([
            'title' => $request['title'],
            'description' => $request['description'],
            'image_path' => $files->original->path,
            'thumbnail_path' => $files->thumbnail->path,
            'image_url' => $files->original->url,
            'thumbnail_url' => $files->thumbnail->url
        ]);

        $form->successMessage('Image uploaded successfully!');
    }
}

$form->createMultipart('Title, Description|textarea, Photo|file');

Complete Registration with Auth

User registration with password hashing and automatic login.

<?php
require 'vendor/autoload.php';

$form = new Flick\Flick([
    'views' => 'tailwind',
    'services' => [
        'auth' => [],
        'sql' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'myapp',
            'username' => 'root',
            'password' => 'secret'
        ]
    ]
]);

$db = $form->sql;

if ($form->submitted()) {
    $request = $form->request('
        Name[required, min:2],
        Email[required, email],
        Password[required, strongPassword],
        Confirm Password[required, matches:password]
    ');

    if ($form->ok()) {
        // Check if email is already registered
        if (!$db->validateUnique('users', 'email', $request['email'])) {
            $form->addError('email', 'This email is already registered.');
        }
    }

    if ($form->ok()) {
        // Save user with hashed password
        $userId = $db->table('users')
            ->useTimestamps()
            ->save([
                'name' => $request['name'],
                'email' => $request['email'],
                'password' => $form->auth->hash($request['password'])
            ]);

        // Log them in automatically
        $form->auth->login($userId);
        $form->redirect('/dashboard');
    }
}

$form->create('Name, Email, Password|password, Confirm Password|password');