Creating a Form Builder


Related Links

Introduction

Usually you don't have to make form builders yourself. When you use the make:stream command the form builder is generated for you in the addon's src/{entry}/Form/ directory.

This tutorial will show you how to create a form builder manually.

Creating a Form Builder

To get started simply create a new class that extends the \Anomaly\Streams\Platform\Ui\Form\FormBuilder class:

<?php namespace App\Form;

use Anomaly\Streams\Platform\Ui\Form\FormBuilder;

class ExampleFormBuilder extends FormBuilder
{

}

Required Properties

Generated form builders use a combination of class transformation and guessing so there is nothing that is required on your part. However when creating form builders manually there are a few properties which you must provide.

Model

The form model is usually a stream entry model but a normal Eloquent model can be used as well though it will require manually providing field definitions.

<?php namespace App\Form;

use Anomaly\Streams\Platform\Ui\Form\FormBuilder;
use Anomaly\UsersModule\User\UserModel;

class ExampleFormBuilder extends FormBuilder
{

    protected $model = UserModel::class;
}

The above example will display a form with all of the user fields from the users module by default because the streams entry model provides the field definitions in the case that we don't override this behavior and provide them ourselves.

Fields

If you provide a generic Eloquent model or, as in some advanced cases, you don't use a model, then you must provide the fields definitions. This is because normal models don't contain any streams data so you have to tell the form builder what fields are available.

When defining custom fields for a non-streams form the field slugs should match up with the database columns:

<?php namespace App\Form;

use Anomaly\Streams\Platform\Ui\Form\FormBuilder;
use Anomaly\UsersModule\User\UserModel;
use Laravel\Passport\Client;

class ExampleFormBuilder extends FormBuilder
{

    protected $model = Client::class;

    protected $fields = [
        'user_id'  => [
            'required' => true,
            'label'    => 'User',
            'type'     => 'anomaly.field_type.relationship',
            'config'   => [
                'mode'    => 'lookup',
                'related' => UserModel::class,
            ],
        ],
        'name'     => [
            'required' => true,
            'label'    => 'Client Name',
            'type'     => 'anomaly.field_type.text',
        ],
        'redirect' => [
            'required' => true,
            'label'    => 'Redirect URL',
            'type'     => 'anomaly.field_type.url',
        ],
    ];
}

The above form builder defines a normal Eloquent model, in this case from Laravel's passport package, and maps a few fields to the database columns in the model's table.