moirei/fields

A simple package for code-defined application inputs & fields.

1.1.1 2022-09-10 00:40 UTC

This package is auto-updated.

Last update: 2024-04-10 04:00:30 UTC


README

This package provides a simple solution for working with backend defined fields. Use cases:

  • Backend defined forms fields
  • Defined survey questionnaire with strict input types and valid values
  • Define configuration application settings options with default values
  • Fetch form data (including input type, validation rules, etc) from the backend for frontend display.

Notes

  • This package was inspired by Laravel Nova fields.
  • Field properties are aimed to be consistent with Vuetify form input component properties.
$field = Boolean::make('Enable notification')->default(false);

Installation

composer require moirei/fields

Usage

use MOIREI\Fields\Inputs\Field;
use MOIREI\Fields\Inputs\{Text, Number, Select, Radio, Textarea};
...

$survey_questions = [
    Text::make('Whats your name?', 'name')
        ->rules('max:24')
        ->placeholder('John Doe')
        ->toArray(),

    Number::make('How old are you?', 'age')
        ->min(18)
        ->toArray(),

    Select::make('Gender')
        ->options([
            'Fridge',
            'Bridge',
            [ 'text' => 'I prefer not to say', 'value' => 'other' ],
        ])
        ->default('other')
        ->toArray(),

    Radio::make('Can keep you data for future promos?', 'subscribe')
        ->trueValue('Yes plez')
        ->falseValue('No thanks')
        ->toArray(),

    Textarea::make('More about yourself?', 'more')
        ->rows(10)
        ->hint('In a few words. Feel free to elaborate on the above.')
        ->persistentHint()
        ->toArray(),
];

Validation

$field = Text::make('Whats your name?', 'name')
        ->rules('max:24')
        ->placeholder('John Doe');

$valid = $field->validate('James Bond');
// or assert and throw exception
$field->validate('James Bond', true)

Validate multiple values

$fields = [
    Text::make('Whats your name?', 'name')
        ->rules('max:24')
        ->placeholder('John Doe'),
    ...
];

$returnOnlyValidated = true;

$input = Field::validateInput($request->all(), $fields, $returnOnlyValidated)

Tests

composer test