表单字段动态显示

{tip} 此功能在工具表单中一样有效

表单字段动态显示是指,在选择表单项的指定的选项时,联动显示其他的表单项。

表单字段动态显示 - 图1

目前支持的表单联动的组件有:

  • select
  • multipleSelect
  • radio
  • checkbox

使用方法

可以将上面的组件分为单选和多选两种类型,其中selectradio为单选组件,其它为多选组件

单选组件

下面的例子中,选择不同的国籍类型,将会切换选择不同的联动表单项:

  1. $form->radio('radio')
  2. ->when([1, 4], function (Form $form) {
  3. // 值为1和4时显示文本框
  4. $form->text('text1');
  5. $form->text('text2');
  6. $form->text('text3');
  7. })
  8. ->when(2, function (Form $form) {
  9. $form->editor('editor');
  10. })
  11. ->when(3, function (Form $form) {
  12. $form->image('image');
  13. })
  14. ->options([
  15. 1 => '显示文本框',
  16. 2 => '显示编辑器',
  17. 3 => '显示文件上传',
  18. 4 => '还是显示文本框',
  19. ])
  20. ->default(1);

上例中,方法when(1, $callback)等效于when('=', 1, $callback), 如果用操作符=,则可以省略这个参数

同时也支持这些操作符,=>>=<<=!=使用方法如下:

  1. $form->radio('check')
  2. ->when('>', 1, function () {
  3. })->when('>=', 2, function () {
  4. });

select 组件的使用方法和radio是一样的。

另外需要注意的是,如果使用动态显示功能之后表单不能使用required方法,应该使用required_if代替,如

  1. $form->radio('type')
  2. ->when([1, 4], function (Form $form) {
  3. $form->text('text1')
  4. ->rules('required_if:type,1,4') // 使用required_if
  5. ->setLabelClass(['asterisk']); // 显示 * 号
  6. });

多选组件

多选组件支持两个操作符:innotIn

  1. $form->checkbox('nationality', '国籍')
  2. ->options([
  3. 1 => '中国',
  4. 2 => '外国',
  5. ])->when([1, 2], function (Form $form) {
  6. $form->text('name', '姓名');
  7. $form->text('idcard', '身份证');
  8. })->when('notIn', 2, function (Form $form) {
  9. $form->text('name', '姓名');
  10. $form->text('passport', '护照');
  11. });

multipleSelect组件的使用方法和checkbox是一样的。

布局

表单动态显示功能支持结合column以及tab布局功能一起使用,用法如下

tab布局

  1. $form->tab('Radio', function (Form $form) {
  2. $form->display('title')->value('单选框动态展示');
  3. $form->radio('radio')
  4. ->when([1, 4], function (Form $form) {
  5. $form->text('text1');
  6. $form->text('text2');
  7. })
  8. ->when(2, function (Form $form) {
  9. $form->editor('editor');
  10. })
  11. ->options($this->options)
  12. ->default(1);
  13. });

column布局

  1. $form->column(6, function (Form $form) {
  2. $form->radio('radio')
  3. ->when([1, 4], function (Form $form) {
  4. $form->text('text1');
  5. $form->text('text2');
  6. })
  7. ->when(2, function (Form $form) {
  8. $form->editor('editor');
  9. })
  10. ->options($this->options)
  11. ->default(1);
  12. });