PHP code example of ramondev / formcraft

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

    

ramondev / formcraft example snippets


use Formcraft\FormProcessor;
use Formcraft\FormFields;
use Formcraft\LaravelFormTemplate;

class ContactForm extends FormProcessor
{
    public function setFields(): LaravelFormTemplate
    {
        return new LaravelFormTemplate(fn (FormFields $f) => [
            'name'  => $f->CharField(label: 'Full name'),
            'email' => $f->EmailField(),
        ]);
    }
}

public function store(Request $request, ContactForm $form)
{
    $form->validate($request->all());

    if (! $form->is_validated()) {
        return back()->withErrors($form->errors()->all())->withInput();
    }

    // do something with $form->values()
}

public function setFields(): LaravelFormTemplate
{
    return new LaravelFormTemplate(fn (FormFields $f) => [
        'name'     => $f->CharField(label: 'Full name', '      => $f->IntegerField(min: 18, max: 120),
        'birthday' => $f->DateField(),
        'role'     => $f->SelectField(options: [
            ['value' => 'admin', 'text' => 'Administrator'],
            ['value' => 'user',  'text' => 'Regular user'],
        ]),
        'terms'    => $f->CheckBoxField(label: 'I agree to the terms', value: '1'),
        'avatar'   => $f->ImageField(

'photo[]' => $f->ImageField(
    multiple: true,
    minFiles: 2,
    maxFiles: 4,
    max: 2048, // KB, per file
    validateMessageAttribute: 'Photos',
),

'photo[]' => $f->ImageField(
    multiple: true,
    maxFiles: 4,
    validateMessageAttribute: fn (int $index) => 'Photo ' . ($index + 1),
),

$form->validate($request->all(), $request->allFiles());

if ($form->is_validated()) {
    // ...
}

$values = $form->values(); // ObjectClass
$values->email;            // the submitted email
$values->toArray();        // as a plain array

$form->initialValue($existingModel); // array or object
$form->validate($request->all());

$form->dirty();            // ['email', 'bio'] - keys whose submitted value changed
$form->isDirty('email');   // true/false

$form->setModel(new User());
$form->validate($request->all());

if ($form->is_validated()) {
    $user = $form->save(); // returns the saved model
}

'avatar' => $f->ImageField(
    ,
    imageSize: '800x800',
    oldFile: $user->avatar ?? null,
),

$form->validate($request->all(), $request->allFiles());

if ($form->is_validated()) {
    $form->uploadFiles();               // moves/resizes files, generates filenames
    $user = $form->save();              // values()/save() now use the uploaded filenames
}

'avatar' => $f->ImageField(
    uploadTo: 'uploads/avatars',
    filename: 'user-' . auth()->id() . '-avatar', // -> user-42-avatar.jpg
),

'avatar' => $f->ImageField(
    uploadTo: 'uploads/avatars',
    imageSize: '800x800',
    filename: 'user-' . auth()->id() . '-avatar',

    thumbnail: '150x150',                 // enables the thumbnail
    thumbnailTo: 'uploads/avatars/thumbs', // saved into its own folder
    thumbnailName: 'user-' . auth()->id() . '-avatar-thumb',

    oldFile: $user->avatar ?? null,           // deletes the old main file
    oldThumbnail: $user->avatar_thumb ?? null, // deletes the old thumbnail, same way

    saveAs: 'avatar',              // main filename -> users.avatar
    thumbnailSaveAs: 'avatar_thumb', // thumbnail filename -> users.avatar_thumb
),

$form->uploadFiles();

$form->values()->avatar['filename'];   // e.g. "user-42-avatar.jpg"
$form->values()->avatar['thumbnail'];  // e.g. "user-42-avatar-thumb.jpg"

// or, before/without calling values():
$form->getUploadedFiles()->avatar['thumbnail'];

$form->setModel($user);
$form->uploadFiles();
$user = $form->save(); // sets $user->avatar AND $user->avatar_thumb, then saves

use Formcraft\FileManager;

$manager = new FileManager($request->file('avatar'));
$manager->path = 'uploads/avatars';
$manager->size = '800x800';
$manager->filename = 'user-42-avatar';         // optional - custom main filename
$manager->thumb = '150x150';
$manager->thumbPath = 'uploads/avatars/thumbs'; // optional - separate thumbnail folder
$manager->thumbFilename = 'user-42-avatar-thumb'; // optional - custom thumbnail filename
$manager->old = $user->avatar;
$manager->oldThumb = $user->avatar_thumb;
$manager->upload();

$newFilename = $manager->filename;
$newThumbFilename = $manager->thumbFilename; // set whenever $thumb was configured

'address' => $f->GroupField(label: 'Address', fields: [
    'street' => $f->CharField(),
    'city'   => $f->CharField(),
]),

'items' => $f->GroupField(valueType: 'array', fields: [
    'name'  => $f->CharField(validateMessageAttribute: 'Item name'),
    'qty'   => $f->IntegerField(min: 1),
], applyRuleToFields: ['

use Formcraft\FormProcessor;

$addressSet = FormProcessor::formSet(AddressForm::class, num: 3, label: 'address');

// Render each copy (names are auto-namespaced: address_0, address_1, address_2)
foreach ($addressSet->set() as $addressForm) {
    echo $addressForm;
}

public function create(Request $request)
{
    $rows = max((int) $request->query('rows', 3), 1);

    if ($request->session()->hasOldInput()) {
        $rows = max((int) old('item_count', $rows), 1); // keep the same row count
    }

    $items = FormProcessor::formSet(OrderItemForm::class, $rows, 'item');

    if ($request->session()->hasOldInput()) {
        $items->validate($request->session()->getOldInput());
    }

    return view('orders.create', compact('items'));
}

use Formcraft\FormWizard;

$wizard = new FormWizard('signup', [
    'account' => AccountStepForm::class,
    'profile' => ProfileStepForm::class,
    'billing' => BillingStepForm::class,
]);

// Show the current step
$step = $wizard->currentStep();  // e.g. 'account' - null once all steps are done
$form = $wizard->form();         // that step's FormProcessor, pre-filled from any prior submission

// Handle a submission
if ($wizard->submitStep($request->all(), $request->allFiles())) {
    return redirect()->route('signup.step', $wizard->currentStep());
}
// Failed - use $wizard->lastForm()->errors(). If the failed step has a file
// input, render $wizard->lastForm() directly instead of redirecting, since a
// redirect can't carry an uploaded file back with it.

// Once done
if ($wizard->isComplete()) {
    $allData = $wizard->allData(); // ['account' => [...], 'profile' => [...], 'billing' => [...]]
}

$form->setTheme(new \Formcraft\Support\BootstrapTheme());

protected function defaultTheme(): FormTheme
{
    return new \Formcraft\Support\TailwindTheme();
}

use Formcraft\Support\FormTheme;
use Formcraft\ObjectClass;

class MyTheme implements FormTheme
{
    public function inputClasses(string $renderType, array $props): string
    {
        // $renderType: "input" | "textarea" | "select" | "groupField"
        // for "input", $props['type'] is the HTML input type
        return 'my-input';
    }

    public function labelClasses(string $renderType, array $props): string
    {
        return 'my-label';
    }

    public function render(string $name, ObjectClass $fields, array $props, string $renderType): string
    {
        // $fields->label / ->input are already-rendered HTML strings
        // $fields->errors is a Collection of this field's error messages
        $wrapperTag = ($props['group'] ?? false) ? 'fieldset' : 'div';
        return "<{$wrapperTag}>{$fields->label}{$fields->input}</{$wrapperTag}>";
    }
}



namespace App\Forms;

use Formcraft\FormFields;
use Formcraft\FormProcessor;
use Formcraft\LaravelFormTemplate;
use Formcraft\Support\FormTheme;
use Formcraft\Support\BootstrapTheme;

class RegistrationForm extends FormProcessor
{
    protected function defaultTheme(): FormTheme
    {
        return new BootstrapTheme();
    }

    public function setFields(): LaravelFormTemplate
    {
        return new LaravelFormTemplate(fn (FormFields $f) => [
            'name' => $f->CharField(
                label: 'Full name',
                minLength: 2,
                maxLength: 100,
            ),
            'email' => $f->EmailField(
                validateRule: ['unique:users,email'],
            ),
            'password' => $f->PasswordField(
                minLength: 8,
                hashValue: true,
            ),
            'avatar' => $f->ImageField(
                



namespace App\Http\Controllers;

use App\Forms\RegistrationForm;
use App\Models\User;
use Illuminate\Http\Request;

class RegistrationController extends Controller
{
    public function create(RegistrationForm $form)
    {
        return view('register', compact('form'));
    }

    public function store(Request $request, RegistrationForm $form)
    {
        $form->validate($request->all(), $request->allFiles());

        if (! $form->is_validated()) {
            return back()->withErrors($form->errors()->all())->withInput();
        }

        $form->uploadFiles();
        $form->setModel(new User());
        $user = $form->save();

        return redirect()->route('dashboard')->with('status', 'Welcome, ' . $user->name . '!');
    }
}
blade
<form method="POST">
    @csrf
    {!! $form !!}
    <button type="submit">Send</button>
</form>
blade
<div>
    {!! $form->email->label !!}
    {!! $form->email->input !!}
    @foreach ($form->email->errors->all() as $error)
        <p class="text-red-600">{{ $error }}</p>
    @endforeach
</div>
bash
php artisan make:theme Card              # creates CardTheme
php artisan make:theme MyCompanyTheme --path=Themes
blade
<form method="POST" action="{{ route('register.store') }}" enctype="multipart/form-data">
    @csrf
    {!! $form !!}
    <button type="submit">Create account</button>
</form>