HasMany.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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. if ($values = old($this->column)) {
  365. foreach ($values as $key => $data) {
  366. if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
  367. continue;
  368. }
  369. $forms[$key] = $this->buildNestedForm($key)
  370. ->fill($data);
  371. }
  372. } else {
  373. if (is_array($this->value)) {
  374. foreach ($this->value as $idx => $data) {
  375. $key = Arr::get($data, $this->getKeyName(), $idx);
  376. $forms[$key] = $this->buildNestedForm($key)
  377. ->fill($data);
  378. }
  379. }
  380. }
  381. return $forms;
  382. }
  383. /**
  384. * Setup script for this field in different view mode.
  385. *
  386. * @param string $script
  387. *
  388. * @return void
  389. */
  390. protected function setupScript($script)
  391. {
  392. $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
  393. call_user_func([$this, $method], $script);
  394. }
  395. /**
  396. * Setup default template script.
  397. *
  398. * @param string $templateScript
  399. *
  400. * @return void
  401. */
  402. protected function setupScriptForDefaultView($templateScript)
  403. {
  404. $removeClass = NestedForm::REMOVE_FLAG_CLASS;
  405. $defaultKey = NestedForm::DEFAULT_KEY_NAME;
  406. /**
  407. * When add a new sub form, replace all element key in new sub form.
  408. *
  409. * @example comments[new___key__][title] => comments[new_{index}][title]
  410. *
  411. * {count} is increment number of current sub form count.
  412. */
  413. $script = <<<JS
  414. (function () {
  415. var nestedIndex = 0;
  416. $('#has-many-{$this->column}').on('click', '.add', function () {
  417. var tpl = $('template.{$this->column}-tpl');
  418. nestedIndex++;
  419. var template = tpl.html().replace(/{$defaultKey}/g, nestedIndex);
  420. $('.has-many-{$this->column}-forms').append(template);
  421. {$templateScript}
  422. });
  423. $('#has-many-{$this->column}').on('click', '.remove', function () {
  424. $(this).closest('.has-many-{$this->column}-form').hide();
  425. $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
  426. });
  427. })();
  428. JS;
  429. Admin::script($script);
  430. }
  431. /**
  432. * Setup tab template script.
  433. *
  434. * @param string $templateScript
  435. *
  436. * @return void
  437. */
  438. protected function setupScriptForTabView($templateScript)
  439. {
  440. $removeClass = NestedForm::REMOVE_FLAG_CLASS;
  441. $defaultKey = NestedForm::DEFAULT_KEY_NAME;
  442. $script = <<<JS
  443. (function () {
  444. $('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
  445. var \$navTab = $(this).siblings('a');
  446. var \$pane = $(\$navTab.attr('href'));
  447. if( \$pane.hasClass('new') ){
  448. \$pane.remove();
  449. }else{
  450. \$pane.removeClass('active').find('.$removeClass').val(1);
  451. }
  452. if(\$navTab.closest('li').hasClass('active')){
  453. \$navTab.closest('li').remove();
  454. $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').click();
  455. }else{
  456. \$navTab.closest('li').remove();
  457. }
  458. });
  459. var nestedIndex = 0;
  460. $('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
  461. nestedIndex++;
  462. var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, nestedIndex);
  463. var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, nestedIndex);
  464. $('#has-many-{$this->column} > .nav').append(navTabHtml);
  465. $('#has-many-{$this->column} > .tab-content').append(paneHtml);
  466. $('#has-many-{$this->column} > .nav > li:last-child a').click();
  467. {$templateScript}
  468. });
  469. if ($('.has-error').length) {
  470. $('.has-error').parent('.tab-pane').each(function () {
  471. var tabId = '#'+$(this).attr('id');
  472. $('li a[href="'+tabId+'"] i').removeClass('d-none');
  473. });
  474. var first = $('.has-error:first').parent().attr('id');
  475. $('li a[href="#'+first+'"]').tab('show');
  476. }
  477. })();
  478. JS;
  479. Admin::script($script);
  480. }
  481. /**
  482. * Setup default template script.
  483. *
  484. * @param string $templateScript
  485. *
  486. * @return void
  487. */
  488. protected function setupScriptForTableView($templateScript)
  489. {
  490. $removeClass = NestedForm::REMOVE_FLAG_CLASS;
  491. $defaultKey = NestedForm::DEFAULT_KEY_NAME;
  492. /**
  493. * When add a new sub form, replace all element key in new sub form.
  494. *
  495. * @example comments[new___key__][title] => comments[new_{index}][title]
  496. *
  497. * {count} is increment number of current sub form count.
  498. */
  499. $script = <<<JS
  500. (function () {
  501. var nestedIndex = 0;
  502. $('#has-many-{$this->column}').on('click', '.add', function () {
  503. var tpl = $('template.{$this->column}-tpl');
  504. nestedIndex++;
  505. var template = tpl.html().replace(/{$defaultKey}/g, nestedIndex);
  506. $('.has-many-{$this->column}-forms').append(template);
  507. {$templateScript}
  508. });
  509. $('#has-many-{$this->column}').on('click', '.remove', function () {
  510. $(this).closest('.has-many-{$this->column}-form').hide();
  511. $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
  512. });
  513. })();
  514. JS;
  515. Admin::script($script);
  516. }
  517. /**
  518. * Disable create button.
  519. *
  520. * @return $this
  521. */
  522. public function disableCreate()
  523. {
  524. $this->options['allowCreate'] = false;
  525. return $this;
  526. }
  527. /**
  528. * Disable delete button.
  529. *
  530. * @return $this
  531. */
  532. public function disableDelete()
  533. {
  534. $this->options['allowDelete'] = false;
  535. return $this;
  536. }
  537. /**
  538. * Render the `HasMany` field.
  539. *
  540. * @throws \Exception
  541. *
  542. * @return \Illuminate\View\View|string
  543. */
  544. public function render()
  545. {
  546. if (! $this->shouldRender()) {
  547. return '';
  548. }
  549. if ($this->viewMode == 'table') {
  550. return $this->renderTable();
  551. }
  552. // specify a view to render.
  553. $this->view = $this->views[$this->viewMode];
  554. [$template, $script] = $this->buildNestedForm()
  555. ->getTemplateHtmlAndScript();
  556. $this->setupScript($script);
  557. return parent::render()->with([
  558. 'forms' => $this->buildRelatedForms(),
  559. 'template' => $template,
  560. 'relationName' => $this->relationName,
  561. 'options' => $this->options,
  562. ]);
  563. }
  564. /**
  565. * Render the `HasMany` field for table style.
  566. *
  567. * @throws \Exception
  568. *
  569. * @return mixed
  570. */
  571. protected function renderTable()
  572. {
  573. $headers = [];
  574. $fields = [];
  575. $hidden = [];
  576. $scripts = [];
  577. /* @var Field $field */
  578. foreach ($this->buildNestedForm()->fields() as $field) {
  579. if (is_a($field, Hidden::class)) {
  580. $hidden[] = $field->render();
  581. } else {
  582. /* Hide label and set field width 100% */
  583. $field->setLabelClass(['hidden']);
  584. $field->width(12, 0);
  585. $fields[] = $field->render();
  586. $headers[] = $field->label();
  587. }
  588. /*
  589. * Get and remove the last script of Admin::$script stack.
  590. */
  591. if ($field->getScript()) {
  592. $scripts[] = array_pop(Admin::asset()->script);
  593. }
  594. }
  595. /* Build row elements */
  596. $template = array_reduce($fields, function ($all, $field) {
  597. $all .= "<td>{$field}</td>";
  598. return $all;
  599. }, '');
  600. /* Build cell with hidden elements */
  601. $template .= '<td class="hidden">'.implode('', $hidden).'</td>';
  602. $this->setupScript(implode("\r\n", $scripts));
  603. // specify a view to render.
  604. $this->view = $this->views[$this->viewMode];
  605. Admin::style('.table-has-many .input-group{flex-wrap: nowrap!important}');
  606. return parent::render()->with([
  607. 'headers' => $headers,
  608. 'forms' => $this->buildRelatedForms(),
  609. 'template' => $template,
  610. 'relationName' => $this->relationName,
  611. 'options' => $this->options,
  612. ]);
  613. }
  614. }