Skip to content

Form Service ​

The form service builds forms from plain PHP objects. A form is defined once, then reused to fill values, filter and validate input, and render HTML.

When each controller and template builds its own fields, the field names, validation rules and markup drift apart. A shared definition keeps them in sync.

INFO

The standalone package has its own detailed guide: Windwalker Form. This page focuses on using it inside the Windwalker framework.

Minimal Setup ​

Create a definition class. Mark each method with #[FormDefine] and add the fields with add().

php
use Windwalker\Form\Attributes\FormDefine;
use Windwalker\Form\Field\EmailField;
use Windwalker\Form\Field\TextField;
use Windwalker\Form\Form;

class UserForm
{
    #[FormDefine]
    public function define(Form $form): void
    {
        $form->add('name', TextField::class)
            ->required(true);

        $form->add('email', EmailField::class)
            ->required(true);
    }
}

The form is built by FormFactory. Get it from the container, or inject it into a constructor.

php
use Windwalker\Core\Form\FormFactory;

$formFactory = $app->retrieve(FormFactory::class);
$form = $formFactory->create(UserForm::class);

For more about service lookup, see Service Variants.

Complete Example ​

The following example defines a form, fills it with stored data, filters and validates a submitted request, and renders the result.

php
use Windwalker\Core\Form\FormFactory;
use Windwalker\Form\Attributes\FormDefine;
use Windwalker\Form\Field\EmailField;
use Windwalker\Form\Field\PasswordField;
use Windwalker\Form\Field\TextField;
use Windwalker\Form\Form;

class UserForm
{
    #[FormDefine]
    public function define(Form $form): void
    {
        $form->ns('user', function (Form $form) {
            $form->addField(new TextField('name', 'Name'))
                ->required(true);

            $form->addField(new EmailField('email', 'Email'))
                ->required(true);

            $form->addField(new PasswordField('password', 'Password'));
        });
    }
}

$form = $formFactory->create(UserForm::class);

// Fill the form with stored data.
$form->fill([
    'user' => [
        'name' => 'Alice',
        'email' => '[email protected]',
    ],
]);

// Filter and validate the submitted data.
$data = $form->filter($input);
$result = $form->validate($data);

if ($result->isFailure()) {
    // ERROR: $result->getResult('user/email') reports the failed field.
    $first = $result->first();
}

// Render all fields.
echo $form->renderFields();

Defining Fields ​

Field Classes ​

Each field is a class in the Windwalker\Form\Field namespace. The constructor takes the field name and label. Options are set by chained calls, such as required(true) and attr().

php
use Windwalker\Form\Field\NumberField;
use Windwalker\Form\Field\TextareaField;

$form->add('bio', TextareaField::class);

$form->add('age', NumberField::class)
    ->min(0)
    ->attr('data-bs-toggle', 'tooltip');

See the Fields reference for the full list of field types.

Adding by Class Name ​

add() creates the field from a class name. It returns the field.

php
$bio = $form->add('bio', TextareaField::class);

Namespaces and Fieldsets ​

ns() prefixes field names with a namespace. A field named email inside ns('user') has the full name user/email. Use getField() with that full name.

php
$form->ns('user', function (Form $form) {
    $form->add('email', TextField::class);
});

// Input name is user[email]; field key is user/email.
echo $form->getField('user/email')->getInputName();

fieldset() groups fields under a name. getFieldset() returns the group.

php
$form->fieldset('basic', function (Form $form) {
    $form->addField(new TextField('id', 'ID'));
});

INFO

getFields() matches the namespace exactly. It does not match prefixes, so getFields(null, 'user') does not return fields in user/profile.

Choices ​

Select, radio and checkbox fields take their options from a choice list. See Choices for the option APIs.

Filling Data ​

fill() assigns an array to the form. JSON-looking strings are decoded by default. Pass false as the second argument to keep them as plain text.

php
$form->fill($data);

// Keep JSON-looking strings as plain text.
$form->fill($data, false);

getValues() returns the current values. fillTo() copies the values to another object or array. See Data for the full data workflow.

Filtering and Validation ​

filter() applies each field's filters and skips disabled fields. validate() checks the data and returns a ResultSet.

php
$data = $form->filter($input);
$result = $form->validate($data);

if ($result->isFailure()) {
    $first = $result->first();
}

ResultSet::getResult() takes the full namespaced field name, such as user/email. Each ValidateResult has these status codes:

  • ValidateResult::STATUS_SUCCESS (200): the value passed.
  • ValidateResult::STATUS_REQUIRED (400): a required value is missing.
  • ValidateResult::STATUS_FAILURE (500): a rule rejected the value.

prepareStore() returns the filtered and validated values, ready for storage.

For the filters and validation rules, see Validation and Filter and the Filter component.

Rendering ​

renderFields() renders every field. renderField() renders one field by its full name.

php
echo $form->renderField('user/email');

setRenderer() replaces the renderer. The default FormRenderer looks up the @theme::form.field-wrapper, @theme::form.label and @theme::form.input templates. When they are missing, it uses a simple built-in renderer.

See Rendering for the rendering API.

Using Form in a View ​

A definition class can also receive external values. Pass them after the class name to create(), and they go to the constructor of the definition. This lets the fields change with the request, for example a list of allowed roles from the current user:

php
use Windwalker\Form\Attributes\FormDefine;
use Windwalker\Form\Field\ListField;
use Windwalker\Form\Form;

class CustomForm
{
    public function __construct(
        protected string $role,
    ) {
    }

    #[FormDefine]
    public function define(Form $form): void
    {
        if ($this->role === 'admin') {
            $form->add('role', ListField::class)
                ->setOptions([
                    'user' => 'User',
                    'admin' => 'Admin',
                ]);
        } else {
            $form->add('role', ListField::class)
                ->setOptions([
                    'user' => 'User',
                ]);
        }
    }
}

Views receive the form from FormFactory, fill it with the record, and pass it to the template. For the full pattern, see View and Admin. The Unicorn edit-form tutorial is at Edit Forms.

The short example below follows the pattern in those guides.

php
use Windwalker\Core\Form\FormFactory;

class UserEditView
{
    public function __construct(
        protected FormFactory $formFactory,
    ) {
    }

    public function prepare(#[Input, Filter('int')] int $id): array
    {
        $user = $this->userRepository->findOne($id);
    
        $form = $this->formFactory->create(
            UserForm::class, 
            role: $user->role
        );
        $form->fill(['user' => $user]);

        return compact('form');
    }
}

Reminders ​

WARNING

Do not store request data without calling filter() and validate() first. Unvalidated input can reach your database.

TIP

Keep one definition class per form. Controllers, views and renderers should all use the same class so the field names stay consistent.

Released under the MIT License.