Select.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Exception\RuntimeException;
  5. use Dcat\Admin\Form\Field;
  6. use Dcat\Admin\Support\Helper;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Illuminate\Support\Arr;
  9. use Illuminate\Support\Str;
  10. class Select extends Field
  11. {
  12. use CanCascadeFields;
  13. protected $cascadeEvent = 'change';
  14. /**
  15. * @var array
  16. */
  17. protected $groups = [];
  18. /**
  19. * @var array
  20. */
  21. protected $config = [];
  22. /**
  23. * Set options.
  24. *
  25. * @param array|\Closure|string $options
  26. *
  27. * @return $this|mixed
  28. */
  29. public function options($options = [])
  30. {
  31. if ($options instanceof \Closure) {
  32. $this->options = $options;
  33. return $this;
  34. }
  35. // remote options
  36. if (is_string($options)) {
  37. // reload selected
  38. if (class_exists($options) && in_array(Model::class, class_parents($options))) {
  39. return $this->model(...func_get_args());
  40. }
  41. return $this->loadRemoteOptions(...func_get_args());
  42. }
  43. $this->options = Helper::array($options);
  44. return $this;
  45. }
  46. /**
  47. * @param array $groups
  48. */
  49. /**
  50. * Set option groups.
  51. *
  52. * eg: $group = [
  53. * [
  54. * 'label' => 'xxxx',
  55. * 'options' => [
  56. * 1 => 'foo',
  57. * 2 => 'bar',
  58. * ...
  59. * ],
  60. * ...
  61. * ]
  62. *
  63. * @param array $groups
  64. *
  65. * @return $this
  66. */
  67. public function groups(array $groups)
  68. {
  69. $this->groups = $groups;
  70. return $this;
  71. }
  72. /**
  73. * Load options for other select on change.
  74. *
  75. * @param string $field
  76. * @param string $sourceUrl
  77. * @param string $idField
  78. * @param string $textField
  79. *
  80. * @return $this
  81. */
  82. public function load($field, $sourceUrl, string $idField = 'id', string $textField = 'text')
  83. {
  84. if (Str::contains($field, '.')) {
  85. $field = $this->formatName($field);
  86. }
  87. $class = $this->normalizeElementClass($field);;
  88. $url = admin_url($sourceUrl);
  89. return $this->addVariables(['load' => compact('url', 'class', 'idField', 'textField')]);
  90. }
  91. /**
  92. * Load options for other selects on change.
  93. *
  94. * @param string $fields
  95. * @param string $sourceUrls
  96. * @param string $idField
  97. * @param string $textField
  98. *
  99. * @return $this
  100. */
  101. public function loads($fields = [], $sourceUrls = [], string $idField = 'id', string $textField = 'text')
  102. {
  103. $fieldsStr = implode('^', array_map(function ($field) {
  104. if (Str::contains($field, '.')) {
  105. return $this->normalizeElementClass($field).'_';
  106. }
  107. return $this->normalizeElementClass($field);
  108. }, (array) $fields));
  109. $urlsStr = implode('^', array_map(function ($url) {
  110. return admin_url($url);
  111. }, (array) $sourceUrls));
  112. return $this->addVariables(['loads' => [
  113. 'fields' => $fieldsStr,
  114. 'urls' => $urlsStr,
  115. 'idField' => $idField,
  116. 'textField' => $textField,
  117. ]]);
  118. }
  119. /**
  120. * Load options from current selected resource(s).
  121. *
  122. * @param string $model
  123. * @param string $idField
  124. * @param string $textField
  125. *
  126. * @return $this
  127. */
  128. public function model($model, string $idField = 'id', string $textField = 'name')
  129. {
  130. if (! class_exists($model)
  131. || ! in_array(Model::class, class_parents($model))
  132. ) {
  133. throw new RuntimeException("[$model] must be a valid model class");
  134. }
  135. $this->options = function ($value) use ($model, $idField, $textField) {
  136. if (empty($value)) {
  137. return [];
  138. }
  139. $resources = [];
  140. if (is_array($value)) {
  141. if (Arr::isAssoc($value)) {
  142. $resources[] = Arr::get($value, $idField);
  143. } else {
  144. $resources = array_column($value, $idField);
  145. }
  146. } else {
  147. $resources[] = $value;
  148. }
  149. return $model::find($resources)->pluck($textField, $idField)->toArray();
  150. };
  151. return $this;
  152. }
  153. /**
  154. * Load options from remote.
  155. *
  156. * @param string $url
  157. * @param array $parameters
  158. * @param array $options
  159. *
  160. * @return $this
  161. */
  162. protected function loadRemoteOptions(string $url, array $parameters = [], array $options = [])
  163. {
  164. $ajaxOptions = [
  165. 'url' => admin_url($url.'?'.http_build_query($parameters)),
  166. ];
  167. $ajaxOptions = array_merge($ajaxOptions, $options);
  168. return $this->addVariables(['remoteOptions' => $ajaxOptions]);
  169. }
  170. /**
  171. * @param string|array $key
  172. * @param mixed $value
  173. *
  174. * @return $this
  175. */
  176. public function addDefaultConfig($key, $value = null)
  177. {
  178. if (is_array($key)) {
  179. foreach ($key as $k => $v) {
  180. $this->addDefaultConfig($k, $v);
  181. }
  182. return $this;
  183. }
  184. if (! isset($this->config[$key])) {
  185. $this->config[$key] = $value;
  186. }
  187. return $this;
  188. }
  189. /**
  190. * Load options from ajax results.
  191. *
  192. * @param string $url
  193. * @param $idField
  194. * @param $textField
  195. *
  196. * @return $this
  197. */
  198. public function ajax(string $url, string $idField = 'id', string $textField = 'text')
  199. {
  200. $this->addDefaultConfig([
  201. 'minimumInputLength' => 1,
  202. ]);
  203. $url = admin_url($url);
  204. return $this->addVariables(['ajax' => compact('url', 'idField', 'textField')]);
  205. }
  206. /**
  207. * Set config for select2.
  208. *
  209. * all configurations see https://select2.org/configuration/options-api
  210. *
  211. * @param string $key
  212. * @param mixed $val
  213. *
  214. * @return $this
  215. */
  216. public function config(string $key, $val)
  217. {
  218. $this->config[$key] = $val;
  219. return $this;
  220. }
  221. /**
  222. * Disable clear button.
  223. *
  224. * @return $this
  225. */
  226. public function disableClearButton()
  227. {
  228. return $this->config('allowClear', false);
  229. }
  230. /**
  231. * {@inheritdoc}
  232. */
  233. public function render()
  234. {
  235. $this->addDefaultConfig([
  236. 'allowClear' => true,
  237. 'placeholder' => [
  238. 'id' => '',
  239. 'text' => $this->placeholder(),
  240. ],
  241. ]);
  242. $this->addCascadeScript();
  243. $this->formatOptions();
  244. $this->addVariables([
  245. 'options' => $this->options,
  246. 'groups' => $this->groups,
  247. 'configs' => $this->config,
  248. ]);
  249. $this->attribute('data-value', implode(',', Helper::array($this->value())));
  250. return parent::render();
  251. }
  252. protected function formatOptions()
  253. {
  254. if ($this->options instanceof \Closure) {
  255. $this->options = $this->options->bindTo($this->values());
  256. $this->options(call_user_func($this->options, $this->value(), $this));
  257. }
  258. $this->options = array_filter($this->options, 'strlen');
  259. }
  260. /**
  261. * {@inheritdoc}
  262. */
  263. public function placeholder($placeholder = null)
  264. {
  265. if ($placeholder === null) {
  266. return $this->placeholder ?: $this->label;
  267. }
  268. $this->placeholder = $placeholder;
  269. return $this;
  270. }
  271. }