PHP code example of litepie / form

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

    

litepie / form example snippets


use Litepie\Form\Field;

// Simple field
$field = Field::make('text', 'username');

// With fluent API
$field = Field::make('select', 'theme')
    ->label('Select Theme')
    ->options(['dark' => 'Dark Mode', 'light' => 'Light Mode'])
    ->

use Litepie\Form\Facades\Form;

$form = Form::create()
    ->add('name', 'text', ['label' => 'Name', '

use Litepie\Form\Fields\TextField;
use Litepie\Form\Fields\SelectField;

$textField = new TextField('username');
$selectField = new SelectField('country');

use Litepie\Form\Facades\Form;
use Litepie\Form\Field;

$contactForm = Form::create()
    ->action('/contact')
    ->method('POST')
    ->add(Field::make('text', 'name')
        ->label('Full Name')
        ->quired|email')
    )
    ->add(Field::make('textarea', 'message')
        ->label('Message')
        ->

$registrationForm = Form::create()
    ->action('/register')
    ->method('POST')
    ->files(true)
    ->add(Field::make('image', 'avatar')
        ->label('Profile Picture')
        ->setAttribute('accept', 'image/*')
        ->setAttribute('maxSize', 5) // 5MB
        ->setAttribute('crop', true)
        ->setAttribute('aspectRatio', '1:1')
    )
    ->add(Field::make('text', 'first_name')
        ->label('First Name')
        ->ion', 'password', [
        'label' => 'Confirm Password',
        '

// Quick form creation
$quickForm = form_quick([
    'name' => 'text',
    'email' => ['type' => 'email', 'ld
$nameField = form_field('name', 'text', [
    'label' => 'Full Name',
    '

use Litepie\Form\Facades\Form;

$userForm = Form::create()
    ->action('/users')
    ->forUser(auth()->user())  // Set user for all operations
    
    // Basic fields - visible to everyone
    ->add(Form::text('name')->label('Name'))
    ->add(Form::email('email')->label('Email'))
    
    // Only visible with permission
    ->add(
        Form::number('salary')
            ->label('Salary')
            ->can('view-salary')
    )
    
    // Only visible to specific roles
    ->add(
        Form::select('department')
            ->label('Department')
            ->options(['sales' => 'Sales', 'engineering' => 'Engineering'])
            ->roles(['manager', 'admin'])
    )
    
    // Custom visibility logic
    ->add(
        Form::text('api_key')
            ->label('API Key')
            ->visibleWhen(fn($user) => $user && $user->isPremium())
    );

// Render only visible fields
echo $userForm->render();

// For client-side (Vue, React, etc.) - only visible fields 

use Litepie\Form\Facades\Form;

// Enable caching with default TTL (1 hour)
$form = Form::create()
    ->forUser(auth()->user())
    ->cache()  // Enable caching
    ->add(Form::text('name'))
    ->add(Form::email('email'))
    ->add(Form::number('salary')->can('view-salary'));

// First render - generates and caches output
$html = $form->render();  // Slow

// Subsequent renders - returns cached output
$html = $form->render();  // Fast (from cache)

// Custom cache TTL (30 minutes)
$form->cache(1800);

// Cache is automatically scoped per user
$adminForm = $form->render($adminUser);    // Cached for admin
$managerForm = $form->render($managerUser); // Cached for manager

// Clear cache when needed
$form->clearCache();

// Disable caching
$form->withoutCache();

use Litepie\Form\Facades\Form;

// Default: all fields are 6 columns (half width)
$form = Form::create()
    ->add(Form::text('first_name'))  // 6 columns (default)
    ->add(Form::text('last_name'));  // 6 columns (default)

// Custom column widths
$form = Form::create()
    ->add(Form::text('first_name')->col(6))   // 6/12 columns
    ->add(Form::text('last_name')->col(6))    // 6/12 columns
    ->add(Form::email('email')->col(12))      // Full width
    ->add(Form::text('city')->col(4))         // 4/12 columns
    ->add(Form::text('state')->col(4))        // 4/12 columns
    ->add(Form::text('zip')->col(4));         // 4/12 columns

// Group fields in rows (Recommended)
$form = Form::create()
    // Row 1: Two half-width fields (auto row ID: 'row1')
    ->row([
        Form::text('first_name')->col(6),
        Form::text('last_name')->col(6)
    ])
    
    // Row 2: Three equal fields (auto row ID: 'row2')
    ->row([
        Form::text('city')->col(4),
        Form::text('state')->col(4),
        Form::text('zip')->col(4)
    ])
    
    // Row 3: Custom split (auto row ID: 'row3')
    ->row([
        Form::text('field1')->col(3),
        Form::text('field2')->col(4),
        Form::text('field3')->col(5)
    ])
    
    // Row with custom ID
    ->row([
        Form::textarea('notes')->col(12)
    ], 'notes-row');

// Alternative: Manual row assignment
$form = Form::create()
    ->add(Form::text('first_name')->col(6)->row('contact'))
    ->add(Form::text('last_name')->col(6)->row('contact'))
    ->add(Form::text('city')->col(4)->row('address'))
    ->add(Form::text('state')->col(4)->row('address'))
    ->add(Form::text('zip')->col(4)->row('address'));

// Change default width for all fields
$form = Form::create()
    ->defaultWidth(4)  // All fields 4 columns by default
    ->row([
        Form::text('field1'),      // 4 columns (uses default)
        Form::text('field2'),      // 4 columns (uses default)
        Form::text('field3')       // 4 columns (uses default)
    ])
    ->row([
        Form::text('notes')->col(12)  // Override: full width
    ]);

// Output 

use Litepie\Form\Facades\Form;

$form = Form::create()
    ->action('/users')
    
    // Group 1: Basic Information
    ->group('basic_info', 'Basic Information', 'Enter your basic details')
        
        // Section 1.1: Personal Details
        ->section('personal', 'Personal Details')
            ->row([
                Form::text('first_name')->col(6)->label('First Name')->ow([
                Form::text('street')->col(12)->label('Street Address')
            ])
            ->row([
                Form::text('city')->col(4)->label('City'),
                Form::text('state')->col(4)->label('State'),
                Form::text('zip')->col(4)->label('ZIP Code')
            ])
        ->endSection()
        
    ->endGroup()
    
    // Visual separator with label
    ->divider('Additional Details')
    
    // Group 2: Account Settings
    ->group('account_settings', 'Account Settings')
        
        ->section('security', 'Security')
            ->row([
                Form::password('password')->col(6)->label('Password'),
                Form::password('password_confirmation')->col(6)->label('Confirm Password')
            ])
        ->endSection()
        
        ->section('preferences', 'Preferences')
            ->row([
                Form::checkbox('newsletter')->label('Subscribe to newsletter'),
                Form::checkbox('notifications')->label('Enable notifications')
            ])
        ->endSection()
        
    ->endGroup()
    
    // Divider without label (just a line)
    ->divider()
    
    // Fields without group/section (top-level)
    ->row([
        Form::submit('submit')->value('Save Changes')->class('btn btn-primary')
    ]);

$form = Form::create()
    ->group('info', 'Information')
    
    // Add fields - they automatically get group='info'
    ->add(Form::text('name')->col(6)->section('personal'))
    ->add(Form::email('email')->col(6)->section('personal'))
    
    ->add(Form::text('company')->col(6)->section('business'))
    ->add(Form::text('title')->col(6)->section('business'))
    
    ->endGroup();

// Divider with label
->divider('Section Title')

// Plain divider (just a line)
->divider()

// Divider in specific group/section
->divider('Advanced Options', 'settings_group', 'advanced_section')

// Bootstrap 5 (default)
Form::create()->theme('bootstrap5');

// Bootstrap 4
Form::create()->theme('bootstrap4');

// Tailwind CSS
Form::create()->theme('tailwind');

// Custom theme
Form::create()->theme('custom');

return [
    'default_theme' => 'bootstrap5',
    'validation' => [
        'realtime' => true,
        'debounce' => 300,
        'show_errors' => true,
    ],
    'uploads' => [
        'disk' => 'public',
        'path' => 'uploads/forms',
        'max_size' => '10MB',
        'allowed_types' => ['jpg', 'png', 'pdf', 'doc'],
    ],
    'maps' => [
        'provider' => 'google',
        'api_key' => env('GOOGLE_MAPS_API_KEY'),
        'default_zoom' => 10,
    ],
    'editor' => [
        'provider' => 'tinymce',
        'config' => [
            'height' => 300,
            'menubar' => false,
            'toolbar' => 'bold italic | link image | bullist numlist',
        ],
    ],
];

$form->add('email', 'email', [
    'validation' => '

$form->add('username', 'text', [
    'validation' => '

$form->add('custom_field', 'text', [
    'validation' => ['is field is mandatory'
    ]
]);

$form->add('account_type', 'select', [
    'label' => 'Account Type',
    'options' => [
        'personal' => 'Personal',
        'business' => 'Business'
    ]
])
->add('company_name', 'text', [
    'label' => 'Company Name',
    'show_if' => 'account_type:business',
    'validation' => '

$multiStepForm = Form::create()
    ->multiStep(true)
    ->add('step1_name', 'text', [
        'label' => 'Name',
        'step' => 1
    ])
    ->add('step2_details', 'textarea', [
        'label' => 'Details',
        'step' => 2
    ])
    ->add('step3_confirmation', 'checkbox', [
        'label' => 'Confirm',
        'step' => 3
    ]);

$form->add('document', 'file', [
    'label' => 'Upload Document',
    'accept' => '.pdf,.doc,.docx',
    'maxSize' => '10MB',
    '

$form->add('profile_image', 'image', [
    'label' => 'Profile Picture',
    'crop' => true,
    'aspectRatio' => '1:1',
    'minWidth' => 400,
    'maxSize' => '5MB',
    'formats' => ['jpg', 'png', 'webp']
]);

$form->add('photos', 'gallery', [
    'label' => 'Photo Gallery',
    'maxFiles' => 10,
    'sortable' => true,
    'preview' => true,
    'uploadUrl' => '/upload/gallery'
]);

use Litepie\Form\Facades\Form;

// Create a container with multiple forms
$container = Form::container('user-settings')
    ->name('User Settings')
    ->description('Manage your account settings')
    ->tabbed(true); // Use tabbed interface

// Add forms to the container
$profileForm = $container->createForm('profile', [
    'title' => 'Profile Information',
    'description' => 'Update your personal details'
]);

$profileForm
    ->add('first_name', 'text', ['label' => 'First Name', 'd', 'password', ['label' => 'Confirm Password']);

// Render the container
{!! $container->render() !!}

// Create multiple forms at once
$container = Form::quickContainer([
    'contact' => [
        'fields' => [
            'name' => 'text',
            'email' => ['type' => 'email', '       'title' => 'Contact Information',
            'description' => 'Get in touch with us'
        ]
    ],
    'feedback' => [
        'fields' => [
            'rating' => ['type' => 'range', 'min' => 1, 'max' => 5],
            'suggestion' => 'textarea'
        ],
        'containerOptions' => [
            'title' => 'Feedback',
            'description' => 'Help us improve'
        ]
    ]
], [
    'name' => 'Contact & Feedback',
    'accordion' => true // Use accordion interface
]);

// Tabbed interface
$container->tabbed(true)->activeForm('step1');

// Accordion interface
$container->accordion(true);

// Stacked interface (default)
// Forms displayed one after another

// Individual validation (default) - each form validated separately
$container->validationMode('individual');

// Combined validation - all forms must pass
$container->validationMode('combined');

// Sequential validation - stops at first failure
$container->validationMode('sequential');

class RegistrationContainer extends \Litepie\Form\FormContainer
{
    public function __construct($app)
    {
        parent::__construct($app, 'registration');
        $this->setupRegistrationForms();
    }

    protected function setupRegistrationForms(): void
    {
        $this->name('User Registration')
             ->tabbed(true)
             ->validationMode('sequential');

        // Step 1: Personal Information
        $personal = $this->createForm('personal', [
            'title' => 'Personal Information',
            'icon' => 'user'
        ]);

        $personal
            ->add('first_name', 'text', ['        return (int)(($currentStep + 1) / $totalSteps * 100);
    }
}

// Usage
$registrationContainer = new RegistrationContainer(app());
echo $registrationContainer->render();

class ContactController extends Controller
{
    public function create()
    {
        $form = Form::create()
            ->action(route('contact.store'))
            ->method('POST')
            ->add('name', 'text', ['uest)
    {
        // Form validation is automatic
        $validated = $request->validate([
            'name' => '

// Convert existing form to array
$form = Form::create()
    ->add('name', 'text', ['formJson = $form->toJson();

// Or use helper functions
$formArray = form_array([
    'name' => ['type' => 'text', 'label' => 'Name', '

// Return form schema as JSON for Vue/React/Angular
Route::get('/api/forms/contact', function() {
    return form_array([
        'name' => ['type' => 'text', 'label' => 'Name', '     'action' => '/api/contact',
        'method' => 'POST'
    ]);
});

$form->add('name', 'text', [
    'class' => 'custom-input large',
    'wrapper_class' => 'custom-wrapper',
    'label_class' => 'custom-label'
]);

$form = Form::create()
    ->ajax(true)
    ->action('/api/contact')
    ->onSuccess('handleSuccess')
    ->onError('handleError')
    ->add('name', 'text', ['

$form = Form::create()
    ->add('base_field', 'text')
    ->addIf($condition, 'conditional_field', 'text')
    ->addWhen('user_type', 'business', function($form) {
        $form->add('company_name', 'text', ['

class ContactFormTest extends TestCase
{
    /** @test */
    public function it_validates_contact_form()
    {
        $form = Form::create()
            ->add('name', 'text', [''
        ]));

        $this->assertFalse($form->validate([
            'name' => '',
            'email' => 'invalid-email'
        ]));
    }
}

$form->action(string $action)              // Set form action URL
$form->method(string $method)              // Set HTTP method (POST, GET, etc.)
$form->files(bool $enabled = true)         // Enable file uploads
$form->theme(string $theme)                // Set UI framework (bootstrap5, tailwind)
$form->ajax(bool $enabled = true)          // Enable AJAX submission
$form->multiStep(bool $enabled = true)     // Enable multi-step forms

$form->forUser(object $user)               // Set user for visibility checks
$form->getUser()                           // Get current user

$form->cache(int $ttl = 3600)             // Enable caching with TTL
$form->cached()                            // Check if caching is enabled
$form->withoutCache()                      // Disable caching
$form->clearCache()                        // Clear form cache

$form->add(string $name, string $type, array $options = [])  // Add field
$form->remove(string $name)                                   // Remove field
$form->has(string $name)                                      // Check if field exists
$form->get(string $name)                                      // Get field instance

$form->row(array $fields, ?string $id = null)                                    // Add fields in a row
$form->group(string $id, ?string $title = null, ?string $description = null)    // Start group
$form->section(string $id, ?string $title = null, ?string $description = null)  // Start section
$form->endGroup()                                                                 // End current group
$form->endSection()                                                               // End current section
$form->divider(?string $label = null)                                            // Add divider
$form->defaultWidth(int $width)                                                   // Set default field width

$form->populate(array $data)               // Populate form with data
$form->validate(array $data)               // Validate form data
$form->getValidationRules()                // Get all validation rules

$form->render(?object $user = null)        // Render HTML (respects visibility)
$form->toArray(?object $user = null)       // Convert to array (respects visibility)
$form->toJson(?object $user = null)        // Convert to JSON (respects visibility)
$form->visibleFields(?object $user = null) // Get visible fields only
$form->renderField(string $name)           // Render single field
$form->renderErrors()                      // Render validation errors

[
    'label' => 'Field Label',
    'placeholder' => 'Enter value...',
    'help' => 'Help text',
    'ta-custom' => 'value'],
    'show_if' => 'other_field:value',
    'hide_if' => 'other_field:value',
    'value' => 'default value'
]

// Enable caching with custom TTL
$container = Form::container('user-settings')
    ->enableCache(3600) // 1 hour
    ->cacheTags(['user_forms', 'settings']);

// Configure cache settings
$container->cache([
    'enabled' => true,
    'ttl' => 1800, // 30 minutes
    'driver' => 'redis',
    'tags' => ['forms', 'containers'],
]);

// Cache is automatically applied to:
// - render() - Caches full HTML output
// - renderSingleForm() - Caches individual form HTML
// - toArray() - Caches array representation
// - getVisibleForms() - Caches filtered collections

// Manual cache management
$container->clearCache(); // Clear all cache for this container
$container->disableCache(); // Temporarily disable caching

'cache' => [
    'enabled' => env('FORM_CACHE_ENABLED', true),
    'ttl' => env('FORM_CACHE_TTL', 3600),
    'driver' => env('FORM_CACHE_DRIVER', 'redis'),
    'prefix' => 'form_cache',
    'tags' => ['forms', 'containers'],
    'auto_clear_on_update' => true,
],
bash
php artisan vendor:publish --provider="Litepie\Form\FormServiceProvider"
php artisan form:install