HasMany.php 18 KB

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