KeyValue.php 2.5 KB

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