HasMany.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Form;
  5. use Dcat\Admin\Form\Field;
  6. use Dcat\Admin\Form\NestedForm;
  7. use Dcat\Admin\Support\Helper;
  8. use Illuminate\Support\Arr;
  9. use Illuminate\Support\Facades\Validator;
  10. use Illuminate\Support\Str;
  11. /**
  12. * Class HasMany.
  13. */
  14. class HasMany extends Field
  15. {
  16. /**
  17. * Relation name.
  18. *
  19. * @var string
  20. */
  21. protected $relationName = '';
  22. /**
  23. * Relation key name.
  24. *
  25. * @var string
  26. */
  27. protected $relationKeyName = 'id';
  28. /**
  29. * Form builder.
  30. *
  31. * @var \Closure
  32. */
  33. protected $builder = null;
  34. /**
  35. * Form data.
  36. *
  37. * @var array
  38. */
  39. protected $value = [];
  40. /**
  41. * View Mode.
  42. *
  43. * Supports `default` and `tab` currently.
  44. *
  45. * @var string
  46. */
  47. protected $viewMode = 'default';
  48. /**
  49. * Available views for HasMany field.
  50. *
  51. * @var array
  52. */
  53. protected $views = [
  54. 'default' => 'admin::form.hasmany',
  55. 'tab' => 'admin::form.hasmanytab',
  56. 'table' => 'admin::form.hasmanytable',
  57. ];
  58. /**
  59. * Options for template.
  60. *
  61. * @var array
  62. */
  63. protected $options = [
  64. 'allowCreate' => true,
  65. 'allowDelete' => true,
  66. ];
  67. /**
  68. * Create a new HasMany field instance.
  69. *
  70. * @param $relationName
  71. * @param array $arguments
  72. */
  73. public function __construct($relationName, $arguments = [])
  74. {
  75. $this->relationName = $relationName;
  76. $this->column = $relationName;
  77. if (count($arguments) == 1) {
  78. $this->label = $this->formatLabel();
  79. $this->builder = $arguments[0];
  80. }
  81. if (count($arguments) == 2) {
  82. [$this->label, $this->builder] = $arguments;
  83. }
  84. }
  85. /**
  86. * Get validator for this field.
  87. *
  88. * @param array $input
  89. *
  90. * @return bool|Validator
  91. */
  92. public function getValidator(array $input)
  93. {
  94. if (! array_key_exists($this->column, $input)) {
  95. return false;
  96. }
  97. $input = Arr::only($input, $this->column);
  98. $form = $this->buildNestedForm();
  99. $rules = $attributes = $messages = [];
  100. /* @var Field $field */
  101. foreach ($form->fields() as $field) {
  102. if (! $fieldRules = $field->getRules()) {
  103. continue;
  104. }
  105. if ($field instanceof File) {
  106. $fieldRules = is_string($fieldRules) ? explode('|', $fieldRules) : $fieldRules;
  107. Helper::deleteByValue($fieldRules, ['image', 'file']);
  108. }
  109. $column = $field->column();
  110. if (is_array($column)) {
  111. foreach ($column as $key => $name) {
  112. $rules[$name.$key] = $fieldRules;
  113. }
  114. $this->resetInputKey($input, $column);
  115. } else {
  116. $rules[$column] = $fieldRules;
  117. }
  118. $attributes = array_merge(
  119. $attributes,
  120. $this->formatValidationAttribute($input, $field->label(), $column)
  121. );
  122. $messages = array_merge(
  123. $messages,
  124. $this->formatValidationMessages($input, $field->getValidationMessages())
  125. );
  126. }
  127. Arr::forget($rules, NestedForm::REMOVE_FLAG_NAME);
  128. if (empty($rules)) {
  129. return false;
  130. }
  131. $newRules = [];
  132. $newInput = [];
  133. foreach ($rules as $column => $rule) {
  134. foreach (array_keys($input[$this->column]) as $key) {
  135. if ($input[$this->column][$key][NestedForm::REMOVE_FLAG_NAME]) {
  136. continue;
  137. }
  138. $newRules["{$this->column}.$key.$column"] = $rule;
  139. if (isset($input[$this->column][$key][$column]) &&
  140. is_array($input[$this->column][$key][$column])) {
  141. foreach ($input[$this->column][$key][$column] as $vkey => $value) {
  142. $newInput["{$this->column}.$key.{$column}$vkey"] = $value;
  143. }
  144. }
  145. }
  146. }
  147. if (empty($newInput)) {
  148. $newInput = $input;
  149. }
  150. return Validator::make($newInput, $newRules, array_merge($this->getValidationMessages(), $messages), $attributes);
  151. }
  152. /**
  153. * Format validation messages.
  154. *
  155. * @param array $input
  156. * @param array $messages
  157. *
  158. * @return array
  159. */
  160. protected function formatValidationMessages(array $input, array $messages)
  161. {
  162. $result = [];
  163. foreach ($input[$this->column] as $key => &$value) {
  164. $newKey = $this->column.'.'.$key;
  165. foreach ($messages as $k => $message) {
  166. $result[$newKey.'.'.$k] = $message;
  167. }
  168. }
  169. return $result;
  170. }
  171. /**
  172. * Format validation attributes.
  173. *
  174. * @param array $input
  175. * @param string $label
  176. * @param string $column
  177. *
  178. * @return array
  179. */
  180. protected function formatValidationAttribute($input, $label, $column)
  181. {
  182. $new = $attributes = [];
  183. if (is_array($column)) {
  184. foreach ($column as $index => $col) {
  185. $new[$col.$index] = $col;
  186. }
  187. }
  188. foreach (array_keys(Arr::dot($input)) as $key) {
  189. if (is_string($column)) {
  190. if (Str::endsWith($key, ".$column")) {
  191. $attributes[$key] = $label;
  192. }
  193. } else {
  194. foreach ($new as $k => $val) {
  195. if (Str::endsWith($key, ".$k")) {
  196. $attributes[$key] = $label."[$val]";
  197. }
  198. }
  199. }
  200. }
  201. return $attributes;
  202. }
  203. /**
  204. * Reset input key for validation.
  205. *
  206. * @param array $input
  207. * @param array $column $column is the column name array set
  208. *
  209. * @return void.
  210. */
  211. protected function resetInputKey(array &$input, array $column)
  212. {
  213. /**
  214. * flip the column name array set.
  215. *
  216. * for example, for the DateRange, the column like as below
  217. *
  218. * ["start" => "created_at", "end" => "updated_at"]
  219. *
  220. * to:
  221. *
  222. * [ "created_at" => "start", "updated_at" => "end" ]
  223. */
  224. $column = array_flip($column);
  225. /**
  226. * $this->column is the inputs array's node name, default is the relation name.
  227. *
  228. * So... $input[$this->column] is the data of this column's inputs data
  229. *
  230. * in the HasMany relation, has many data/field set, $set is field set in the below
  231. */
  232. foreach ($input[$this->column] as $index => $set) {
  233. /*
  234. * foreach the field set to find the corresponding $column
  235. */
  236. foreach ($set as $name => $value) {
  237. /*
  238. * if doesn't have column name, continue to the next loop
  239. */
  240. if (! array_key_exists($name, $column)) {
  241. continue;
  242. }
  243. /**
  244. * example: $newKey = created_atstart.
  245. *
  246. * Σ( ° △ °|||)︴
  247. *
  248. * I don't know why a form need range input? Only can imagine is for range search....
  249. */
  250. $newKey = $name.$column[$name];
  251. /*
  252. * set new key
  253. */
  254. Arr::set($input, "{$this->column}.$index.$newKey", $value);
  255. /*
  256. * forget the old key and value
  257. */
  258. Arr::forget($input, "{$this->column}.$index.$name");
  259. }
  260. }
  261. }
  262. /**
  263. * Prepare input data for insert or update.
  264. *
  265. * @param array $input
  266. *
  267. * @return array
  268. */
  269. protected function prepareInputValue($input)
  270. {
  271. $form = $this->buildNestedForm();
  272. return array_values(
  273. $form->setOriginal($this->original, $this->getKeyName())->prepare($input)
  274. );
  275. }
  276. /**
  277. * Build a Nested form.
  278. *
  279. * @param null $key
  280. *
  281. * @return NestedForm
  282. */
  283. public function buildNestedForm($key = null)
  284. {
  285. $form = new Form\NestedForm($this->column, $key);
  286. $form->setForm($this->form);
  287. call_user_func($this->builder, $form);
  288. $form->hidden($this->getKeyName());
  289. $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
  290. return $form;
  291. }
  292. /**
  293. * Get the HasMany relation key name.
  294. *
  295. * @return string
  296. */
  297. public function getKeyName()
  298. {
  299. if (is_null($this->form)) {
  300. return;
  301. }
  302. return $this->relationKeyName;
  303. }
  304. /**
  305. * @param string $relationKeyName
  306. */
  307. public function setRelationKeyName(?string $relationKeyName)
  308. {
  309. $this->relationKeyName = $relationKeyName;
  310. return $this;
  311. }
  312. /**
  313. * Set view mode.
  314. *
  315. * @param string $mode currently support `tab` mode.
  316. *
  317. * @return $this
  318. *
  319. * @author Edwin Hui
  320. */
  321. public function mode($mode)
  322. {
  323. $this->viewMode = $mode;
  324. return $this;
  325. }
  326. /**
  327. * Use tab mode to showing hasmany field.
  328. *
  329. * @return HasMany
  330. */
  331. public function useTab()
  332. {
  333. return $this->mode('tab');
  334. }
  335. /**
  336. * Use table mode to showing hasmany field.
  337. *
  338. * @return HasMany
  339. */
  340. public function useTable()
  341. {
  342. return $this->mode('table');
  343. }
  344. /**
  345. * Build Nested form for related data.
  346. *
  347. * @throws \Exception
  348. *
  349. * @return array
  350. */
  351. protected function buildRelatedForms()
  352. {
  353. if (is_null($this->form)) {
  354. return [];
  355. }
  356. $forms = [];
  357. /*
  358. * If redirect from `exception` or `validation error` page.
  359. *
  360. * Then get form data from session flash.
  361. *
  362. * Else get data from database.
  363. */
  364. foreach (Helper::array($this->value()) as $idx => $data) {
  365. $key = Arr::get($data, $this->getKeyName(), $idx);
  366. $forms[$key] = $this->buildNestedForm($key)
  367. ->fill($data);
  368. }
  369. return $forms;
  370. }
  371. /**
  372. * Setup script for this field in different view mode.
  373. *
  374. * @param string $script
  375. *
  376. * @return void
  377. */
  378. protected function setupScript($script)
  379. {
  380. $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
  381. call_user_func([$this, $method], $script);
  382. }
  383. /**
  384. * Setup default template script.
  385. *
  386. * @param string $templateScript
  387. *
  388. * @return void
  389. */
  390. protected function setupScriptForDefaultView($templateScript)
  391. {
  392. $removeClass = NestedForm::REMOVE_FLAG_CLASS;
  393. /**
  394. * When add a new sub form, replace all element key in new sub form.
  395. *
  396. * @example comments[new___key__][title] => comments[new_{index}][title]
  397. *
  398. * {count} is increment number of current sub form count.
  399. */
  400. $script = <<<JS
  401. (function () {
  402. var nestedIndex = 0;
  403. {$this->makeReplaceNestedIndexScript()}
  404. $('{$this->getContainerElementSelector()}').on('click', '.add', function () {
  405. var tpl = $('template.{$this->column}-tpl');
  406. nestedIndex++;
  407. var template = replaceNestedFormIndex(tpl.html());
  408. $('.has-many-{$this->column}-forms').append(template);
  409. {$templateScript}
  410. });
  411. $('{$this->getContainerElementSelector()}').on('click', '.remove', function () {
  412. $(this).closest('.has-many-{$this->column}-form').hide();
  413. $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
  414. });
  415. })()
  416. JS;
  417. Admin::script($script);
  418. }
  419. /**
  420. * Setup tab template script.
  421. *
  422. * @param string $templateScript
  423. *
  424. * @return void
  425. */
  426. protected function setupScriptForTabView($templateScript)
  427. {
  428. $removeClass = NestedForm::REMOVE_FLAG_CLASS;
  429. $script = <<<JS
  430. (function () {
  431. $('{$this->getContainerElementSelector()} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
  432. var \$navTab = $(this).siblings('a');
  433. var \$pane = $(\$navTab.attr('href'));
  434. if( \$pane.hasClass('new') ){
  435. \$pane.remove();
  436. }else{
  437. \$pane.removeClass('active').find('.$removeClass').val(1);
  438. }
  439. if(\$navTab.closest('li').hasClass('active')){
  440. \$navTab.closest('li').remove();
  441. $('{$this->getContainerElementSelector()} > .nav > li:nth-child(1) > a').click();
  442. }else{
  443. \$navTab.closest('li').remove();
  444. }
  445. });
  446. {$this->makeReplaceNestedIndexScript()}
  447. var nestedIndex = 0;
  448. $('{$this->getContainerElementSelector()} > .header').off('click', '.add').on('click', '.add', function(){
  449. nestedIndex++;
  450. var navTabHtml = replaceNestedFormIndex($('{$this->getContainerElementSelector()} > template.nav-tab-tpl').html());
  451. var paneHtml = replaceNestedFormIndex($('{$this->getContainerElementSelector()} > template.pane-tpl').html());
  452. $('{$this->getContainerElementSelector()} > .nav').append(navTabHtml);
  453. $('{$this->getContainerElementSelector()} > .tab-content').append(paneHtml);
  454. $('{$this->getContainerElementSelector()} > .nav > li:last-child a').click();
  455. {$templateScript}
  456. });
  457. if ($('.has-error').length) {
  458. $('.has-error').parent('.tab-pane').each(function () {
  459. var tabId = '#'+$(this).attr('id');
  460. $('li a[href="'+tabId+'"] i').removeClass('d-none');
  461. });
  462. var first = $('.has-error:first').parent().attr('id');
  463. $('li a[href="#'+first+'"]').tab('show');
  464. }
  465. })();
  466. JS;
  467. Admin::script($script);
  468. }
  469. /**
  470. * Setup default template script.
  471. *
  472. * @param string $templateScript
  473. *
  474. * @return void
  475. */
  476. protected function setupScriptForTableView($templateScript)
  477. {
  478. $removeClass = NestedForm::REMOVE_FLAG_CLASS;
  479. /**
  480. * When add a new sub form, replace all element key in new sub form.
  481. *
  482. * @example comments[new___key__][title] => comments[new_{index}][title]
  483. *
  484. * {count} is increment number of current sub form count.
  485. */
  486. $script = <<<JS
  487. (function () {
  488. var nestedIndex = 0;
  489. {$this->makeReplaceNestedIndexScript()}
  490. $('{$this->getContainerElementSelector()}').on('click', '.add', function () {
  491. var tpl = $('template.{$this->column}-tpl');
  492. nestedIndex++;
  493. var template = replaceNestedFormIndex(tpl.html());
  494. $('.has-many-{$this->column}-forms').append(template);
  495. {$templateScript}
  496. });
  497. $('{$this->getContainerElementSelector()}').on('click', '.remove', function () {
  498. $(this).closest('.has-many-{$this->column}-form').hide();
  499. $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
  500. });
  501. })();
  502. JS;
  503. Admin::script($script);
  504. }
  505. /**
  506. * @return string
  507. */
  508. protected function getContainerElementSelector()
  509. {
  510. return ".has-many-{$this->column}";
  511. }
  512. /**
  513. * @return string
  514. */
  515. protected function makeReplaceNestedIndexScript()
  516. {
  517. $defaultKey = NestedForm::DEFAULT_KEY_NAME;
  518. return <<<JS
  519. function replaceNestedFormIndex(value) {
  520. return String(value).replace(/{$defaultKey}/g, nestedIndex);
  521. }
  522. JS;
  523. }
  524. /**
  525. * Disable create button.
  526. *
  527. * @return $this
  528. */
  529. public function disableCreate()
  530. {
  531. $this->options['allowCreate'] = false;
  532. return $this;
  533. }
  534. /**
  535. * Disable delete button.
  536. *
  537. * @return $this
  538. */
  539. public function disableDelete()
  540. {
  541. $this->options['allowDelete'] = false;
  542. return $this;
  543. }
  544. /**
  545. * Render the `HasMany` field.
  546. *
  547. * @throws \Exception
  548. *
  549. * @return \Illuminate\View\View|string
  550. */
  551. public function render()
  552. {
  553. if (! $this->shouldRender()) {
  554. return '';
  555. }
  556. if ($this->viewMode == 'table') {
  557. return $this->renderTable();
  558. }
  559. // specify a view to render.
  560. $this->view = $this->views[$this->viewMode];
  561. [$template, $script] = $this->buildNestedForm()
  562. ->getTemplateHtmlAndScript();
  563. $this->setupScript($script);
  564. return parent::render()->with([
  565. 'forms' => $this->buildRelatedForms(),
  566. 'template' => $template,
  567. 'relationName' => $this->relationName,
  568. 'options' => $this->options,
  569. ]);
  570. }
  571. /**
  572. * Render the `HasMany` field for table style.
  573. *
  574. * @throws \Exception
  575. *
  576. * @return mixed
  577. */
  578. protected function renderTable()
  579. {
  580. $headers = [];
  581. $fields = [];
  582. $hidden = [];
  583. $scripts = [];
  584. /* @var Field $field */
  585. foreach ($this->buildNestedForm()->fields() as $field) {
  586. if (is_a($field, Hidden::class)) {
  587. $hidden[] = $field->render();
  588. } else {
  589. /* Hide label and set field width 100% */
  590. $field->setLabelClass(['hidden']);
  591. $field->width(12, 0);
  592. $fields[] = $field->render();
  593. $headers[] = $field->label();
  594. }
  595. /*
  596. * Get and remove the last script of Admin::$script stack.
  597. */
  598. if ($field->getScript()) {
  599. $scripts[] = array_pop(Admin::asset()->script);
  600. }
  601. }
  602. /* Build row elements */
  603. $template = array_reduce($fields, function ($all, $field) {
  604. $all .= "<td>{$field}</td>";
  605. return $all;
  606. }, '');
  607. /* Build cell with hidden elements */
  608. $template .= '<td class="hidden">'.implode('', $hidden).'</td>';
  609. $this->setupScript(implode(";\r\n", $scripts));
  610. // specify a view to render.
  611. $this->view = $this->views[$this->viewMode];
  612. Admin::style('.table-has-many .input-group{flex-wrap: nowrap!important}');
  613. return parent::render()->with([
  614. 'headers' => $headers,
  615. 'forms' => $this->buildRelatedForms(),
  616. 'template' => $template,
  617. 'relationName' => $this->relationName,
  618. 'options' => $this->options,
  619. ]);
  620. }
  621. }