Builder.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. <?php
  2. namespace Dcat\Admin\Form;
  3. use Closure;
  4. use Dcat\Admin\Admin;
  5. use Dcat\Admin\Contracts\UploadField;
  6. use Dcat\Admin\Form;
  7. use Dcat\Admin\Form\Field\Hidden;
  8. use Dcat\Admin\Support\Helper;
  9. use Dcat\Admin\Traits\HasVariables;
  10. use Dcat\Admin\Widgets\DialogForm;
  11. use Illuminate\Contracts\Support\Renderable;
  12. use Illuminate\Support\Arr;
  13. use Illuminate\Support\Collection;
  14. use Illuminate\Support\Facades\URL;
  15. use Illuminate\Support\Str;
  16. /**
  17. * Class Builder.
  18. */
  19. class Builder
  20. {
  21. use HasVariables;
  22. /**
  23. * 上个页面URL保存的key.
  24. */
  25. const PREVIOUS_URL_KEY = '_previous_';
  26. /**
  27. * Modes constants.
  28. */
  29. const MODE_EDIT = 'edit';
  30. const MODE_CREATE = 'create';
  31. const MODE_DELETE = 'delete';
  32. /**
  33. * @var mixed
  34. */
  35. protected $id;
  36. /**
  37. * @var Form
  38. */
  39. protected $form;
  40. /**
  41. * @var
  42. */
  43. protected $action;
  44. /**
  45. * @var Collection|Field[]
  46. */
  47. protected $fields;
  48. /**
  49. * @var array
  50. */
  51. protected $options = [];
  52. /**
  53. * Form action mode, could be create|view|edit.
  54. *
  55. * @var string
  56. */
  57. protected $mode = self::MODE_CREATE;
  58. /**
  59. * @var array
  60. */
  61. protected $hiddenFields = [];
  62. /**
  63. * @var Tools
  64. */
  65. protected $tools;
  66. /**
  67. * @var Footer
  68. */
  69. protected $footer;
  70. /**
  71. * Width for label and field.
  72. *
  73. * @var array
  74. */
  75. protected $width = [
  76. 'label' => 2,
  77. 'field' => 8,
  78. ];
  79. /**
  80. * View for this form.
  81. *
  82. * @var string
  83. */
  84. protected $view = 'admin::form.container';
  85. /**
  86. * Form title.
  87. *
  88. * @var string
  89. */
  90. protected $title;
  91. /**
  92. * @var Layout
  93. */
  94. protected $layout;
  95. /**
  96. * @var string
  97. */
  98. protected $elementId;
  99. /**
  100. * @var \Closure
  101. */
  102. protected $wrapper;
  103. /**
  104. * @var bool
  105. */
  106. protected $showHeader = true;
  107. /**
  108. * @var bool
  109. */
  110. protected $showFooter = true;
  111. /**
  112. * @var array
  113. */
  114. public $confirm = [];
  115. /**
  116. * Builder constructor.
  117. *
  118. * @param Form $form
  119. */
  120. public function __construct(Form $form)
  121. {
  122. $this->form = $form;
  123. $this->fields = new Collection();
  124. $this->layout = new Layout($form);
  125. $this->tools = new Tools($this);
  126. $this->footer = new Footer($this);
  127. }
  128. /**
  129. * @param \Closure $closure
  130. *
  131. * @return Layout
  132. */
  133. public function layout($closure = null)
  134. {
  135. if ($closure) {
  136. $closure($this->layout);
  137. }
  138. return $this->layout;
  139. }
  140. /**
  141. * @param Closure $closure
  142. *
  143. * @return $this;
  144. */
  145. public function wrap(Closure $closure)
  146. {
  147. $this->wrapper = $closure;
  148. return $this;
  149. }
  150. /**
  151. * @return bool
  152. */
  153. public function hasWrapper()
  154. {
  155. return $this->wrapper ? true : false;
  156. }
  157. /**
  158. * Get form tools instance.
  159. *
  160. * @return Tools
  161. */
  162. public function tools()
  163. {
  164. return $this->tools;
  165. }
  166. /**
  167. * Get form footer instance.
  168. *
  169. * @return Footer
  170. */
  171. public function footer()
  172. {
  173. return $this->footer;
  174. }
  175. /**
  176. * @param string $title
  177. * @param string $content
  178. *
  179. * @return $this
  180. */
  181. public function confirm(?string $title = null, ?string $content = null)
  182. {
  183. $this->confirm['title'] = $title;
  184. $this->confirm['content'] = $content;
  185. return $this;
  186. }
  187. /**
  188. * Set the builder mode.
  189. *
  190. * @param string $mode
  191. *
  192. * @return void|string
  193. */
  194. public function mode(string $mode = null)
  195. {
  196. if ($mode === null) {
  197. return $this->mode;
  198. }
  199. $this->mode = $mode;
  200. }
  201. /**
  202. * Returns builder is $mode.
  203. *
  204. * @param $mode
  205. *
  206. * @return bool
  207. */
  208. public function isMode($mode)
  209. {
  210. return $this->mode == $mode;
  211. }
  212. /**
  213. * Check if is creating resource.
  214. *
  215. * @return bool
  216. */
  217. public function isCreating()
  218. {
  219. return $this->isMode(static::MODE_CREATE);
  220. }
  221. /**
  222. * Check if is editing resource.
  223. *
  224. * @return bool
  225. */
  226. public function isEditing()
  227. {
  228. return $this->isMode(static::MODE_EDIT);
  229. }
  230. /**
  231. * Check if is deleting resource.
  232. *
  233. * @return bool
  234. */
  235. public function isDeleting()
  236. {
  237. return $this->isMode(static::MODE_DELETE);
  238. }
  239. /**
  240. * Set resource Id.
  241. *
  242. * @param $id
  243. *
  244. * @return mixed|void
  245. */
  246. public function setResourceId($id)
  247. {
  248. $this->id = $id;
  249. }
  250. /**
  251. * @return mixed
  252. */
  253. public function getResourceId()
  254. {
  255. return $this->id;
  256. }
  257. /**
  258. * @return string
  259. */
  260. public function resource($slice = null)
  261. {
  262. if ($this->mode == self::MODE_CREATE) {
  263. return $this->form->resource(-1);
  264. }
  265. if ($slice !== null) {
  266. return $this->form->resource($slice);
  267. }
  268. return $this->form->resource();
  269. }
  270. /**
  271. * @param int $field
  272. * @param int $label
  273. *
  274. * @return $this
  275. */
  276. public function width($field = 8, $label = 2)
  277. {
  278. $this->width = [
  279. 'label' => $label,
  280. 'field' => $field,
  281. ];
  282. return $this;
  283. }
  284. /**
  285. * Get label and field width.
  286. *
  287. * @return array
  288. */
  289. public function getWidth()
  290. {
  291. return $this->width;
  292. }
  293. /**
  294. * Get or set action for form.
  295. *
  296. * @return string|void
  297. */
  298. public function action($action = null)
  299. {
  300. if ($action !== null) {
  301. $this->action = admin_url($action);
  302. return;
  303. }
  304. if ($this->action) {
  305. return $this->action;
  306. }
  307. if ($this->isMode(static::MODE_EDIT)) {
  308. return $this->form->resource().'/'.$this->id;
  309. }
  310. if ($this->isMode(static::MODE_CREATE)) {
  311. return $this->form->resource(-1);
  312. }
  313. return '';
  314. }
  315. /**
  316. * Set view for this form.
  317. *
  318. * @param string $view
  319. *
  320. * @return $this
  321. */
  322. public function view($view)
  323. {
  324. $this->view = $view;
  325. return $this;
  326. }
  327. /**
  328. * Get or set title for form.
  329. *
  330. * @param string $title
  331. *
  332. * @return $this|string
  333. */
  334. public function title($title = null)
  335. {
  336. if ($title !== null) {
  337. $this->title = $title;
  338. return $this;
  339. }
  340. if ($this->title) {
  341. return $this->title;
  342. }
  343. if ($this->mode == static::MODE_CREATE) {
  344. return trans('admin.create');
  345. }
  346. if ($this->mode == static::MODE_EDIT) {
  347. return trans('admin.edit');
  348. }
  349. return '';
  350. }
  351. /**
  352. * Get fields of this builder.
  353. *
  354. * @return Collection
  355. */
  356. public function fields()
  357. {
  358. return $this->fields;
  359. }
  360. /**
  361. * Get specify field.
  362. *
  363. * @param string|Field $name
  364. *
  365. * @return Field|null
  366. */
  367. public function field($name)
  368. {
  369. return $this->fields->first(function (Field $field) use ($name) {
  370. if (is_array($field->column())) {
  371. $result = in_array($name, $field->column(), true) || $field->column() === $name ? $field : null;
  372. if ($result) {
  373. return $result;
  374. }
  375. }
  376. return $field === $name || $field->column() === $name;
  377. });
  378. }
  379. /**
  380. * @param $column
  381. *
  382. * @return void
  383. */
  384. public function removeField($column)
  385. {
  386. $this->fields = $this->fields->filter(function (Field $field) use ($column) {
  387. return $field->column() != $column;
  388. });
  389. }
  390. /**
  391. * If the parant form has rows.
  392. *
  393. * @return bool
  394. */
  395. public function hasRows()
  396. {
  397. return ! empty($this->form->rows());
  398. }
  399. /**
  400. * Get field rows of form.
  401. *
  402. * @return array
  403. */
  404. public function rows()
  405. {
  406. return $this->form->rows();
  407. }
  408. /**
  409. * @return Form
  410. */
  411. public function form()
  412. {
  413. return $this->form;
  414. }
  415. /**
  416. * @return array
  417. */
  418. public function hiddenFields()
  419. {
  420. return $this->hiddenFields;
  421. }
  422. /**
  423. * @param Field $field
  424. *
  425. * @return void
  426. */
  427. public function addHiddenField(Field $field)
  428. {
  429. $this->hiddenFields[] = $field;
  430. }
  431. /**
  432. * Add or get options.
  433. *
  434. * @param array $options
  435. *
  436. * @return array|null
  437. */
  438. public function options($options = [])
  439. {
  440. if (empty($options)) {
  441. return $this->options;
  442. }
  443. $this->options = array_merge($this->options, $options);
  444. }
  445. /**
  446. * Get or set option.
  447. *
  448. * @param string $option
  449. * @param mixed $value
  450. *
  451. * @return void
  452. */
  453. public function option($option, $value = null)
  454. {
  455. if (func_num_args() == 1) {
  456. return Arr::get($this->options, $option);
  457. }
  458. $this->options[$option] = $value;
  459. }
  460. /**
  461. * @param bool $disable
  462. *
  463. * @return void
  464. */
  465. public function disableHeader(bool $disable = true)
  466. {
  467. $this->showHeader = ! $disable;
  468. }
  469. /**
  470. * @param bool $disable
  471. *
  472. * @return void
  473. */
  474. public function disableFooter(bool $disable = true)
  475. {
  476. $this->showFooter = ! $disable;
  477. }
  478. /**
  479. * @param $id
  480. *
  481. * @return void
  482. */
  483. public function setElementId($id)
  484. {
  485. $this->elementId = $id;
  486. }
  487. /**
  488. * @return string
  489. */
  490. public function getElementId()
  491. {
  492. return $this->elementId ?: ($this->elementId = 'form-'.Str::random(8));
  493. }
  494. public function pushField(Field $field)
  495. {
  496. $this->fields->push($field);
  497. return $this;
  498. }
  499. /**
  500. * Determine if form fields has files.
  501. *
  502. * @return bool
  503. */
  504. public function hasFile()
  505. {
  506. foreach ($this->fields() as $field) {
  507. if ($field instanceof UploadField) {
  508. return true;
  509. }
  510. }
  511. return false;
  512. }
  513. /**
  514. * Add field for store redirect url after update or store.
  515. *
  516. * @return void
  517. */
  518. protected function addRedirectUrlField()
  519. {
  520. $previous = Helper::getPreviousUrl();
  521. if (! $previous || $previous == URL::current()) {
  522. return;
  523. }
  524. if (
  525. Str::contains($previous, url($this->resource()))
  526. && ! Helper::urlHasQuery($previous, [DialogForm::QUERY_NAME])
  527. ) {
  528. $this->addHiddenField(
  529. (new Hidden(static::PREVIOUS_URL_KEY))->value($previous)
  530. );
  531. }
  532. }
  533. /**
  534. * Open up a new HTML form.
  535. *
  536. * @param array $options
  537. *
  538. * @return string
  539. */
  540. public function open($options = [])
  541. {
  542. $attributes = [];
  543. if ($this->isMode(static::MODE_EDIT)) {
  544. $this->addHiddenField((new Hidden('_method'))->value('PUT'));
  545. }
  546. $this->addHiddenField((new Hidden('_token'))->value(csrf_token()));
  547. $this->addRedirectUrlField();
  548. $attributes['id'] = $this->getElementId();
  549. $attributes['action'] = $this->action();
  550. $attributes['method'] = Arr::get($options, 'method', 'post');
  551. $attributes['accept-charset'] = 'UTF-8';
  552. $attributes['data-toggle'] = 'validator';
  553. $attributes['class'] = Arr::get($options, 'class');
  554. if ($this->hasFile()) {
  555. $attributes['enctype'] = 'multipart/form-data';
  556. }
  557. $html = [];
  558. foreach ($attributes as $name => $value) {
  559. $html[] = "$name=\"$value\"";
  560. }
  561. return '<form '.implode(' ', $html).' '.Admin::getPjaxContainerId().'>';
  562. }
  563. /**
  564. * Close the current form.
  565. *
  566. * @return string
  567. */
  568. public function close()
  569. {
  570. $this->form = null;
  571. $this->fields = null;
  572. return '</form>';
  573. }
  574. /**
  575. * 移除需要忽略的字段.
  576. *
  577. * @return void
  578. */
  579. protected function removeIgnoreFields()
  580. {
  581. $this->fields = $this->fields()->reject(function (Field $field) {
  582. return $field->hasAttribute(Field::BUILD_IGNORE);
  583. });
  584. }
  585. /**
  586. * Remove reserved fields like `id` `created_at` `updated_at` in form fields.
  587. *
  588. * @return void
  589. */
  590. protected function removeReservedFields()
  591. {
  592. if (! $this->isMode(static::MODE_CREATE)) {
  593. return;
  594. }
  595. $reservedColumns = [
  596. $this->form->keyName(),
  597. $this->form->createdAtColumn(),
  598. $this->form->updatedAtColumn(),
  599. ];
  600. $reject = function ($field) use (&$reservedColumns) {
  601. if ($field instanceof Field) {
  602. return in_array($field->column(), $reservedColumns, true)
  603. && $field instanceof Form\Field\Display;
  604. }
  605. if ($field instanceof Row) {
  606. $fields = $field->fields()->reject(function ($item) use (&$reservedColumns) {
  607. return in_array($item['element']->column(), $reservedColumns, true)
  608. && $item['element'] instanceof Form\Field\Display;
  609. });
  610. $field->setFields($fields);
  611. }
  612. };
  613. $this->fields = $this->fields()->reject($reject);
  614. if ($this->form->hasTab()) {
  615. $this->form->getTab()->getTabs()->transform(function ($item) use ($reject) {
  616. if (! empty($item['fields'])) {
  617. $item['fields'] = $item['fields']->reject($reject);
  618. }
  619. return $item;
  620. });
  621. }
  622. }
  623. /**
  624. * Render form header tools.
  625. *
  626. * @return string
  627. */
  628. public function renderTools()
  629. {
  630. return $this->tools->render();
  631. }
  632. /**
  633. * Render form footer.
  634. *
  635. * @return string
  636. */
  637. public function renderFooter()
  638. {
  639. if (! $this->showFooter) {
  640. return;
  641. }
  642. return $this->footer->render();
  643. }
  644. protected function defaultVariables()
  645. {
  646. return [
  647. 'form' => $this,
  648. 'tabObj' => $this->form->getTab(),
  649. 'width' => $this->width,
  650. 'elementId' => $this->getElementId(),
  651. 'showHeader' => $this->showHeader,
  652. 'fields' => $this->fields,
  653. 'rows' => $this->rows(),
  654. 'layout' => $this->layout(),
  655. ];
  656. }
  657. /**
  658. * Render form.
  659. *
  660. * @return string
  661. */
  662. public function render()
  663. {
  664. $this->removeIgnoreFields();
  665. $this->removeReservedFields();
  666. $tabObj = $this->form->getTab();
  667. if (! $tabObj->isEmpty()) {
  668. $tabObj->addScript();
  669. }
  670. if ($this->form->allowAjaxSubmit()) {
  671. $this->addSubmitScript();
  672. }
  673. $open = $this->open(['class' => 'form-horizontal']);
  674. if ($this->layout->hasColumns()) {
  675. $content = $this->doWrap(view($this->view, $this->variables()));
  676. } else {
  677. if (! $this->layout->hasBlocks()) {
  678. $this->layout->prepend(
  679. 12,
  680. $this->doWrap(view($this->view, $this->variables()))
  681. );
  682. }
  683. $content = $this->layout->build();
  684. }
  685. return "{$open}{$content}{$this->close()}";
  686. }
  687. /**
  688. * @param Renderable $view
  689. *
  690. * @return string
  691. */
  692. protected function doWrap(Renderable $view)
  693. {
  694. if ($wrapper = $this->wrapper) {
  695. return Helper::render($wrapper($view));
  696. }
  697. return "<div class='card'>{$view->render()}</div>";
  698. }
  699. /**
  700. * @return void
  701. */
  702. protected function addSubmitScript()
  703. {
  704. $confirm = admin_javascript_json($this->confirm);
  705. $toastr = $this->form->validationErrorToastr ? 'true' : 'false';
  706. Admin::script(
  707. <<<JS
  708. $('#{$this->getElementId()}').form({
  709. validate: true,
  710. confirm: {$confirm},
  711. validationErrorToastr: $toastr,
  712. });
  713. JS
  714. );
  715. }
  716. }