HasMany.php 14 KB

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