Tree.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. <?php
  2. /**
  3. * FormBuilder表单生成器
  4. * Author: xaboy
  5. * Github: https://github.com/xaboy/form-builder
  6. */
  7. namespace FormBuilder\components;
  8. use FormBuilder\FormComponentDriver;
  9. /**
  10. * 树型组件
  11. * Class Tree
  12. *
  13. * @package FormBuilder\components
  14. * @method $this type(String $type) 类型,可选值为 checked、selected
  15. * @method $this multiple(Boolean $bool) 是否支持多选, 当`type=selected`并且`multiple=false`, 默认为false, 值为String或Number类型,其他情况为Array类型
  16. * @method $this showCheckbox(Boolean $bool) 是否显示多选框, 默认为false
  17. * @method $this emptyText(String $emptyText) 没有数据时的提示, 默认为'暂无数据'
  18. */
  19. class Tree extends FormComponentDriver
  20. {
  21. /**
  22. * @var string
  23. */
  24. protected $name = 'tree';
  25. /**
  26. *
  27. */
  28. const TYPE_SELECTED = 'selected';
  29. /**
  30. *
  31. */
  32. const TYPE_CHECKED = 'checked';
  33. /**
  34. * @var array
  35. */
  36. protected $props = [
  37. 'type' => self::TYPE_CHECKED,
  38. 'data' => [],
  39. 'multiple' => true
  40. ];
  41. /**
  42. * @var array
  43. */
  44. protected static $propsRule = [
  45. 'type' => 'string',
  46. 'multiple' => 'boolean',
  47. 'showCheckbox' => 'boolean',
  48. 'emptyText' => 'string',
  49. ];
  50. /**
  51. * @param array $treeData
  52. * @return $this
  53. */
  54. public function data(array $treeData)
  55. {
  56. if (!is_array($this->props['data'])) $this->props['data'] = [];
  57. foreach ($treeData as $child) {
  58. $this->props['data'][] = $child instanceof TreeData
  59. ? $child->build()
  60. : $child;
  61. }
  62. return $this;
  63. }
  64. /**
  65. * @param $var
  66. * @return $this
  67. */
  68. public function jsData($var)
  69. {
  70. $this->props['data'] = 'js.' . $var;
  71. return $this;
  72. }
  73. /**
  74. * @param $value
  75. * @return $this
  76. */
  77. public function value($value)
  78. {
  79. if (is_array($value)) {
  80. foreach ($value as $k => $v) {
  81. $value[$k] = (string)$v;
  82. }
  83. } else {
  84. $value = (string)$value;
  85. }
  86. $this->value = $value;
  87. return $this;
  88. }
  89. public function getValidateHandler()
  90. {
  91. if ($this->props['multiple'])
  92. return Validate::arr();
  93. else
  94. return Validate::str();
  95. }
  96. /**
  97. * @return array
  98. */
  99. public function build()
  100. {
  101. return [
  102. 'type' => $this->name,
  103. 'field' => $this->field,
  104. 'title' => $this->title,
  105. 'value' => $this->value,
  106. 'props' => (object)$this->props,
  107. 'validate' => $this->validate,
  108. 'col' => $this->col
  109. ];
  110. }
  111. }