Fields

Defining Fields

Each Lamotivo resource has a fields method. This method returns an array of fields. Lamotivo offers a variety of fields.

Lamotivo fields are used to retrieve data from the model for both index and form pages.

To add a field to a resource, you need to add it to resource's fields method. Fields may be created usign the static make method. The method accepts several arguments, but you usually only need to pass the model attribute name. Lamotivo will automatically convert it to human readable string.

use Anyspin\Lamotivo\Fields\ID;
use Anyspin\Lamotivo\Fields\Text;

/**
 * Get the fields for the resource.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function fields(Request $request)
{
    return [
        ID::make()->sortable(),
        Text::make('name'),
    ];
}

If necessary, you may pass the human readable string as the second argument to the field's make method:

Text::make('name', 'Customer Name'),

Visibility of Fields

A resource has a few screen modes to render: index listing, details (preview), creation and update forms.

Almost every field of a resource is shown in all screens by default. But sometimes you may wish to show some fields only on certain screens.

The following methods are to show or hide fields:

  • showOnIndex()
  • showOnDetails()
  • showOnCreating()
  • showOnUpdating()
  • hideFromIndex()
  • hideFromDetails()
  • hideWhenCreating()
  • hideWhenUpdating()
  • onlyOnIndex()
  • onlyOnDetails()
  • onlyOnForms()
  • exceptOnForms()

You may chain the methods onto your field in order to instruct Lamotivo where the field should be displayed:

Text::make('name')->hideFromIndex(),

Sortable Fields

When you add a field to a resource, you may us the field's sortable method to indicate that the resource index may be sorted by the given field:

Text::make('name')->sortable(),

Field Types

Lamotivo offers a variety of field types.

Avatar Field

The Avatar field extends the Image field and accepts the same options and configuration:

use Anyspin\Lamotivo\Fields\Avatar;

Avatar::make('avatar'),

If a resource contains an Avatar field, that field will be displayed next to the resource's title when the resource is displayed in global search results.

BasicFile Field

Files are handled with the lamotivo/uploads package. The provided column name is the partial path to a file on the disk.

use Anyspin\Lamotivo\Fields\BasicFile;

BasicFile::make('avatar_url'),

You may define a disk, valid extensions, the max file size (in kilobytes) and the path to store the file:

BasicFile::make('document_url')
    ->extensions('doc,docx,pdf')
    ->disk('public')
    ->maxSize(1024)
    ->path('docs'),

Boolean Field

The Boolean field may be used to represent a boolean column in your database. For example, assuming your database has a boolean column named is_active, you may attach a Boolean field to your resource like so:

use Anyspin\Lamotivo\Fields\Boolean;

Boolean::make('is_active'),

Lamotivo uses values 1, or 0 to represent true and false. If you would like to use the custom values, chain the trueValue and falseValue methods onto your field:

Boolean::make('is_active')
    ->trueValue('Yes')
    ->falseValue('No'),

You may customize the label for the rendered checkbox using the field's checkboxLabel method:

Boolean::make('is_active')
    ->checkboxLabel('Activated'),

Code Field

The Code fields provides a code editor. Generally, code fields should be attached to TEXT database columns.

use Anyspin\Lamotivo\Fields\Code;

Code::make('custom_js'),

By default, Lamotivo will never display a Code field on a resource index listing.

You may customize the language syntax highlighting of the Code field chaining the following methods:

  • css()
  • html()
  • javascript()
  • js()
  • json()
  • markdown()
  • nginx()
  • php()
  • sass()
  • xml()
  • yaml()
use Anyspin\Lamotivo\Fields\Code;

Code::make('attributes')->json(),

Some additional methods to setup the code editor:

  • indentUnit(4)
  • tabSize(4)
  • indentWithTabs(false)
  • wrapLines(true)
  • lineNumbers(true)
  • allowDropFileTypes(['application/json'])

This field type is always hidden from the resource's index screen.

Country Field

The Country fields generates a list of the world's countries. The field operates with the two-letter code of a country.

The list of country names will be localized and sorted alphabetically.

use Anyspin\Lamotivo\Fields\Country;

Country::make('country'),

You may restrict the list by using the countries method with the accurate list:

Country::make('country')->countries(['US', 'GB', 'FR', 'RU', 'CN']),

If you wish to restrict the list globally, define the list using the setDefaultCountryList static method:

Country::setDefaultCountryList(['US', 'GB', 'FR', 'RU', 'CN']),

Sometimes, you may want to show a country code instead of the name on the index page to save space. Use the abbreviateOnIndex method to achieve this:

Country::make('country')->abbreviateOnIndex(),

Currency Field

The Currency field generates a Number field with currency symbol:

use Anyspin\Lamotivo\Fields\Currency;

Currency::make('price'),

Date Field

The Date field may be used to store a date value.

use Anyspin\Lamotivo\Fields\Date;

Date::make('shipped_at'),

You may customize the display format of your Date fields using the format method. The format must be a format supported by Angular.js:

Date::make('shipped_at')->format('fullDate'),

DateTime Field

The DateTime field may be used to store a datetime value.

use Anyspin\Lamotivo\Fields\Date;

Date::make('shipped_at'),

You may customize the display format of your Date fields using the format method. The format must be a format supported by Angular.js:

Date::make('shipped_at')->format('fullDate'),

File Field

Files are handled with the lamotivo/uploads package. The provided column name is not a real column in fact, it is a relation name, that belongs to an attachment model. Your resource model must have the id foreign field, e.g. attachment_id.

use Anyspin\Lamotivo\Fields\File;

File::make('attachment'),

Hidden Field

The Hidden field may be used to pass any value that doesn't need to be changed and even visible but is required for saving:

use Illuminate\Support\Str;
use Anyspin\Lamotivo\Fields\Hidden;

Hidden::make('uuid')->initUsing(function($request) {
    return (string)Str::uuid();
}),

The fillUsing method allows you to fill a value when saving:

use Illuminate\Support\Str;
use Anyspin\Lamotivo\Fields\Hidden;

Hidden::make('slug')->fillUsing(function($request, $model, $column, $value) {
    if (!$model->slug && $request->has('name')
    {
        $model->slug = Str::slug($request->get('name'));
    }
}),

ID Field

The ID field represents the primary key of your resource's database table. By default, the ID field assumes the underlying database column is named id:

use Anyspin\Lamotivo\Fields\ID;

ID::make(),

Image Field

The Image field extends the File field and accepts the same options and configurations. The Image field, unlike the File field, will display a thumbnail preview of the underlying image when viewing the resource:

use Anyspin\Lamotivo\Fields\Image;

Image::make('photo'),

Number Field

The Number field provides an input control with a type attribute of number:

use Anyspin\Lamotivo\Fields\Number;

Number::make('amount'),

You may use the min, max, and step methods to set their corresponding attributes on the generated input control:

Number::make('amount')->min(1)->max(1000)->step(0.1),

The Number field allows you to specify the unit of measurement using the unit method:

Number::make('weight')->unit('kg'),

If necessary, you may add the unit converter which allows the user convert values on the fly:

Number::make('weight')->unit('kg')->withConverter(),

Optionally, you may pass the convertation unit as the first argument:

Number::make('weight')->unit('kg')->withConverter('g'),

The list of supported units:

  • Units of weight (mass):

    • gram (g)
    • milligram (mg)
    • kilogram (kg)
    • tonne (t)
    • ounce (oz)
    • pound (lb)
    • stone (st)
  • Units of length:

    • centimeter (cm)
    • foot (ft, feet)
    • inch (in, inches)
    • mile (mi, miles)
    • mile-scandinavian (smi)
    • millimeter (mm)
    • kilometer (km)
    • meter (m)
    • yard (yd)
  • Units of speed:

    • kilometer-per-hour (km/h)
    • meter-per-second (m/s)
    • mile-per-hour (mph)
  • Units of area:

    • acre (ac)
    • hectare (ha)
    • square-centimeter (sq.cm, cm2)
    • square-meter (sq.m, m2)
    • square-kilometer (sq.km, km2)
    • square-inch (sq.in, in2)
    • square-foot (sq.ft, ft2)
    • square-yard (sq.yd, yd2)
    • square-mile (sq.mi, mi2)
  • Units of volume:

    • fluid-ounce (fl oz)
    • gallon (gal)
    • liter (L, l)
    • milliliter (ml, mL)
    • cubic-meter (m3)
    • cubic-kilometer (km3)
    • cubic-centimeter (cm3)
    • cubic-inch (in3)
  • Units of duration (time):

    • day (d, days)
    • hour (hr, hrs, hours)
    • microsecond (us)
    • millisecond (ms)
    • minute (min, mins, minutes)
    • month (mth, mths, months, mo)
    • nanosecond (ns)
    • second (s, sec)
    • week (wk, wks, weeks)
    • year (yr, yrs, years)
  • Units of temperature:

    • celsius
    • fahrenheit
  • Units of information (digital data):

    • bit (b)
    • byte (B, o)
    • gigabit (Gb, Gbit)
    • gigabyte (GB, Go)
    • kilobit (kb, kbit)
    • kilobyte (kB, ko)
    • megabit (Mb, Mbit)
    • megabyte (Mb, Mo)
    • petabyte (Pb, Po)
    • terabit (Tb, Tbit)
    • terabyte (TB, To)
  • Units of bitrate (data bitrate):

    • bit-per-second
    • byte-per-second
    • gigabit-per-second (Gbps)
    • gigabyte-per-second
    • kilobit-per-second (kbps)
    • kilobyte-per-second
    • megabit-per-second (Mbps)
    • megabyte-per-second
    • terabit-per-second
    • terabyte-per-second
  • Angle unit:

    • degree
  • Percent:

    • percent

For convenience, Lamotivo provides methods to specify the measurement with an optional unit:

  • length($unit = null)
  • area($unit = null)
  • speed($unit = null)
  • weight($unit = null), mass($unit = null)
  • volume($unit = null)
  • information($unit = null)
  • bitrate($unit = null)
  • duration($unit = null)
  • temperature($unit = null)
  • percent($unit = null)
  • degree($unit = null)

If the unit is omitted, the default unit is used for the selected measurement.

You may also customize the default units for measurements:

  • Number::setPrimaryLengthUnit($unit)
  • Number::setPrimaryAreaUnit($unit)
  • Number::setPrimarySpeedUnit($unit)
  • Number::setPrimaryVolumeUnit($unit)
  • Number::setPrimaryWeightUnit($unit)
  • Number::setPrimaryInformationUnit($unit)
  • Number::setPrimaryDurationUnit($unit)
  • Number::setPrimaryTemperatureUnit($unit)

Lamotivo also provides shortcut methods for commonly used units:

  • meters()
  • centimeters()
  • millimeters()
  • kilometers()
  • feet()
  • inches()
  • miles()
  • milesPerHour()
  • kilometersPerHour()
  • metersPerSecond()
  • grams()
  • kilograms()
  • ounces()
  • pounds()
  • liters()
  • milliliters()
  • flOz(), fluidOunces()
  • bytes()
  • kilobytes()
  • megabytes()
  • gigabytes()
  • kbps()
  • mbps()
  • minutes()
  • hours()
  • days()
  • weeks()
  • months()
  • years()
  • celsius()
  • fahrenheit()

Password Field

The Password field provides an input control with a type attribute of password:

use Anyspin\Lamotivo\Fields\Password;

Password::make('password'),

The Password field will automatically preserve the password that is currently stored in the database if the incoming password field is empty.

Select Field

The Select field may be used to generate a drop-down select menu. The select menu's options may be defined using the options method:

use Anyspin\Lamotivo\Fields\Select;

Select::make('size')->options([
    's' => 'Small',
    'm' => 'Medium',
    'l' => 'Large',
]),

Status Field

The Status field extends the Select field and may be used to display a "progress state" column.

The loadingWhen and failedWhen methods may be used to instruct the field which words indicate a "loading" state and which words indicate a "failed" state. In this example, we will indicate that database column values of waiting or running should display a "loading" indicator:

use Anyspin\Lamotivo\Fields\Status;

Status::make('status')
    ->loadingWhen(['waiting', 'running'])
    ->failedWhen(['failed']),

Text Field

The Text field provides an input control with a type attribute of text:

use Anyspin\Lamotivo\Fields\Text;

Text::make('name'),

The Text field also supports some special methods on the resource's index screen:

Text::make('name')
    ->wraps() // allows the value to be wrapped
    ->limitTo(20), // limits the value to only 20 characters in length

Textarea Field

The Textarea field provides a textarea control:

use Anyspin\Lamotivo\Fields\Textarea;

Textarea::make('bio'),

Textarea may have an auto height mode:

Textarea::make('bio')
    ->autoheight(),

The Textarea field also supports some special methods on the resource's index screen:

Textarea::make('bio')
    ->wraps() // allows the value to be wrapped
    ->limitTo(20), // limits the value to only 20 characters in length

TextEditor Field

The TextEditor field provides a WYSIWYG Textangular editor. Typically, this field will correspond to a TEXT column in your database.

use Anyspin\Lamotivo\Fields\TextEditor;

Texteditor::make('biography'),

This field type is always hidden from the resource's index screen.

Customization

Readonly Fields

There are times where you may want to allow the user to only create and update certain fields on a resource. You can do this by using the readonly() or disabled() method on the field, which will disable the field's corresponding input:

Text::make('email')->readonly(),

Required Fields

Text::make('email')->rules('required'),

Default Values

Text::make('type')->default('customer'),

If you would like to fill the default value dynamically, you may use the initUsing method:

Date::make('date')->initUsing(function($request) {
    return now();
}),

Field Resolution and Displaying

The resolveUsing method allows you to customize the format of a value:

Date::make('date')->resolveUsing(function($value) {
    return $value->getTimestamp();
}),

The displayUsing method allows you to customize the display format of a value on index listing and details view:

Text::make('uin')->displayUsing(function($value) {
    return mb_strtoupper($value);
}),

Virtual Fields

Sometimes you have to display an attribute that is not associated with a database column. You may compute the value on the fly:

Text::make('page_url')->asVirtual()->displayUsing(function() {
    return route('page', $this->slug);
}),

The callable is bound to your Eloquent model, so you can call $this to access attributes of your model directly.

Request Transformation

When saving a model, you may customize the form value:

Text::make('uin')->transformRequest(function($request, $value) {
    return mb_strtotupper($value);
}),

If you would like to fill the model more granularly, you should use the fillUsing method.

Text::make('uin')->fillUsing(function($request, $model, $column, $value) {
    $model->{$column} = mb_strtotupper($value);
}),

Text Prepending and Appending

Text::make('email')
    ->prepend('<span class="fa fa-envelope"></span>'),

Text::make('amount')
    ->append('pcs'),

Placeholder

Text::make('email')
    ->placeholder('Customer email'),

Comment

The field label may have a comment from below.

Text::make('token')
    ->comment('An API token to use'),

Help Text

The field control may have a help text from below.

Text::make('token')
    ->help('An API token to use'),