Use of form fields

There are a number of form components built into model-form to help you build form forms quickly.

Public methods

Set the value of the form (value)

  1. $form->text('title')->value('text...');

Set default values (default)

  1. $form->text('title')->default('text...');

Set default (default)This method is only available on add a page, if the edit page also needs to set the default value, you can refer to the following method.

  1. $form->text('xxx')->default('default value', true);

Set up a message (help)

  1. $form->text('title')->help('help...');

Set attribute

  1. $form->text('title')->attribute(['data-title' => 'title...']);
  2. $form->text('title')->attribute('data-title', 'title...');

Set as required

  1. $form->text('title')->required();
  2. // The "*" is not displayed.
  3. $form->text('title')->required(false);

Set to uneditable (disable)

  1. $form->text('title')->disable();

Setting the placeholder

  1. $form->text('title')->placeholder('Please enter...');

Set the width

  1. $form->text('title')->width(8, 2);

Set validation rules

See form validation for more details.

Modify form input values to be saved (saving)

The saving method allows you to change the format of the data to be saved.

  1. use Dcat\Admin\Support\Helper;
  2. $form->multipleFile('files')->saving(function ($paths) {
  3. $paths = Helper::array($paths);
  4. // Get other fields of the current row of the database
  5. $username = $this->username;
  6. // Final conversion to json to save to database
  7. return json_encode($paths);
  8. });

Modify form data display (customFormat)

The customFormat method can be used to change the value of a field injected into the form from an external source.

In the example below, the multiFile field requires the field values to be rendered in array format, and we can convert the field values from the database to array format using the customFormat method

  1. use Dcat\Admin\Support\Helper;
  2. $form->multipleFile('files')->saving(function ($paths) {
  3. $paths = Helper::array($paths);
  4. return json_encode($paths);
  5. })->customFormat(function ($paths) {
  6. // Get other fields of the current row of the database
  7. $username = $this->username;
  8. // convert to arrays
  9. return Helper::array($paths);
  10. });

Hide in pop-ups

If you don’t want to display a field in the popup, you can use the Form\Field::hideInDialog method

  1. $form->display('id');
  2. $form->text('title');
  3. $form->textarea('contents')->hideInDialog();

Save as string type saveAsString

The saveAsString method converts the form value to a string type for saving, which is useful when the saved database field value is not allowed to be null.

  1. $form->text('nickname')->saveAsString();

Save as json type saveAsJson

saveAsJson can save form values in json format

  1. $form->text('nickname')->saveAsJson();

Text (text)

  1. $form->text($column, [$label]);
  2. // 添加提交验证规则
  3. $form->text($column, [$label])->rules('required|min:10');

Hide field (hidden)

The hidden method allows you to set a hidden field for your form.

  1. $form->hidden('author_id')->value(Admin::user()->getKey());

can often be used in conjunction with the saving event

  1. $form->hidden('author_id');
  2. $form->saving(function (Form $form) {
  3. $form->author_id = Admin::user()->getKey();
  4. });

Drop-down box radio (select)

  1. $form->select($column[, $label])->options([1 => 'foo', 2 => 'bar', 'val' => 'Option name']);

Or get a list of options from api:

  1. $form->select($column[, $label])->options('/api/users');
  2. // Use ajax and display the selected item
  3. $form->select($column[, $label])->options(Model::class)->ajax('/api/users');
  4. // or assign a name and ID
  5. $form->select($column[, $label])->options(Model::class, 'name', 'id')->ajax('/api/users');

where the format of the api interface must be in the following format:

  1. [
  2. {
  3. "id": 9,
  4. "text": "xxx"
  5. },
  6. {
  7. "id": 21,
  8. "text": "xxx"
  9. },
  10. ...
  11. ]

If there are too many options, you can dynamically page-load options via ajax:

  1. $form->select('user_id')->options(function ($id) {
  2. $user = User::find($id);
  3. if ($user) {
  4. return [$user->id => $user->name];
  5. }
  6. })->ajax('api/users');

To load data during editing using the model method:

  1. $form->select('user_id')->model(User::class, 'id', 'name');

The code above is the same as the one below:

  1. $form->select('user_id')->options(function ($id) {
  2. $user = User::find($id);
  3. if ($user) {
  4. return [$user->id => $user->name];
  5. }
  6. });

API code for the /admin/api/users interface:

  1. public function users(Request $request)
  2. {
  3. $q = $request->get('q');
  4. return User::where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
  5. }

The data structure returned by the interface is

  1. {
  2. "total": 4,
  3. "per_page": 15,
  4. "current_page": 1,
  5. "last_page": 1,
  6. "next_page_url": null,
  7. "prev_page_url": null,
  8. "from": 1,
  9. "to": 3,
  10. "data": [
  11. {
  12. "id": 9,
  13. "text": "xxx"
  14. },
  15. {
  16. "id": 21,
  17. "text": "xxx"
  18. },
  19. {
  20. "id": 42,
  21. "text": "xxx"
  22. },
  23. {
  24. "id": 48,
  25. "text": "xxx"
  26. }
  27. ]
  28. }

Dropdown checkbox linkage (load)

The select component supports unidirectional linkage of parent-child relationships.

  1. $form->select('province')->options(...)->load('city', '/api/city');
  2. $form->select('city');

Where load('city', '/api/city'); means that after the current select option is switched, the value of the current option will be taken through the parameter q, calling the interface /api/city, and the data returned by api will be populated into the options of the city selection box, where the format of the data returned by api/api/city must match:

  1. [
  2. {
  3. "id": 9,
  4. "text": "xxx"
  5. },
  6. {
  7. "id": 21,
  8. "text": "xxx"
  9. },
  10. ...
  11. ]

The sample code for controller action is as follows:

  1. public function city(Request $request)
  2. {
  3. $provinceId = $request->get('q');
  4. return ChinaArea::city()->where('parent_id', $provinceId)->get(['id', DB::raw('name as text')]);
  5. }

selectTable, multipleSelectTable, radio, checkbox can also use the load method to link select and multipleSelect forms, the usage is the same as the above example.

Linking multiple fields (loads)

Multiple fields can be linked using the loads method, which is used as follows

  1. $form->select('status')
  2. ->options(...)
  3. ->loads(['field1', 'field2'], ['/api/field1', '/api/field2']);
  4. $form->select('field1');
  5. $form->select('field2');

The data format returned by api is consistent with the load method. selectTable, multiSelectTable, radio, checkbox can also be linked using the loads method.

MultiSelect dropdown boxes (multipleSelect)

{tip} The data injected into this field (from the database) can be a string separated by ,, a json string or an array of array.

  1. $form->multipleSelect($column[, $label])
  2. ->options([1 => 'foo', 2 => 'bar', 'val' => 'Option name'])
  3. ->saving(function ($value) {
  4. // Convert to a json string to save to a database
  5. return json_encode($value);
  6. });
  7. // Using ajax and displaying the selected item:
  8. $form->multipleSelect($column[, $label])->options(Model::class)->ajax('ajax_url');
  9. // or assign a name and ID
  10. $form->multipleSelect($column[, $label])->options(Model::class, 'name', 'id')->ajax('ajax_url');

The multiple choice box can handle two cases, the first being the ManyToMany relationship

  1. class Post extends Models
  2. {
  3. public function tags()
  4. {
  5. return $this->belongsToMany(Tag::class);
  6. }
  7. }
  8. return Form::make(Post::with('tags'), function (Form $form) {
  9. ...
  10. $form->multipleSelect('tags')
  11. ->options(Tag::all()->pluck('name', 'id'))
  12. ->customFormat(function ($v) {
  13. if (! $v) {
  14. return [];
  15. }
  16. // Converted to IDs from a two-dimensional array of database lookups
  17. return array_column($v, 'id');
  18. });
  19. });

The second is to store an array of options in a single field. If the field is a string, then you need to define accessors and modifiers for the field inside the model to store and read it.

If there are too many options, you can dynamically page-load options via ajax:

  1. $form->select('friends')->options(function ($ids) {
  2. return User::find($ids)->pluck('name', 'id');
  3. })->ajax('api/users');

API code for the /admin/api/users interface:

  1. public function users(Request $request)
  2. {
  3. $q = $request->get('q');
  4. return User::where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
  5. }

The data structure returned by the interface is

  1. {
  2. "total": 4,
  3. "per_page": 15,
  4. "current_page": 1,
  5. "last_page": 1,
  6. "next_page_url": null,
  7. "prev_page_url": null,
  8. "from": 1,
  9. "to": 3,
  10. "data": [
  11. {
  12. "id": 9,
  13. "text": "xxx"
  14. },
  15. {
  16. "id": 21,
  17. "text": "xxx"
  18. },
  19. {
  20. "id": 42,
  21. "text": "xxx"
  22. },
  23. {
  24. "id": 48,
  25. "text": "xxx"
  26. }
  27. ]
  28. }

Table selector (selectTable)

  1. use App\Admin\Renderable\UserTable;
  2. use Dcat\Admin\Models\Administrator;
  3. $form->selectTable($field)
  4. ->title('Pop-up window TITLE')
  5. ->dialogWidth('50%') // Popup width, default 800px
  6. ->from(UserTable::make(['id' => $form->getKey()])) // Set the rendering class instance and pass custom parameters
  7. ->model(Administrator::class, 'id', 'name'); // Set the display of editing data
  8. // The above code is equivalent to
  9. $form->selectTable($field)
  10. ->from(UserTable::make(['id' => $form->getKey()])) // Set the rendering class instance and pass custom parameters
  11. ->options(function ($v) { // Set the display of editing data
  12. if (! $v) {
  13. return [];
  14. }
  15. return Administrator::find($v)->pluck('name', 'id');
  16. });

Define the rendering class as follows, which needs to inherit Dcat\Admin\Grid\LazyRenderable.

{tip} The data table is loaded asynchronously, please refer to load asynchronously for more details.

  1. <?php
  2. namespace App\Admin\Renderable;
  3. use Dcat\Admin\Grid;
  4. use Dcat\Admin\Grid\LazyRenderable;
  5. use Dcat\Admin\Models\Administrator;
  6. class UserTable extends LazyRenderable
  7. {
  8. public function grid(): Grid
  9. {
  10. // Getting externally passed parameters
  11. $id = $this->id;
  12. return Grid::make(Administrator::where('xxx_id', $id), function (Grid $grid) {
  13. $grid->column('id');
  14. $grid->column('username');
  15. $grid->column('name');
  16. $grid->column('created_at');
  17. $grid->column('updated_at');
  18. $grid->quickSearch(['id', 'username', 'name']);
  19. $grid->paginate(10);
  20. $grid->disableActions();
  21. $grid->filter(function (Grid\Filter $filter) {
  22. $filter->like('username')->width(4);
  23. $filter->like('name')->width(4);
  24. });
  25. });
  26. }
  27. }

result

Use of form fields - 图1

Set the fields that will be saved to the form and displayed when selected

  1. $form->selectTable($field)
  2. ->from(UserTable::make(['id' => $form->getKey()]))
  3. ->options(function ($v) { // set edit data to display
  4. if (! $v) {
  5. return [];
  6. }
  7. return Administrator::find($v)->pluck('name', 'id');
  8. })
  9. ->pluck('name', 'id'); // the first parameter is the field to be displayed, the second parameter is the field that will be saved to the form when selected
  10. // The above code can also be simplified to
  11. $form->selectTable($field)
  12. ->from(UserTable::make(['id' => $form->getKey()]))
  13. ->model(Administrator::class, 'id', 'name'); // set edit data to display

Multiple Selection (multipleSelectTable)

The usage of multiple choice is the same as the above selectTable method.

  1. $form->multipleSelectTable($field)
  2. ->max(10) // 最多选择 10 个选项,不传则不限制
  3. ->from(UserTable::make(['id' => $form->getKey()])) // Set the rendering class instance and pass custom parameters
  4. ->model(Administrator::class, 'id', 'name') // Set the display of editing data
  5. ->saving(function ($v) {
  6. // $v is the value of the form submission field, the default is an array type, here you need to convert it manually.
  7. // Save as a string separated by "," and do not convert if it is a many-to-many relationship.
  8. return implode(',', $v);
  9. });

multiple choice box (listbox)

The method is similar to multipleSelect.

{tip} The data injected into this field (from the database) can be a string separated by ,, a json string or an array of array.

  1. $form->listbox($column[, $label])->options([1 => 'foo', 2 => 'bar', 'val' => 'Option name']);

Long text (textarea)

  1. $form->textarea($column[, $label])->rows(10);

Single choice (radio)

  1. $form->radio($column[, $label])->options(['m' => 'Female', 'f'=> 'Male'])->default('m');

Multiple choice (checkbox)

options() method is used to set the selection:

  1. $form->checkbox($column[, $label])
  2. ->options([1 => 'foo', 2 => 'bar', 'val' => 'Option name'])
  3. ->saving(function ($value) {
  4. // Convert to a json string to save to a database
  5. return json_encode($value);
  6. });

Enable Select All

  1. $form->checkbox('column')->canCheckAll();

</a

autocomplete

This form allows you to search for form values while filling out the form and display the results in a dropdown list, as follows

  1. $form->autocomplete($column[, $label])->options(['foo', 'bar', ...]) ;
  2. // Set the group name
  3. $form->autocomplete($column[, $label])->groups([
  4. [
  5. 'label' => 'group name',
  6. 'options' => ['foo', 'bar', ...] ,
  7. ],
  8. ]);

The effect is as follows !

Fetching data from remote APIs

It is also possible to fetch data from a remote API

  1. // the first parameter of the ajax function is the ajax url, the second parameter is the valueField (optional), and the third parameter is the groupField (optional)
  2. $form->autocomplete($column[, $label])->ajax('/countries', 'name', 'region');

The remote API server-side request parameter is query, and the sample code is as follows

  1. class CountryController extends AdminController
  2. {
  3. public function search()
  4. {
  5. $countries = Country::when(request('query'), function ($query, $value) {
  6. $query->where('name', 'like', "%{$value}%");
  7. })->get();
  8. return Admin::json($countries->toArray());
  9. }
  10. }

Custom autocomplete settings.

For detailed settings, see: devbridge/jQuery-Autocomplete

  1. $js = <<<JS
  2. function (suggestion) {
  3. alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
  4. }
  5. JS;
  6. $form->autocomplete($column[, $label])->configs([
  7. 'minChars' => 5,
  8. 'noCache' => true,
  9. 'onSelect' => JavaScript::make($js),
  10. ]);

configs also supports closures.

  1. $form->autocomplete($column[, $label])->configs(function($model, $value){
  2. return [
  3. ....
  4. ];
  5. });

Form linkage

The linkage logic of autocomplete is just the opposite of select’s. depends needs to be written to the affected field, regardless of the parent field type, and the value of the parent field will be uploaded to the API at the same time.

  1. $form->select('region')->options([
  2. 'asia',
  3. 'Africa',
  4. 'America',
  5. 'Europe',
  6. ]);
  7. $form->autocomplete('country')->ajax('/countries', 'name', 'region');
  8. // A request for /states?query={query}&region={region}&country={country} will be sent
  9. $form->autocomplete('addr')->ajax('/states', 'name')->depends(['region', 'country']);

Email (email)

  1. $form->email($column[, $label]);

Password (password)

  1. $form->password($column[, $label]);

Links (url)

  1. $form->url($column[, $label]);

IP address (ip)

  1. $form->ip($column[, $label]);

Mobile (mobile)

  1. $form->mobile($column[, $label])->options(['mask' => '999 9999 9999']);

Color picker (color)

  1. $form->color($column[, $label]);

Time (time)

  1. $form->time($column[, $label]);
  2. // Set the time format, see http://momentjs.com/docs/#/displaying/format/ for more formats.
  3. $form->time($column[, $label])->format('HH:mm:ss');

Date (date)

  1. $form->date($column[, $label]);
  2. // Set the date format, see http://momentjs.com/docs/#/displaying/format/ for more formats.
  3. $form->date($column[, $label])->format('YYYY-MM-DD');

Date and time (datetime)

  1. $form->datetime($column[, $label]);
  2. // Set the date format, see http://momentjs.com/docs/#/displaying/format/ for more formats.
  3. $form->datetime($column[, $label])->format('YYYY-MM-DD HH:mm:ss');

timeRange

$startTime and $endTime are the start and end time fields:

  1. $form->timeRange($startTime, $endTime, 'Time Range');

Date Range (dateRange)

$startDate and $endDate are the start and end date fields:

  1. $form->dateRange($startDate, $endDate, 'Date Range');

time and date range (datetimeRange)

$startDateTime, $endDateTime are the start and end time dates:

  1. $form->datetimeRange($startDateTime, $endDateTime, 'DateTime Range');

Scope (range)

  1. $form->range('start_column', 'end_column', '范围');

File upload (file)

Before you can use the file upload function, you need to complete the upload configuration first. For file upload configuration and built-in methods, see: Image/File Upload.

The file upload directory is configured in the upload.file file in the config/admin.php file, if the directory does not exist, you need to create the directory and open write permissions.

{tip} Please do not set the accessor and modifier splicing domain name in the file or image upload form fields in the model, refer to File/Image Domain Name Splicing for related requirements.

  1. $form->file($column[, $label]);
  2. // Change the file upload path and file name.
  3. $form->file($column[, $label])->move($dir, $name);
  4. // and set the upload file type.
  5. $form->file($column[, $label])->rules('mimes:doc,docx,xlsx');
  6. // Add file delete button
  7. $form->file($column[, $label])->removable();

Image upload (image)

Before using the image upload function, you need to complete the upload configuration first. For image upload configuration and built-in methods, please refer to:image/file upload.

The image upload directory is configured in the file upload.image in the config/admin.php file; if the directory does not exist, it needs to be created with open write permissions.

Compression, cropping, watermarking, etc. can be used in various ways, requiring intervention/image to be installed.

For more information, please refer to [Intervention]:

{tip} Please do not set the accessor and mutator splicing domain name in the file or image upload form fields in the model, refer to File/Image Domain Name Splicing for related requirements.

  1. $form->image($column[, $label]);
  2. // Modify image upload path and file name.
  3. $form->image($column[, $label])->move($dir, $name);
  4. // Cropping pictures
  5. $form->image($column[, $label])->crop(int $width, int $height, [int $x, int $y]);
  6. // Watermarking
  7. $form->image($column[, $label])->insert($watermark, 'center');

Multiple Image and multiple file uploads (multipleImage/multipleFile)

Multi-image upload form inherits from single-image upload form, and multi-file upload form inherits from single-file upload form.

{tip} The data injected into this field (from the database) can be a string separated by ,, a json string or an array of array

  1. // Multiple pictures
  2. $form->multipleImage($column[, $label]);
  3. // Limit the maximum number of uploads
  4. $form->multipleImage($column[, $label])->limit(3);
  5. // Multiple files
  6. $form->multipleFile($column[, $label]);
  7. // Limit the maximum number of uploads
  8. $form->multipleFile($column[, $label])->limit(5);

The data submitted when multiple images/file uploads are an array array, you can change the data to the format you want before saving it into the database by:

  1. // Convert to json format and save to database
  2. $form->multipleFile($column[, $label])->saving(function ($paths) {
  3. // Can be converted to a string format separated by `,`
  4. // return implode(',', $paths);
  5. // can also be converted to json
  6. return json_encode($paths);
  7. });

Of course, if you want to save it in any other format, that’s fine, it’s just that if you want to save it in any other format, you need to convert the data to a one-dimensional array display by using the customFormat method, such as:

  1. $form->multipleFile($column[, $label])
  2. ->customFormat(function ($paths) {
  3. return collect($paths)->map(function ($value) {
  4. return explode('|', $value);
  5. })->flatten()->toArray();
  6. })
  7. ->saving(function ($paths) {
  8. return implode('|', $paths);
  9. });

Enable sortable feature

  1. $form->multipleImage('images')->sortable();

Rich Text Editor (editor)

The system integrates the TinyMCE editor as a built-in editor.

Basic Use

  1. $form->editor($column[, $label]);

to set up language packs

If you need other languages, you can set the language pack address in the following way:

  1. $form->editor('content')->languageUrl(url('TinyMCE/langs/de.js'));

Editor Configuration

For specific configuration, please refer to official document or Chinese document.

  1. <?php
  2. use Dcat\Admin\Support\JavaScript;
  3. $form->editor('content')->options([
  4. 'toolbar' => [],
  5. 'setup' => JavaScript::make(
  6. <<<JS
  7. function (editor) {
  8. console.log('The editor is initialized with success.', editor)
  9. }
  10. JS
  11. ),
  12. ]);

set height

The default value is 400

  1. $form->editor('content')->height('600');

read-only

  1. $form->editor('content')->readOnly();
  2. // 或
  3. $form->editor('content')->disable();

image upload

Set the disk configuration for image upload, which is uploaded by default to the configuration specified by admin.upload.disk.

  1. // Upload to oss
  2. $form->editor('content')->disk('oss');

Set the image upload directory to tinymce/images by default:

  1. $form->editor('content')->imageDirectory('editor/images');

Customize the upload interface, the return format of the interface needs to be {"location": "image url"}.

  1. $form->editor('content')->imageUrl('editor/upload-image');

global settings

If you need to set the editor globally, you can add the following code to app\Admin\bootstrap.php.

  1. <?php
  2. use Dcat\Admin\Form\Field\Editor;
  3. Editor::resolving(function (Editor $editor) {
  4. // Setting the default configuration
  5. $editor->options([...]);
  6. // Set the default uploading of editor images to qiniu Cloud.
  7. $editor->disk('qiniu');
  8. });

Markdown Editor (markdown)

The system integrates the editor-md editor as a built-in Markdown editor.

Basic Use

  1. $form->markdown($column[, $label]);

to set up language packs

If you need other languages, you can set the language pack address in the following way:

  1. $form->markdown('content')->languageUrl(admin_asset('@admin/dcat/plugins/editor-md/languages/zh-tw.js'));

Editor Configuration

For specific configuration, please refer to official document

  1. <?php
  2. use Dcat\Admin\Support\JavaScript;
  3. $form->markdown('content')->options([
  4. 'onpreviewing' => JavaScript::make(
  5. <<<JS
  6. function() {
  7. // console.log("onpreviewing =>", this, this.id, this.settings);
  8. // on previewing you can custom css .editormd-preview-active
  9. }
  10. JS
  11. ),
  12. ]);

set height

The default value is 500

  1. $form->markdown('content')->height('600');

read-only

  1. $form->markdown('content')->readOnly();
  2. // or
  3. $form->markdown('content')->disable();

image upload

Set the disk configuration for image upload, which is uploaded by default to the configuration specified by admin.upload.disk

  1. // Upload to oss
  2. $form->markdown('content')->disk('oss');

Set the image upload directory to markdown/images by default

  1. $form->markdown('content')->imageDirectory('markdown/images');

Customize the upload interface, the return format of the interface needs to be {"success": 1, "url": "image url" }.

  1. $form->markdown('content')->imageUrl('markdown/upload-image');

global settings

If you need to set the editor globally, you can add the following code to app\Admin\bootstrap.php.

  1. <?php
  2. use Dcat\Admin\Form\Field\Markdown;
  3. Markdown::resolving(function (Markdown $markdown) {
  4. // Setting the default configuration
  5. $markdown->options([...]);
  6. // Set the default uploading of editor images to qiniu Cloud.
  7. $markdown->disk('qiniu');
  8. });

Switch

use

  1. $form->switch($column[, $label]);

The default values of the switch form to save to the database are 1 and 0, if you need to change the value to save to the database, you can use this

  1. $form->switch($column[, $label])
  2. ->customFormat(function ($v) {
  3. return $v == 'open' ? 1 : 0;
  4. })
  5. ->saving(function ($v) {
  6. return $v ? 'open' : 'closed';
  7. });

Map (map)

Map control to select latitude and longitude, $latitude, $longitude for the latitude and longitude fields.

To use this feature you need to change the value of map_provider in the config/admin.php file (currently supported maps are: “tencent”, “google”, “yandex”). For different maps, you need to apply your own KEY and configure it in the .env file, then you need to add the following code to app/Admin/bootstrap.php.

  1. Form\Field\Map::requireAssets();

use

  1. $form->map($latitude, $longitude, $label);

Slider

Can be used for selection of numeric type fields, such as age.

  1. $form->slider($column[, $label])->options(['max' => 100, 'min' => 1, 'step' => 1, 'postfix' => 'years old']);

For more options, please refer to:https://github.com/IonDen/ion.rangeSlider#settings

Display only (display)

Only the fields are displayed and no action is taken:

  1. $form->display($column[, $label]);
  2. // More complex display
  3. $form->display($column[, $label])->with(function ($value) {
  4. return "<img src="$value" />";
  5. });

Unit symbol (currency)

  1. $form->currency($column[, $label]);
  2. // Set unit symbols
  3. $form->currency($column[, $label])->symbol('¥');

Number (number)

  1. $form->number($column[, $label]);

Rating (rate)

  1. $form->rate($column[, $label]);

Divider (divider)

  1. $form->divider();

Custom content (html)

Insert html content, parameter can be Htmlable, Renderable or a class that implements __toString() method.

  1. $form->html('Your html content', $label = '');

Tags (tags)

Insert comma-separated string tags

  1. $form->tags('keywords');

tags also supports the relationship ManyToMany, as in the following example.

  1. $form->tags('tags', 'Article Tags')
  2. ->pluck('name', 'id') // name is the field of the Tag model to be displayed, id is the primary key.
  3. ->options(Tag::all());// drop-down box options

Note: The pluck method must be called when handling ManyToMany relationships, specifying the field name and primary key to be displayed. In addition, when the options method is passed to a Collection object, options will automatically call the pluck method of that object to an array of ['Primary Key Name' => 'Show Field Name'] as a drop-down box option. Or you can just use an array like ['Primary Key Name' => 'Show Field Name'] as an argument.

tags also supports the saving method for processing submitted data, as in the following example:

  1. $form->tags('tags', 'Article Tags')
  2. ->pluck('name', 'id')
  3. ->options(Tag::all())
  4. ->saving(function ($value) {
  5. return $value;
  6. });

The saving method receives a closure that says “submit value for tags, return value is modified tags submit value” and can be used to automatically create new tags or other features.

If there are too many options, you can dynamically paginate the options via ajax.

  1. $form->tags('friends')->options(function ($ids) {
  2. return User::find((array) $ids)->pluck('name', 'id');
  3. })->ajax('api/users');

API /admin/api/users Interface code:

  1. public function users(Request $request)
  2. {
  3. $q = $request->get('q');
  4. return User::where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
  5. }

The data structure returned by the interface is

  1. {
  2. "total": 4,
  3. "per_page": 15,
  4. "current_page": 1,
  5. "last_page": 1,
  6. "next_page_url": null,
  7. "prev_page_url": null,
  8. "from": 1,
  9. "to": 3,
  10. "data": [
  11. {
  12. "id": 9,
  13. "text": "xxx"
  14. },
  15. {
  16. "id": 21,
  17. "text": "xxx"
  18. },
  19. {
  20. "id": 42,
  21. "text": "xxx"
  22. },
  23. {
  24. "id": 48,
  25. "text": "xxx"
  26. }
  27. ]
  28. }

Icon selector (icon)

Select the font-awesome icon

  1. $form->icon('icon');

Tree selector (tree)

tree hierarchy form field

  1. $form->tree('permissions')
  2. ->nodes(Model::get()->toArray()) // Set all nodes
  3. ->customFormat(function ($v) { // Formatting externally injected values
  4. if (!$v) return [];
  5. return array_column($v, 'id');
  6. });
  7. // Modifying the field names of nodes
  8. // Default "id" "name" "parent_id"
  9. $form->tree('permissions')
  10. ->nodes($permissionModel->allNodes())
  11. ->setIdColumn('id')
  12. ->setTitleColumn('title')
  13. ->setParentColumn('parent');
  14. // The default is not to save the value of the parent node, since the parent node generally exists only as a TITLE.
  15. // Disable filtering of parent node values
  16. $form->tree('permissions')
  17. ->nodes($permissionModel->allNodes())
  18. ->exceptParentNode(false);
  19. // Default Collapsed Child Nodes
  20. $form->tree('permissions')
  21. ->nodes($permissionModel->allNodes())
  22. ->expand(false);

The tree form does not allow parent nodes to be selected individually by default, you can turn this on with treeState(false)

  1. $form->tree('xxx')
  2. ->treeState(false) # Allow separate selection of parent nodes
  3. ->setTitleColumn('title')
  4. ->nodes(...) ;

Effects

Use of form fields - 图2

Table form (table)

If a field stores a 2D array in JSON format, the table form component can be used for quick editing:

  1. $form->table('extra', function (NestedForm $table) {
  2. $table->text('key');
  3. $table->text('value');
  4. $table->text('desc');
  5. });

Also add accessors and modifiers to this field in the model:

  1. public function getExtraAttribute($extra)
  2. {
  3. return array_values(json_decode($extra, true) ?: []);
  4. }
  5. public function setExtraAttribute($extra)
  6. {
  7. $this->attributes['extra'] = json_encode(array_values($extra));
  8. }

This component is similar to the hasMany component, but is used to handle the case of a single field for simple two-dimensional data.

One-to-many (hasMany)

A one-to-many inline table for one-to-many relationships is shown in the following simple example.

There are two tables with one-to-many relationships:

  1. CREATE TABLE `demo_painters` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  3. `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  4. `bio` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  5. `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  6. `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  7. PRIMARY KEY (`id`)
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  9. CREATE TABLE `demo_paintings` (
  10. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11. `painter_id` int(10) unsigned NOT NULL,
  12. `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  13. `body` text COLLATE utf8_unicode_ci NOT NULL,
  14. `completed_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  15. `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  16. `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  17. PRIMARY KEY (`id`),
  18. KEY painter_id (`painter_id`)
  19. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The table is modeled as:

  1. <?php
  2. namespace App\Models\Demo;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Painter extends Model
  5. {
  6. public function paintings()
  7. {
  8. return $this->hasMany(Painting::class, 'painter_id');
  9. }
  10. }
  1. <?php
  2. namespace App\Models\Demo;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Painting extends Model
  5. {
  6. protected $fillable = ['title', 'body', 'completed_at'];
  7. public function painter()
  8. {
  9. return $this->belongsTo(Painter::class, 'painter_id');
  10. }
  11. }

Build the form code as follows:

  1. use App\Models\Demo\Painter;
  2. // Here you need to explicitly specify the relationship
  3. $builder = Painter::with('paintings');
  4. // If you are using a data warehouse, you can specify the relationships like this
  5. // $repository = new Painter(['paintings']);
  6. return Form::make($builder, function (Form $form) {
  7. $form->display('id', 'ID');
  8. $form->text('username')->rules('required');
  9. $form->textarea('bio')->rules('required');
  10. $form->hasMany('paintings', function (Form\NestedForm $form) {
  11. $form->text('title');
  12. $form->textarea('body');
  13. $form->datetime('completed_at');
  14. });
  15. $form->display('created_at', 'Created At');
  16. $form->display('updated_at', 'Updated At');
  17. // You can also set the label.
  18. // $form->hasMany('paintings', 'paintings', function (Form\NestedForm $form) {
  19. // ...
  20. // });
  21. });

result

Use of form fields - 图3

Table schema (table)

If you want to display the table mode, you can use it like this

  1. use Dcat\Admin\Support\Helper;
  2. $form->hasMany('paintings', function (Form\NestedForm $form) {
  3. ...
  4. })->useTable();

result

Use of form fields - 图4

Embedded (embeds)

{tip} Embedded forms do not support image and file upload forms.

Used to process mysql‘s JSON type field data or mongodb‘s object type data, can also store data values of multiple fields as JSON strings in mysql string type fields.

For example, if the JSON or string type extra field in the orders table is used to store data from multiple fields, define the model first:

  1. class Order extends Model
  2. {
  3. protected $casts = [
  4. 'extra' => 'json',
  5. ];
  6. }

Then in the form use.

  1. $form->embeds('extra', function ($form) {
  2. $form->text('extra1')->rules('required');
  3. $form->email('extra2')->rules('required');
  4. $form->mobile('extra3');
  5. $form->datetime('extra4');
  6. $form->dateRange('extra5', 'extra6', 'Range')->rules('required');
  7. });
  8. // Custom TITLE
  9. $form->embeds('extra', 'Additional information', function ($form) {
  10. ...
  11. });

The method calls for building form elements inside the callback function are the same as outside.