HasMany.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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();
  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();
  267. return array_values(
  268. $form->setOriginal($this->original, $this->getKeyName())->prepare($input)
  269. );
  270. }
  271. /**
  272. * Build a Nested form.
  273. *
  274. * @param null $key
  275. *
  276. * @return NestedForm
  277. */
  278. public function buildNestedForm($key = null)
  279. {
  280. $form = new Form\NestedForm($this->column, $key);
  281. $form->setForm($this->form);
  282. call_user_func($this->builder, $form);
  283. $form->hidden($this->getKeyName());
  284. $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
  285. return $form;
  286. }
  287. /**
  288. * Get the HasMany relation key name.
  289. *
  290. * @return string
  291. */
  292. protected function getKeyName()
  293. {
  294. if (is_null($this->form)) {
  295. return;
  296. }
  297. return $this->relationKeyName;
  298. }
  299. /**
  300. * @param string $relationKeyName
  301. */
  302. public function setRelationKeyName(?string $relationKeyName)
  303. {
  304. $this->relationKeyName = $relationKeyName;
  305. return $this;
  306. }
  307. /**
  308. * Set view mode.
  309. *
  310. * @param string $mode currently support `tab` mode.
  311. *
  312. * @return $this
  313. *
  314. * @author Edwin Hui
  315. */
  316. public function mode($mode)
  317. {
  318. $this->viewMode = $mode;
  319. return $this;
  320. }
  321. /**
  322. * Use tab mode to showing hasmany field.
  323. *
  324. * @return HasMany
  325. */
  326. public function useTab()
  327. {
  328. return $this->mode('tab');
  329. }
  330. /**
  331. * Use table mode to showing hasmany field.
  332. *
  333. * @return HasMany
  334. */
  335. public function useTable()
  336. {
  337. return $this->mode('table');
  338. }
  339. /**
  340. * Build Nested form for related data.
  341. *
  342. * @throws \Exception
  343. *
  344. * @return array
  345. */
  346. protected function buildRelatedForms()
  347. {
  348. if (is_null($this->form)) {
  349. return [];
  350. }
  351. $forms = [];
  352. /*
  353. * If redirect from `exception` or `validation error` page.
  354. *
  355. * Then get form data from session flash.
  356. *
  357. * Else get data from database.
  358. */
  359. if ($values = old($this->column)) {
  360. foreach ($values as $key => $data) {
  361. if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
  362. continue;
  363. }
  364. $forms[$key] = $this->buildNestedForm($key)
  365. ->fill($data);
  366. }
  367. } else {
  368. if (is_array($this->value)) {
  369. foreach ($this->value as $idx => $data) {
  370. $key = Arr::get($data, $this->getKeyName(), $idx);
  371. $forms[$key] = $this->buildNestedForm($key)
  372. ->fill($data);
  373. }
  374. }
  375. }
  376. return $forms;
  377. }
  378. /**
  379. * Setup script for this field in different view mode.
  380. *
  381. * @param string $script
  382. *
  383. * @return void
  384. */
  385. protected function setupScript($script)
  386. {
  387. $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
  388. call_user_func([$this, $method], $script);
  389. }
  390. /**
  391. * Setup default template script.
  392. *
  393. * @param string $templateScript
  394. *
  395. * @return void
  396. */
  397. protected function setupScriptForDefaultView($templateScript)
  398. {
  399. $removeClass = NestedForm::REMOVE_FLAG_CLASS;
  400. $defaultKey = NestedForm::DEFAULT_KEY_NAME;
  401. /**
  402. * When add a new sub form, replace all element key in new sub form.
  403. *
  404. * @example comments[new___key__][title] => comments[new_{index}][title]
  405. *
  406. * {count} is increment number of current sub form count.
  407. */
  408. $script = <<<JS
  409. (function () {
  410. var index = 0;
  411. $('#has-many-{$this->column}').on('click', '.add', function () {
  412. var tpl = $('template.{$this->column}-tpl');
  413. index++;
  414. var template = tpl.html().replace(/{$defaultKey}/g, index);
  415. $('.has-many-{$this->column}-forms').append(template);
  416. {$templateScript}
  417. });
  418. $('#has-many-{$this->column}').on('click', '.remove', function () {
  419. $(this).closest('.has-many-{$this->column}-form').hide();
  420. $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
  421. });
  422. })();
  423. JS;
  424. Admin::script($script);
  425. }
  426. /**
  427. * Setup tab template script.
  428. *
  429. * @param string $templateScript
  430. *
  431. * @return void
  432. */
  433. protected function setupScriptForTabView($templateScript)
  434. {
  435. $removeClass = NestedForm::REMOVE_FLAG_CLASS;
  436. $defaultKey = NestedForm::DEFAULT_KEY_NAME;
  437. $script = <<<JS
  438. (function () {
  439. $('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
  440. var \$navTab = $(this).siblings('a');
  441. var \$pane = $(\$navTab.attr('href'));
  442. if( \$pane.hasClass('new') ){
  443. \$pane.remove();
  444. }else{
  445. \$pane.removeClass('active').find('.$removeClass').val(1);
  446. }
  447. if(\$navTab.closest('li').hasClass('active')){
  448. \$navTab.closest('li').remove();
  449. $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').click();
  450. }else{
  451. \$navTab.closest('li').remove();
  452. }
  453. });
  454. var index = 0;
  455. $('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
  456. index++;
  457. var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
  458. var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
  459. $('#has-many-{$this->column} > .nav').append(navTabHtml);
  460. $('#has-many-{$this->column} > .tab-content').append(paneHtml);
  461. $('#has-many-{$this->column} > .nav > li:last-child a').click();
  462. {$templateScript}
  463. });
  464. if ($('.has-error').length) {
  465. $('.has-error').parent('.tab-pane').each(function () {
  466. var tabId = '#'+$(this).attr('id');
  467. $('li a[href="'+tabId+'"] i').removeClass('d-none');
  468. });
  469. var first = $('.has-error:first').parent().attr('id');
  470. $('li a[href="#'+first+'"]').tab('show');
  471. }
  472. })();
  473. JS;
  474. Admin::script($script);
  475. }
  476. /**
  477. * Setup default template script.
  478. *
  479. * @param string $templateScript
  480. *
  481. * @return void
  482. */
  483. protected function setupScriptForTableView($templateScript)
  484. {
  485. $removeClass = NestedForm::REMOVE_FLAG_CLASS;
  486. $defaultKey = NestedForm::DEFAULT_KEY_NAME;
  487. /**
  488. * When add a new sub form, replace all element key in new sub form.
  489. *
  490. * @example comments[new___key__][title] => comments[new_{index}][title]
  491. *
  492. * {count} is increment number of current sub form count.
  493. */
  494. $script = <<<JS
  495. (function () {
  496. var index = 0;
  497. $('#has-many-{$this->column}').on('click', '.add', function () {
  498. var tpl = $('template.{$this->column}-tpl');
  499. index++;
  500. var template = tpl.html().replace(/{$defaultKey}/g, index);
  501. $('.has-many-{$this->column}-forms').append(template);
  502. {$templateScript}
  503. });
  504. $('#has-many-{$this->column}').on('click', '.remove', function () {
  505. $(this).closest('.has-many-{$this->column}-form').hide();
  506. $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
  507. });
  508. })();
  509. JS;
  510. Admin::script($script);
  511. }
  512. /**
  513. * Disable create button.
  514. *
  515. * @return $this
  516. */
  517. public function disableCreate()
  518. {
  519. $this->options['allowCreate'] = false;
  520. return $this;
  521. }
  522. /**
  523. * Disable delete button.
  524. *
  525. * @return $this
  526. */
  527. public function disableDelete()
  528. {
  529. $this->options['allowDelete'] = false;
  530. return $this;
  531. }
  532. /**
  533. * Render the `HasMany` field.
  534. *
  535. * @throws \Exception
  536. *
  537. * @return \Illuminate\View\View|string
  538. */
  539. public function render()
  540. {
  541. if (! $this->shouldRender()) {
  542. return '';
  543. }
  544. if ($this->viewMode == 'table') {
  545. return $this->renderTable();
  546. }
  547. // specify a view to render.
  548. $this->view = $this->views[$this->viewMode];
  549. [$template, $script] = $this->buildNestedForm()
  550. ->getTemplateHtmlAndScript();
  551. $this->setupScript($script);
  552. return parent::render()->with([
  553. 'forms' => $this->buildRelatedForms(),
  554. 'template' => $template,
  555. 'relationName' => $this->relationName,
  556. 'options' => $this->options,
  557. ]);
  558. }
  559. /**
  560. * Render the `HasMany` field for table style.
  561. *
  562. * @throws \Exception
  563. *
  564. * @return mixed
  565. */
  566. protected function renderTable()
  567. {
  568. $headers = [];
  569. $fields = [];
  570. $hidden = [];
  571. $scripts = [];
  572. /* @var Field $field */
  573. foreach ($this->buildNestedForm()->fields() as $field) {
  574. if (is_a($field, Hidden::class)) {
  575. $hidden[] = $field->render();
  576. } else {
  577. /* Hide label and set field width 100% */
  578. $field->setLabelClass(['hidden']);
  579. $field->width(12, 0);
  580. $fields[] = $field->render();
  581. $headers[] = $field->label();
  582. }
  583. /*
  584. * Get and remove the last script of Admin::$script stack.
  585. */
  586. if ($field->getScript()) {
  587. $scripts[] = array_pop(Admin::asset()->script);
  588. }
  589. }
  590. /* Build row elements */
  591. $template = array_reduce($fields, function ($all, $field) {
  592. $all .= "<td>{$field}</td>";
  593. return $all;
  594. }, '');
  595. /* Build cell with hidden elements */
  596. $template .= '<td class="hidden">'.implode('', $hidden).'</td>';
  597. $this->setupScript(implode("\r\n", $scripts));
  598. // specify a view to render.
  599. $this->view = $this->views[$this->viewMode];
  600. return parent::render()->with([
  601. 'headers' => $headers,
  602. 'forms' => $this->buildRelatedForms(),
  603. 'template' => $template,
  604. 'relationName' => $this->relationName,
  605. 'options' => $this->options,
  606. ]);
  607. }
  608. }