KeyValue.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Form\Field;
  5. use Illuminate\Support\Arr;
  6. class KeyValue extends Field
  7. {
  8. const DEFAULT_FLAG_NAME = '_def_';
  9. /**
  10. * @var array
  11. */
  12. protected $value = ['' => ''];
  13. /**
  14. * Fill data to the field.
  15. *
  16. * @param array $data
  17. *
  18. * @return mixed
  19. */
  20. public function formatFieldData($data)
  21. {
  22. $this->data = $data;
  23. return Arr::get($data, $this->column, $this->value);
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public function getValidator(array $input)
  29. {
  30. if ($this->validator) {
  31. return $this->validator->call($this, $input);
  32. }
  33. if (! is_string($this->column)) {
  34. return false;
  35. }
  36. $rules = $attributes = [];
  37. if (! $fieldRules = $this->getRules()) {
  38. return false;
  39. }
  40. if (! Arr::has($input, $this->column)) {
  41. return false;
  42. }
  43. $rules["{$this->column}.keys.*"] = 'distinct';
  44. $rules["{$this->column}.values.*"] = $fieldRules;
  45. $attributes["{$this->column}.keys.*"] = __('Key');
  46. $attributes["{$this->column}.values.*"] = __('Value');
  47. $input = $this->prepareValidatorInput($input);
  48. return validator($input, $rules, $this->getValidationMessages(), $attributes);
  49. }
  50. protected function prepareValidatorInput(array $input)
  51. {
  52. Arr::forget($input, $this->column.'.'.static::DEFAULT_FLAG_NAME);
  53. return $input;
  54. }
  55. protected function setupScript()
  56. {
  57. $value = old($this->column, $this->value());
  58. $number = $value ? count($value) : 0;
  59. $class = $this->getElementClassString();
  60. $this->script = <<<JS
  61. (function () {
  62. var index = {$number};
  63. $('.{$class}-add').on('click', function () {
  64. var tpl = $('template.{$class}-tpl').html().replace('{key}', index).replace('{key}', index);
  65. $('tbody.kv-{$class}-table').append(tpl);
  66. index++;
  67. });
  68. $('tbody').on('click', '.{$class}-remove', function () {
  69. $(this).closest('tr').remove();
  70. });
  71. })();
  72. JS;
  73. }
  74. protected function prepareToSave($value)
  75. {
  76. unset($value[static::DEFAULT_FLAG_NAME]);
  77. if (empty($value)) {
  78. return [];
  79. }
  80. return array_combine($value['keys'], $value['values']);
  81. }
  82. public function render()
  83. {
  84. $this->setupScript();
  85. Admin::style('td .form-group {margin-bottom: 0 !important;}');
  86. return parent::render();
  87. }
  88. }