Relation.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Dcat\Admin\Show;
  3. use Dcat\Admin\Grid;
  4. use Dcat\Admin\Show;
  5. use Illuminate\Support\Fluent;
  6. class Relation extends Field
  7. {
  8. /**
  9. * Relation name.
  10. *
  11. * @var string
  12. */
  13. protected $name;
  14. /**
  15. * Relation panel builder.
  16. *
  17. * @var \Closure
  18. */
  19. protected $builder;
  20. /**
  21. * Relation panel title.
  22. *
  23. * @var string
  24. */
  25. protected $title;
  26. /**
  27. * Parent model.
  28. *
  29. * @var Fluent
  30. */
  31. protected $model;
  32. /**
  33. * Relation constructor.
  34. *
  35. * @param string $name
  36. * @param \Closure $builder
  37. * @param string $title
  38. */
  39. public function __construct($name, $builder, $title = '')
  40. {
  41. $this->name = $name;
  42. $this->builder = $builder;
  43. $this->title = $this->formatLabel($title);
  44. }
  45. /**
  46. * Set parent model for relation.
  47. *
  48. * @param Fluent $model
  49. *
  50. * @return $this|Fluent
  51. */
  52. public function model(Fluent $model = null)
  53. {
  54. if ($model === null) {
  55. return $this->model;
  56. }
  57. $this->model = $model;
  58. return $this;
  59. }
  60. /**
  61. * Render this relation panel.
  62. *
  63. * @return string
  64. */
  65. public function render()
  66. {
  67. $view = call_user_func($this->builder, $this->model);
  68. if ($view instanceof Show) {
  69. $view->panel()->title($this->title);
  70. return $view->render();
  71. }
  72. if (! $view instanceof Grid) {
  73. return $view;
  74. }
  75. $view->setName($this->name)
  76. ->title($this->title)
  77. ->disableBatchDelete()
  78. ->disableFilter();
  79. return <<<HTML
  80. <div class="mb-2">
  81. {$view->render()}
  82. </div>
  83. HTML;
  84. }
  85. }