HasMany.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. <?php
  2. namespace Dcat\Admin\Form\Field;
  3. use Dcat\Admin\Form;
  4. use Dcat\Admin\Form\Field;
  5. use Dcat\Admin\Form\NestedForm;
  6. use Dcat\Admin\Support\Helper;
  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. protected $columnClass;
  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. $this->columnClass = $this->formatClass($relationName);
  78. if (count($arguments) == 1) {
  79. $this->label = $this->formatLabel();
  80. $this->builder = $arguments[0];
  81. }
  82. if (count($arguments) == 2) {
  83. [$this->label, $this->builder] = $arguments;
  84. }
  85. }
  86. protected function formatClass(string $column)
  87. {
  88. return str_replace('.', '-', $column);
  89. }
  90. /**
  91. * Get validator for this field.
  92. *
  93. * @param array $input
  94. *
  95. * @return bool|Validator
  96. */
  97. public function getValidator(array $input)
  98. {
  99. if (! Arr::has($input, $this->column)) {
  100. return false;
  101. }
  102. $form = $this->buildNestedForm();
  103. $rules = $attributes = $messages = [];
  104. /* @var Field $field */
  105. foreach ($form->fields() as $field) {
  106. if (! $fieldRules = $field->getRules()) {
  107. continue;
  108. }
  109. if ($field instanceof File) {
  110. $fieldRules = is_string($fieldRules) ? explode('|', $fieldRules) : $fieldRules;
  111. Helper::deleteByValue($fieldRules, ['image', 'file']);
  112. }
  113. $column = $field->column();
  114. if (is_array($column)) {
  115. foreach ($column as $key => $name) {
  116. $rules[$name.$key] = $fieldRules;
  117. }
  118. $this->resetInputKey($input, $column);
  119. } else {
  120. $rules[$column] = $fieldRules;
  121. }
  122. $attributes = array_merge(
  123. $attributes,
  124. $this->formatValidationAttribute($input, $field->label(), $column)
  125. );
  126. $messages = array_merge(
  127. $messages,
  128. $this->formatValidationMessages($input, $field->getValidationMessages())
  129. );
  130. }
  131. Arr::forget($rules, NestedForm::REMOVE_FLAG_NAME);
  132. if (empty($rules)) {
  133. return false;
  134. }
  135. $newRules = [];
  136. $newInput = [];
  137. foreach ($rules as $column => $rule) {
  138. foreach (array_keys(Arr::get($input, $this->column)) as $key) {
  139. if (Arr::get($input, "{$this->column}.{$key}.".NestedForm::REMOVE_FLAG_NAME)) {
  140. continue;
  141. }
  142. $newRules["{$this->column}.$key.$column"] = $rule;
  143. $ruleValue = Arr::get($input, "{$this->column}.$key.$column");
  144. if (is_array($ruleValue)) {
  145. foreach ($ruleValue as $vkey => $value) {
  146. $newInput["{$this->column}.$key.{$column}$vkey"] = $value;
  147. }
  148. }
  149. }
  150. }
  151. if (empty($newInput)) {
  152. $newInput = $input;
  153. }
  154. return Validator::make($newInput, $newRules, array_merge($this->getValidationMessages(), $messages), $attributes);
  155. }
  156. /**
  157. * Format validation messages.
  158. *
  159. * @param array $input
  160. * @param array $messages
  161. *
  162. * @return array
  163. */
  164. protected function formatValidationMessages(array $input, array $messages)
  165. {
  166. $result = [];
  167. foreach (Arr::get($input, $this->column) as $key => &$value) {
  168. $newKey = $this->column.'.'.$key;
  169. foreach ($messages as $k => $message) {
  170. $result[$newKey.'.'.$k] = $message;
  171. }
  172. }
  173. return $result;
  174. }
  175. /**
  176. * Format validation attributes.
  177. *
  178. * @param array $input
  179. * @param string $label
  180. * @param string $column
  181. *
  182. * @return array
  183. */
  184. protected function formatValidationAttribute($input, $label, $column)
  185. {
  186. $new = $attributes = [];
  187. if (is_array($column)) {
  188. foreach ($column as $index => $col) {
  189. $new[$col.$index] = $col;
  190. }
  191. }
  192. foreach (array_keys(Arr::dot($input)) as $key) {
  193. if (is_string($column)) {
  194. if (Str::endsWith($key, ".$column")) {
  195. $attributes[$key] = $label;
  196. }
  197. } else {
  198. foreach ($new as $k => $val) {
  199. if (Str::endsWith($key, ".$k")) {
  200. $attributes[$key] = $label."[$val]";
  201. }
  202. }
  203. }
  204. }
  205. return $attributes;
  206. }
  207. /**
  208. * Reset input key for validation.
  209. *
  210. * @param array $input
  211. * @param array $column $column is the column name array set
  212. *
  213. * @return void.
  214. */
  215. protected function resetInputKey(array &$input, array $column)
  216. {
  217. /**
  218. * flip the column name array set.
  219. *
  220. * for example, for the DateRange, the column like as below
  221. *
  222. * ["start" => "created_at", "end" => "updated_at"]
  223. *
  224. * to:
  225. *
  226. * [ "created_at" => "start", "updated_at" => "end" ]
  227. */
  228. $column = array_flip($column);
  229. /**
  230. * $this->column is the inputs array's node name, default is the relation name.
  231. *
  232. * So... $input[$this->column] is the data of this column's inputs data
  233. *
  234. * in the HasMany relation, has many data/field set, $set is field set in the below
  235. */
  236. foreach (Arr::get($input, $this->column) as $index => $set) {
  237. /*
  238. * foreach the field set to find the corresponding $column
  239. */
  240. foreach ($set as $name => $value) {
  241. /*
  242. * if doesn't have column name, continue to the next loop
  243. */
  244. if (! array_key_exists($name, $column)) {
  245. continue;
  246. }
  247. /**
  248. * example: $newKey = created_atstart.
  249. *
  250. * Σ( ° △ °|||)︴
  251. *
  252. * I don't know why a form need range input? Only can imagine is for range search....
  253. */
  254. $newKey = $name.$column[$name];
  255. /*
  256. * set new key
  257. */
  258. Arr::set($input, "{$this->column}.$index.$newKey", $value);
  259. /*
  260. * forget the old key and value
  261. */
  262. Arr::forget($input, "{$this->column}.$index.$name");
  263. }
  264. }
  265. }
  266. /**
  267. * Prepare input data for insert or update.
  268. *
  269. * @param array $input
  270. *
  271. * @return array
  272. */
  273. protected function prepareInputValue($input)
  274. {
  275. $form = $this->buildNestedForm();
  276. return array_values(
  277. $form->setOriginal($this->original, $this->getKeyName())->prepare($input)
  278. );
  279. }
  280. /**
  281. * Build a Nested form.
  282. *
  283. * @param null $key
  284. *
  285. * @return NestedForm
  286. */
  287. public function buildNestedForm($key = null)
  288. {
  289. $form = new Form\NestedForm($this->column, $key);
  290. $form->setForm($this->form);
  291. call_user_func($this->builder, $form);
  292. $form->hidden($this->getKeyName());
  293. $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
  294. return $form;
  295. }
  296. /**
  297. * Get the HasMany relation key name.
  298. *
  299. * @return string
  300. */
  301. public function getKeyName()
  302. {
  303. if (is_null($this->form)) {
  304. return;
  305. }
  306. return $this->relationKeyName;
  307. }
  308. /**
  309. * @param string $relationKeyName
  310. */
  311. public function setRelationKeyName(?string $relationKeyName)
  312. {
  313. $this->relationKeyName = $relationKeyName;
  314. return $this;
  315. }
  316. /**
  317. * Set view mode.
  318. *
  319. * @param string $mode currently support `tab` mode.
  320. *
  321. * @return $this
  322. *
  323. * @author Edwin Hui
  324. */
  325. public function mode($mode)
  326. {
  327. $this->viewMode = $mode;
  328. return $this;
  329. }
  330. /**
  331. * Use tab mode to showing hasmany field.
  332. *
  333. * @return HasMany
  334. */
  335. public function useTab()
  336. {
  337. return $this->mode('tab');
  338. }
  339. /**
  340. * Use table mode to showing hasmany field.
  341. *
  342. * @return HasMany
  343. */
  344. public function useTable()
  345. {
  346. return $this->mode('table');
  347. }
  348. /**
  349. * Build Nested form for related data.
  350. *
  351. * @throws \Exception
  352. *
  353. * @return array
  354. */
  355. protected function buildRelatedForms()
  356. {
  357. if (is_null($this->form)) {
  358. return [];
  359. }
  360. $forms = [];
  361. /*
  362. * If redirect from `exception` or `validation error` page.
  363. *
  364. * Then get form data from session flash.
  365. *
  366. * Else get data from database.
  367. */
  368. foreach (Helper::array($this->value()) as $idx => $data) {
  369. $key = Arr::get($data, $this->getKeyName(), $idx);
  370. $forms[$key] = $this->buildNestedForm($key)
  371. ->fill($data);
  372. }
  373. return $forms;
  374. }
  375. /**
  376. * Disable create button.
  377. *
  378. * @return $this
  379. */
  380. public function disableCreate()
  381. {
  382. $this->options['allowCreate'] = false;
  383. return $this;
  384. }
  385. /**
  386. * Disable delete button.
  387. *
  388. * @return $this
  389. */
  390. public function disableDelete()
  391. {
  392. $this->options['allowDelete'] = false;
  393. return $this;
  394. }
  395. public function value($value = null)
  396. {
  397. if ($value === null) {
  398. return Helper::array(parent::value($value));
  399. }
  400. return parent::value($value);
  401. }
  402. /**
  403. * Render the `HasMany` field.
  404. *
  405. * @throws \Exception
  406. *
  407. * @return \Illuminate\View\View|string
  408. */
  409. public function render()
  410. {
  411. if (! $this->shouldRender()) {
  412. return '';
  413. }
  414. if ($this->viewMode == 'table') {
  415. return $this->renderTable();
  416. }
  417. // specify a view to render.
  418. $this->view = $this->views[$this->viewMode];
  419. [$template, $script] = $this->buildNestedForm()
  420. ->getTemplateHtmlAndScript();
  421. $this->addVariables([
  422. 'forms' => $this->buildRelatedForms(),
  423. 'template' => $template,
  424. 'relationName' => $this->relationName,
  425. 'options' => $this->options,
  426. 'templateScript' => $script,
  427. 'count' => count($this->value()),
  428. 'columnClass' => $this->columnClass,
  429. ]);
  430. return parent::render();
  431. }
  432. /**
  433. * Render the `HasMany` field for table style.
  434. *
  435. * @throws \Exception
  436. *
  437. * @return mixed
  438. */
  439. protected function renderTable()
  440. {
  441. $headers = [];
  442. $fields = [];
  443. $hidden = [];
  444. $scripts = [];
  445. /* @var Field $field */
  446. foreach ($this->buildNestedForm()->fields() as $field) {
  447. $field->runScript(false);
  448. if (is_a($field, Hidden::class)) {
  449. $hidden[] = $field->render();
  450. } else {
  451. /* Hide label and set field width 100% */
  452. $field->setLabelClass(['hidden']);
  453. $field->width(12, 0);
  454. $fields[] = $field->render();
  455. $headers[] = $field->label();
  456. }
  457. /*
  458. * Get and remove the last script of Admin::$script stack.
  459. */
  460. if ($script = $field->getScript()) {
  461. $scripts[] = $script;
  462. }
  463. }
  464. /* Build row elements */
  465. $template = array_reduce($fields, function ($all, $field) {
  466. $all .= "<td>{$field}</td>";
  467. return $all;
  468. }, '');
  469. /* Build cell with hidden elements */
  470. $template .= '<td class="hidden">'.implode('', $hidden).'</td>';
  471. // specify a view to render.
  472. $this->view = $this->views[$this->viewMode];
  473. $this->addVariables([
  474. 'headers' => $headers,
  475. 'forms' => $this->buildRelatedForms(),
  476. 'template' => $template,
  477. 'relationName' => $this->relationName,
  478. 'options' => $this->options,
  479. 'templateScript' => implode(";\r\n", $scripts),
  480. 'count' => count($this->value()),
  481. 'columnClass' => $this->columnClass,
  482. ]);
  483. return parent::render();
  484. }
  485. }