KeyValue.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. /**
  9. * @var array
  10. */
  11. protected $value = ['' => ''];
  12. /**
  13. * Fill data to the field.
  14. *
  15. * @param array $data
  16. *
  17. * @return mixed
  18. */
  19. public function formatFieldData($data)
  20. {
  21. $this->data = $data;
  22. return Arr::get($data, $this->column, $this->value);
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function getValidator(array $input)
  28. {
  29. if ($this->validator) {
  30. return $this->validator->call($this, $input);
  31. }
  32. if (!is_string($this->column)) {
  33. return false;
  34. }
  35. $rules = $attributes = [];
  36. if (!$fieldRules = $this->getRules()) {
  37. return false;
  38. }
  39. if (!Arr::has($input, $this->column)) {
  40. return false;
  41. }
  42. $rules["{$this->column}.keys.*"] = 'distinct';
  43. $rules["{$this->column}.values.*"] = $fieldRules;
  44. $attributes["{$this->column}.keys.*"] = __('Key');
  45. $attributes["{$this->column}.values.*"] = __('Value');
  46. return validator($input, $rules, $this->getValidationMessages(), $attributes);
  47. }
  48. protected function setupScript()
  49. {
  50. $this->script = <<<JS
  51. $('.{$this->column}-add').on('click', function () {
  52. var tpl = $('template.{$this->column}-tpl').html();
  53. $('tbody.kv-{$this->column}-table').append(tpl);
  54. });
  55. $('tbody').on('click', '.{$this->column}-remove', function () {
  56. $(this).closest('tr').remove();
  57. });
  58. JS;
  59. }
  60. public function prepare($value)
  61. {
  62. return array_combine($value['keys'], $value['values']);
  63. }
  64. public function render()
  65. {
  66. $this->setupScript();
  67. Admin::style('td .form-group {margin-bottom: 0 !important;}');
  68. return parent::render();
  69. }
  70. }