FormBuilder - Field Configuration
Form field configuration starts from the Model definition. FormBuilder methods allow you to modify this base configuration to customize the fields.
Available Methods
| Method | Description | Example |
|---|---|---|
field(string $key) |
Selects an existing field or creates it if it doesn't exist | ->field('email') |
type(string $type) |
Sets the data type (string, int, date, etc.) | ->type('string') |
formType(string $type) |
Sets the form field type (text, select, textarea, etc.) | ->formType('select') |
label(string $label) |
Sets the field label | ->label('Email') |
options(array $options) |
Sets options for select/checkbox/radio | ->options(['1' => 'Yes']) |
required(bool $req = true) |
Makes the field required | ->required() |
helpText(string $text) |
Sets the help text below the field | ->helpText('Format: xxx-xxxx') |
value(mixed $value) |
Sets the field value | ->value('default') |
default(mixed $value) |
Sets the default value if no value exists | ->default('IT') |
checkboxValues($checked, $unchecked) |
Sets custom values for checkbox (e.g., 'S'/'N', 'Y'/'N') | ->checkboxValues('S', 'N') |
disabled(bool $dis = true) |
Disables the field | ->disabled() |
readonly(bool $ro = true) |
Makes the field readonly | ->readonly() |
class(string $class) |
Sets the CSS class | ->class('form-control-lg') |
errorMessage(string $msg) |
Sets a custom error message | ->errorMessage('Invalid email') |
moveBefore(string $field) |
Moves the field before another field | ->moveBefore('status') |
resetFields() |
Hides all existing fields from Model. Fields become visible when you call field() with their base configuration |
->resetFields() |
Basic Usage
Methods are chained after field() which selects the field to configure:
$form = FormBuilder::create($model, $this->page)
->field('email')
->label('Email Address')
->required()
->errorMessage('Please enter a valid email')
->helpText('We will never share your email with anyone else')
->field('status')
->formType('select')
->options(['active' => 'Active', 'inactive' => 'Inactive'])
->value('active')
->getForm();
Creating New Fields
If the field doesn't exist in the Model, it will be created automatically:
->field('phone')
->type('string')
->label('Phone Number')
->required()
->helpText('Format: 555-1234')
Modifying Existing Fields
Fields defined in the Model can be modified:
// 'email' field defined in the Model
->field('email')
->label('Email Address') // Modifies the label
->helpText('We will never share your email') // Adds help text
->required() // Makes it required
Examples by Field Type
Text Field
->field('username')
->type('string')
->label('Username')
->required()
->errorMessage('Username is required')
->helpText('Choose a unique username')
Select Field
->field('category')
->formType('select')
->label('Category')
->options([
'1' => 'Electronics',
'2' => 'Books',
'3' => 'Clothing'
])
->value('1')
->required()
Textarea Field
->field('description')
->formType('textarea')
->label('Description')
->helpText('Provide a detailed description')
Date Field
->field('publish_date')
->type('date')
->label('Publish Date')
->value(date('Y-m-d'))
Checkbox with Custom Values
->field('active')
->formType('checkbox')
->label('Active')
->checkboxValues('S', 'N') // 'S' when checked, 'N' when unchecked
Switch Field
A switch is a checkbox with Bootstrap's form-switch class. Use checkboxValues() for custom values and formParams(['form-check-class' => 'form-switch']) to enable the switch style:
// In your Model
->string('active', 1)
->label('Active')
->formType('checkbox')
->checkboxValues('S', 'N') // 'S' = On, 'N' = Off
->formParams(['form-check-class' => 'form-switch'])
// Or with FormBuilder
->field('notifications')
->formType('checkbox')
->label('Enable Notifications')
->checkboxValues('Y', 'N')
->formParams(['form-check-class' => 'form-switch'])
Disabled Field
->field('created_at')
->label('Created At')
->readonly()
Field with Set Value
->field('post_id')
->type('int')
->value($post_id)
->readonly()
Reset and Rebuild Fields
Use resetFields() to start with a clean slate and show only the fields you explicitly define. This is useful when you want to create a form with a specific subset of fields from your Model.
How resetFields() Works
When you call resetFields(), all existing fields from the Model are hidden. Then, as you call field(), those fields become visible again with their base configuration from the Model.
Key difference from TableBuilder: In FormBuilder, when you reactivate a field with field(), it automatically retains its base configuration from the Model (e.g., if it was defined as a checkbox in the Model, it will be a checkbox).
$form = FormBuilder::create($model, $this->page)
->resetFields() // Hide ALL existing fields from Model
// Only these fields will be shown, with their Model configuration:
->field('id')
->label('ID')
->readonly()
->field('title')
->label('Article Title')
->required()
->field('status')
->label('Status')
// If 'status' is a checkbox in the Model, it remains a checkbox
->field('published_at')
->label('Published Date')
->addStandardActions()
->getForm();
// Result: Form shows only id, title, status, published_at (in that order)
// All other Model fields are hidden
// Each field maintains its base configuration from the Model
Use Cases for resetFields()
- Simplified forms: Show only essential fields for quick edits
- Multi-step forms: Display different field sets for each step
- Role-based forms: Show different fields based on user permissions
- Custom field order: Define the exact order of fields without using
moveBefore()
Field Repositioning
The moveBefore() method moves the field before another field:
->field('email')
->label('Email')
->moveBefore('password') // Email will appear before password
->field('phone')
->type('string')
->label('Phone')
->moveBefore('address') // Phone will appear before address
Complete Example
namespace Modules\Posts;
use App\Abstracts\AbstractController;
use App\{Response, Route};
use Builders\FormBuilder;
class PostsController extends AbstractController
{
public function edit() {
$response = $this->getCommonData();
$response['form'] = FormBuilder::create($this->model, $this->page)
// Modify existing fields from the Model
->field('title')
->label('Post Title')
->required()
->errorMessage('Title is required')
->helpText('Enter a catchy title for your post')
->field('content')
->formType('editor')
->label('Post Content')
->required()
->field('status')
->formType('select')
->options([
'draft' => 'Draft',
'published' => 'Published',
'archived' => 'Archived'
])
->value('draft')
// Create a new field not present in the Model
->field('excerpt')
->type('text')
->formType('textarea')
->label('Excerpt')
->helpText('Brief summary of the post content')
->moveBefore('content')
->field('created_at')
->readonly()
->addStandardActions()
->getForm();
$response['title'] = 'Edit Post';
Response::render(__DIR__ . '/Views/edit_page.php', $response);
}
}
Additional Methods
Adding New Fields with addField()
The addField() method allows you to add a new field programmatically, specifying all properties in a single options array.
Syntax:
->addField(string $field_name, string $type, array $options = [])
Parameters:
$field_name: Name of the field to add$type: Data type (string, int, date, datetime, bool, etc.)$options: Array with all field configurations (label, form-type, required, options, etc.)
To position the field, use ->before('field_name') or ->after('field_name') in the chain.
Basic Example:
// Adds a simple text field at the end of the form
->addField('phone', 'string', [
'label' => 'Phone Number',
'form-type' => 'text',
'required' => true,
'form-params' => [
'help-text' => 'Format: +39 123 456 7890'
]
])
Example with Positioning:
// Adds a select field and moves it before the 'status' field
->addField('priority', 'int', [
'label' => 'Priority',
'form-type' => 'select',
'options' => [
1 => 'Low',
2 => 'Medium',
3 => 'High',
4 => 'Critical'
],
'default' => 2
])->before('status')
Complete Example with All Options:
->addField('custom_field', 'string', [
'label' => 'Custom Field',
'form-type' => 'textarea',
'required' => true,
'default' => '',
'form-params' => [
'help-text' => 'Enter your custom content here',
'class' => 'custom-textarea',
'rows' => 5,
'readonly' => false,
'disabled' => false,
'invalid-feedback' => 'This field is required'
]
])->before('content')
Difference between addField() and field():
field(): Fluent approach with method chaining. Ideal for step-by-step configurationsaddField(): Complete configuration in a single array. Ideal for adding fields in loops or when you already have all configurations in an array
Modifying Existing Fields with modifyField()
The modifyField() method allows you to modify an existing field by merging new options with existing ones, and optionally repositioning it.
Syntax:
->modifyField(string $field_name, array $options, string $position_before = '')
Parameters:
$field_name: Name of the field to modify$options: Array with properties to modify or add (will be merged with existing properties)$position_before: (Optional) Name of the field before which to move the modified field
Basic Example:
// Modifies the label and makes an existing field required
->modifyField('email', [
'label' => 'Email Address',
'required' => true
])
Example with Repositioning:
// Modifies a field and moves it before 'password'
->modifyField('email', [
'label' => 'User Email',
'form-params' => [
'help-text' => 'This will be your login username'
]
], 'password')
Example: Changing a Field from Text to Select:
// Transforms the 'status' field into a select with options
->modifyField('status', [
'form-type' => 'select',
'options' => [
'draft' => 'Draft',
'published' => 'Published',
'archived' => 'Archived'
]
])
Example: Adding Help Text and Validation:
// Adds help text and custom error message
->modifyField('phone', [
'form-params' => [
'help-text' => 'Format: +39 123 456 7890',
'invalid-feedback' => 'Please enter a valid phone number',
'pattern' => '^\+?[0-9\s]+$'
]
])
Difference between modifyField() and field():
field(): Creates the field if it doesn't exist, otherwise modifies it. Fluent approachmodifyField(): Only modifies existing fields. Allows merging complex arrays and repositioning in a single call
Removing Fields
->removeField('created_at')
->removeField('updated_at')
Field Order
->fieldOrder(['id', 'title', 'content', 'status'])
Conditional Visibility
->showIf('publish_date', '[status] == "published"')