CanLoadFields.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Illuminate\Support\Str;
  4. trait CanLoadFields
  5. {
  6. /**
  7. * 联动加载.
  8. *
  9. * @param string $field
  10. * @param string $sourceUrl
  11. * @param string $idField
  12. * @param string $textField
  13. *
  14. * @return $this
  15. */
  16. public function load($field, $sourceUrl, string $idField = 'id', string $textField = 'text')
  17. {
  18. if (Str::contains($field, '.')) {
  19. $field = $this->formatName($field);
  20. }
  21. $class = $this->normalizeElementClass($field);
  22. $url = admin_url($sourceUrl);
  23. return $this->addVariables(['load' => compact('url', 'class', 'idField', 'textField')]);
  24. }
  25. /**
  26. * 联动加载多个字段.
  27. *
  28. * @param string $fields
  29. * @param string $sourceUrls
  30. * @param string $idField
  31. * @param string $textField
  32. *
  33. * @return $this
  34. */
  35. public function loads($fields = [], $sourceUrls = [], string $idField = 'id', string $textField = 'text')
  36. {
  37. $fieldsStr = implode('^', array_map(function ($field) {
  38. if (Str::contains($field, '.')) {
  39. return $this->normalizeElementClass($field).'_';
  40. }
  41. return $this->normalizeElementClass($field);
  42. }, (array) $fields));
  43. $urlsStr = implode('^', array_map(function ($url) {
  44. return admin_url($url);
  45. }, (array) $sourceUrls));
  46. return $this->addVariables(['loads' => [
  47. 'fields' => $fieldsStr,
  48. 'urls' => $urlsStr,
  49. 'idField' => $idField,
  50. 'textField' => $textField,
  51. ]]);
  52. }
  53. }