HasMany.php 14 KB

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