Form.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  1. <?php
  2. namespace Dcat\Admin;
  3. use Closure;
  4. use Dcat\Admin\Form\Builder;
  5. use Dcat\Admin\Form\Condition;
  6. use Dcat\Admin\Form\Field;
  7. use Dcat\Admin\Form\Row;
  8. use Dcat\Admin\Form\Tab;
  9. use Dcat\Admin\Contracts\Repository;
  10. use Dcat\Admin\Traits\HasBuilderEvents;
  11. use Dcat\Admin\Widgets\DialogForm;
  12. use Illuminate\Contracts\Support\MessageProvider;
  13. use Illuminate\Contracts\Support\Renderable;
  14. use Illuminate\Support\Arr;
  15. use Illuminate\Support\Fluent;
  16. use Illuminate\Support\MessageBag;
  17. use Illuminate\Support\Str;
  18. use Illuminate\Support\Traits\Macroable;
  19. use Illuminate\Validation\Validator;
  20. use Symfony\Component\HttpFoundation\Response;
  21. use Dcat\Admin\Form\Concerns;
  22. /**
  23. * Class Form.
  24. *
  25. * @method Field\Text text($column, $label = '')
  26. * @method Field\Checkbox checkbox($column, $label = '')
  27. * @method Field\Radio radio($column, $label = '')
  28. * @method Field\Select select($column, $label = '')
  29. * @method Field\MultipleSelect multipleSelect($column, $label = '')
  30. * @method Field\Textarea textarea($column, $label = '')
  31. * @method Field\Hidden hidden($column, $label = '')
  32. * @method Field\Id id($column, $label = '')
  33. * @method Field\Ip ip($column, $label = '')
  34. * @method Field\Url url($column, $label = '')
  35. * @method Field\Color color($column, $label = '')
  36. * @method Field\Email email($column, $label = '')
  37. * @method Field\Mobile mobile($column, $label = '')
  38. * @method Field\Slider slider($column, $label = '')
  39. * @method Field\Map map($latitude, $longitude, $label = '')
  40. * @method Field\Editor editor($column, $label = '')
  41. * @method Field\Date date($column, $label = '')
  42. * @method Field\Datetime datetime($column, $label = '')
  43. * @method Field\Time time($column, $label = '')
  44. * @method Field\Year year($column, $label = '')
  45. * @method Field\Month month($column, $label = '')
  46. * @method Field\DateRange dateRange($start, $end, $label = '')
  47. * @method Field\DateTimeRange datetimeRange($start, $end, $label = '')
  48. * @method Field\TimeRange timeRange($start, $end, $label = '')
  49. * @method Field\Number number($column, $label = '')
  50. * @method Field\Currency currency($column, $label = '')
  51. * @method Field\SwitchField switch($column, $label = '')
  52. * @method Field\Display display($column, $label = '')
  53. * @method Field\Rate rate($column, $label = '')
  54. * @method Field\Divide divider()
  55. * @method Field\Password password($column, $label = '')
  56. * @method Field\Decimal decimal($column, $label = '')
  57. * @method Field\Html html($html, $label = '')
  58. * @method Field\Tags tags($column, $label = '')
  59. * @method Field\Icon icon($column, $label = '')
  60. * @method Field\Embeds embeds($column, $label = '')
  61. * @method Field\Captcha captcha($column, $label = '')
  62. * @method Field\Listbox listbox($column, $label = '')
  63. * @method Field\SelectResource selectResource($column, $label = '')
  64. * @method Field\File file($column, $label = '')
  65. * @method Field\Image image($column, $label = '')
  66. * @method Field\MultipleFile multipleFile($column, $label = '')
  67. * @method Field\MultipleImage multipleImage($column, $label = '')
  68. * @method Field\HasMany hasMany($column, $labelOrCallback, $callback = null)
  69. * @method Field\Tree tree($column, $label = '')
  70. * @method Field\Table table($column, $labelOrCallback, $callback = null)
  71. * @method Field\ListField list($column, $label = '')
  72. * @method Field\Timezone timezone($column, $label = '')
  73. * @method Field\KeyValue keyValue($column, $label = '')
  74. *
  75. * @method Field\BootstrapFile bootstrapFile($column, $label = '')
  76. * @method Field\BootstrapImage bootstrapImage($column, $label = '')
  77. * @method Field\BootstrapMultipleImage bootstrapMultipleImage($column, $label = '')
  78. * @method Field\BootstrapMultipleFile bootstrapMultipleFile($column, $label = '')
  79. */
  80. class Form implements Renderable
  81. {
  82. use HasBuilderEvents,
  83. Concerns\HasEvents,
  84. Concerns\HasFiles,
  85. Macroable {
  86. __call as macroCall;
  87. }
  88. /**
  89. * Remove flag in `has many` form.
  90. */
  91. const REMOVE_FLAG_NAME = '_remove_';
  92. /**
  93. * Available fields.
  94. *
  95. * @var array
  96. */
  97. protected static $availableFields = [
  98. 'button' => Field\Button::class,
  99. 'checkbox' => Field\Checkbox::class,
  100. 'color' => Field\Color::class,
  101. 'currency' => Field\Currency::class,
  102. 'date' => Field\Date::class,
  103. 'dateRange' => Field\DateRange::class,
  104. 'datetime' => Field\Datetime::class,
  105. 'datetimeRange' => Field\DatetimeRange::class,
  106. 'decimal' => Field\Decimal::class,
  107. 'display' => Field\Display::class,
  108. 'divider' => Field\Divide::class,
  109. 'embeds' => Field\Embeds::class,
  110. 'editor' => Field\Editor::class,
  111. 'email' => Field\Email::class,
  112. 'hidden' => Field\Hidden::class,
  113. 'id' => Field\Id::class,
  114. 'ip' => Field\Ip::class,
  115. 'map' => Field\Map::class,
  116. 'mobile' => Field\Mobile::class,
  117. 'month' => Field\Month::class,
  118. 'multipleSelect' => Field\MultipleSelect::class,
  119. 'number' => Field\Number::class,
  120. 'password' => Field\Password::class,
  121. 'radio' => Field\Radio::class,
  122. 'rate' => Field\Rate::class,
  123. 'select' => Field\Select::class,
  124. 'slider' => Field\Slider::class,
  125. 'switch' => Field\SwitchField::class,
  126. 'text' => Field\Text::class,
  127. 'textarea' => Field\Textarea::class,
  128. 'time' => Field\Time::class,
  129. 'timeRange' => Field\TimeRange::class,
  130. 'url' => Field\Url::class,
  131. 'year' => Field\Year::class,
  132. 'html' => Field\Html::class,
  133. 'tags' => Field\Tags::class,
  134. 'icon' => Field\Icon::class,
  135. 'captcha' => Field\Captcha::class,
  136. 'listbox' => Field\Listbox::class,
  137. 'selectResource' => Field\SelectResource::class,
  138. 'file' => Field\File::class,
  139. 'image' => Field\Image::class,
  140. 'multipleFile' => Field\MultipleFile::class,
  141. 'multipleImage' => Field\MultipleImage::class,
  142. 'hasMany' => Field\HasMany::class,
  143. 'tree' => Field\Tree::class,
  144. 'table' => Field\Table::class,
  145. 'list' => Field\ListField::class,
  146. 'timezone' => Field\Timezone::class,
  147. 'keyValue' => Field\KeyValue::class,
  148. 'bootstrapFile' => Field\BootstrapFile::class,
  149. 'bootstrapImage' => Field\BootstrapImage::class,
  150. 'bootstrapMultipleFile' => Field\BootstrapMultipleFile::class,
  151. 'bootstrapMultipleImage' => Field\BootstrapMultipleImage::class,
  152. ];
  153. /**
  154. * Collected field assets.
  155. *
  156. * @var array
  157. */
  158. protected static $collectedAssets = [];
  159. /**
  160. * Form field alias.
  161. *
  162. * @var array
  163. */
  164. public static $fieldAlias = [];
  165. /**
  166. * @var Repository
  167. */
  168. protected $repository;
  169. /**
  170. * @var Closure
  171. */
  172. protected $fieldBuilder;
  173. /**
  174. * @var bool
  175. */
  176. protected $useAjaxSubmit = true;
  177. /**
  178. * Model of the form.
  179. *
  180. * @var Fluent
  181. */
  182. protected $model;
  183. /**
  184. * @var \Illuminate\Validation\Validator
  185. */
  186. protected $validator;
  187. /**
  188. * @var Builder
  189. */
  190. protected $builder;
  191. /**
  192. * Resource path for this form page.
  193. *
  194. * @var string
  195. */
  196. protected $resource;
  197. /**
  198. * Data for save to current model from input.
  199. *
  200. * @var array
  201. */
  202. protected $updates = [];
  203. /**
  204. * Input data.
  205. *
  206. * @var array
  207. */
  208. protected $inputs = [];
  209. /**
  210. * Ignored saving fields.
  211. *
  212. * @var array
  213. */
  214. protected $ignored = [];
  215. /**
  216. * @var Form\Tab
  217. */
  218. protected $tab = null;
  219. /**
  220. * Field rows in form.
  221. *
  222. * @var array
  223. */
  224. protected $rows = [];
  225. /**
  226. * @var bool
  227. */
  228. protected $isSoftDeletes = false;
  229. /**
  230. * @var MessageBag
  231. */
  232. protected $validationMessages;
  233. /**
  234. * @var Condition[]
  235. */
  236. protected $conditions = [];
  237. /**
  238. * Create a new form instance.
  239. *
  240. * @param Repository $model
  241. * @param \Closure $callback
  242. */
  243. public function __construct(Repository $repository, ?Closure $callback = null)
  244. {
  245. $this->repository = Admin::createRepository($repository);
  246. $this->fieldBuilder = $callback;
  247. $this->builder = new Builder($this);
  248. $this->isSoftDeletes = $this->repository->isSoftDeletes();
  249. $this->setModel(new Fluent());
  250. $this->prepareDialogForm();
  251. $this->callResolving();
  252. }
  253. /**
  254. * Create a form instance.
  255. *
  256. * @param mixed ...$params
  257. * @return $this
  258. */
  259. public static function make(...$params)
  260. {
  261. return new static(...$params);
  262. }
  263. /**
  264. * @param Field $field
  265. *
  266. * @return $this
  267. */
  268. public function pushField(Field $field)
  269. {
  270. $field->setForm($this);
  271. $this->builder->fields()->push($field);
  272. $width = $this->builder->getWidth();
  273. $field->setWidth($width['field'], $width['label']);
  274. $field::collectAssets();
  275. return $this;
  276. }
  277. /**
  278. * @param $column
  279. * @return $this
  280. */
  281. public function removeField($column)
  282. {
  283. $this->builder->removeField($column);
  284. return $this;
  285. }
  286. /**
  287. * @return bool
  288. */
  289. public function isCreating()
  290. {
  291. return $this->builder->isCreating();
  292. }
  293. /**
  294. * @return bool
  295. */
  296. public function isEditing()
  297. {
  298. return $this->builder->isEditing();
  299. }
  300. /**
  301. * @return bool
  302. */
  303. public function isDeleting()
  304. {
  305. return $this->builder->isDeleting();
  306. }
  307. /**
  308. * @return Fluent
  309. */
  310. public function model()
  311. {
  312. return $this->model;
  313. }
  314. /**
  315. * @param Fluent $model
  316. */
  317. public function setModel(Fluent $model)
  318. {
  319. $this->model = $model;
  320. }
  321. /**
  322. * Get resource id.
  323. *
  324. * @return mixed
  325. */
  326. public function getKey()
  327. {
  328. return $this->builder()->getResourceId();
  329. }
  330. /**
  331. * Disable submit with ajax.
  332. *
  333. * @param bool $disable
  334. * @return $this
  335. */
  336. public function disableAjaxSubmit(bool $disable = true)
  337. {
  338. $this->useAjaxSubmit = !$disable;
  339. return $this;
  340. }
  341. /**
  342. * @return bool
  343. */
  344. public function allowAjaxSubmit()
  345. {
  346. return $this->useAjaxSubmit === true;
  347. }
  348. /**
  349. * @param \Closure $closure
  350. * @return $this;
  351. */
  352. public function wrap(\Closure $closure)
  353. {
  354. $this->builder->wrap($closure);
  355. return $this;
  356. }
  357. /**
  358. * @return Builder
  359. */
  360. public function builder()
  361. {
  362. return $this->builder;
  363. }
  364. /**
  365. * @return string
  366. */
  367. public function getFormId()
  368. {
  369. return $this->builder->getFormId();
  370. }
  371. /**
  372. * @return Repository
  373. */
  374. public function repository()
  375. {
  376. return $this->repository;
  377. }
  378. /**
  379. * Generate a edit form.
  380. *
  381. * @param $id
  382. *
  383. * @return $this
  384. */
  385. public function edit($id)
  386. {
  387. $this->builder->setMode(Builder::MODE_EDIT);
  388. $this->builder->setResourceId($id);
  389. $this->setFieldValue();
  390. return $this;
  391. }
  392. /**
  393. * Add a fieldset to form.
  394. *
  395. * @param string $title
  396. * @param Closure $setCallback
  397. *
  398. * @return Field\Fieldset
  399. */
  400. public function fieldset(string $title, Closure $setCallback)
  401. {
  402. $fieldset = new Field\Fieldset();
  403. $this->html($fieldset->start($title))->plain();
  404. $setCallback($this);
  405. $this->html($fieldset->end())->plain();
  406. return $fieldset;
  407. }
  408. /**
  409. * Use tab to split form.
  410. *
  411. * @param string $title
  412. * @param Closure $content
  413. *
  414. * @return $this
  415. */
  416. public function tab($title, Closure $content, $active = false)
  417. {
  418. $this->getTab()->append($title, $content, $active);
  419. return $this;
  420. }
  421. /**
  422. * Get Tab instance.
  423. *
  424. * @return Tab
  425. */
  426. public function getTab()
  427. {
  428. if (is_null($this->tab)) {
  429. $this->tab = new Tab($this);
  430. }
  431. return $this->tab;
  432. }
  433. /**
  434. * Destroy data entity and remove files.
  435. *
  436. * @param $id
  437. *
  438. * @return mixed
  439. */
  440. public function destroy($id)
  441. {
  442. try {
  443. $this->builder->setResourceId($id);
  444. $this->builder->setMode(Builder::MODE_DELETE);
  445. $data = $this->repository->getDataWhenDeleting($this);
  446. $this->setModel(new Fluent($data));
  447. $this->buildField();
  448. if (($response = $this->callDeleting()) instanceof Response) {
  449. return $response;
  450. }
  451. $this->repository->destroy($this, $data);
  452. if (($response = $this->callDeleted()) instanceof Response) {
  453. return $response;
  454. }
  455. $response = [
  456. 'status' => true,
  457. 'message' => trans('admin.delete_succeeded'),
  458. ];
  459. } catch (\Throwable $exception) {
  460. $response = Admin::makeExceptionHandler()->handleDestroyException($exception);
  461. $response = $response ?: [
  462. 'status' => false,
  463. 'message' => $exception->getMessage() ?: trans('admin.delete_failed'),
  464. ];
  465. }
  466. return response()->json($response);
  467. }
  468. /**
  469. * Store a new record.
  470. *
  471. * @param array|null $data
  472. * @param string|string $redirectTo
  473. * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\Http\JsonResponse
  474. */
  475. public function store(?array $data = null, $redirectTo = null)
  476. {
  477. $data = $data ?: request()->all();
  478. if (($response = $this->callSubmitted())) {
  479. return $response;
  480. }
  481. if ($response = $this->handleUploadFile($data)) {
  482. return $response;
  483. }
  484. if ($response = $this->handleFileDeleteBeforeCreate($data)) {
  485. return $response;
  486. }
  487. if ($response = $this->handleFileDeleteWhenCreating($data)) {
  488. return $response;
  489. }
  490. // Handle validation errors.
  491. if ($validationMessages = $this->validationMessages($data)) {
  492. if (!$this->isAjaxRequest()) {
  493. return back()->withInput()->withErrors($validationMessages);
  494. } else {
  495. return response()->json(['errors' => $validationMessages->getMessages()], 422);
  496. }
  497. }
  498. if (($response = $this->prepare($data))) {
  499. $this->deleteFilesWhenCreating($data);
  500. return $response;
  501. }
  502. $this->updates = $this->prepareInsert($this->updates);
  503. $id = $this->repository->store($this);
  504. $this->builder->setResourceId($id);
  505. if (($response = $this->callSaved())) {
  506. return $response;
  507. }
  508. return $this->redirect(
  509. $this->getRedirectUrl($id, $redirectTo),
  510. trans('admin.save_succeeded')
  511. );
  512. }
  513. /**
  514. * Get ajax response.
  515. *
  516. * @param $message
  517. * @param null $redirect
  518. * @param bool $status
  519. * @return bool|\Illuminate\Http\JsonResponse
  520. */
  521. public function ajaxResponse($message, $redirect = null, bool $status = true)
  522. {
  523. if ($this->isAjaxRequest()) {
  524. return response()->json([
  525. 'status' => $status,
  526. 'message' => $message,
  527. 'redirect' => $redirect,
  528. ]);
  529. }
  530. return false;
  531. }
  532. /**
  533. * ajax but not pjax
  534. *
  535. * @return bool
  536. */
  537. public function isAjaxRequest()
  538. {
  539. $request = request();
  540. return $request->ajax() && !$request->pjax();
  541. }
  542. /**
  543. * Prepare input data for insert or update.
  544. *
  545. * @param array $data
  546. *
  547. * @return Response|null
  548. */
  549. protected function prepare($data = [])
  550. {
  551. $this->inputs = array_merge($this->removeIgnoredFields($data), $this->inputs);
  552. if (($response = $this->callSaving()) instanceof Response) {
  553. return $response;
  554. }
  555. $this->updates = $this->inputs;
  556. }
  557. /**
  558. * Remove ignored fields from input.
  559. *
  560. * @param array $input
  561. *
  562. * @return array
  563. */
  564. protected function removeIgnoredFields($input)
  565. {
  566. Arr::forget($input, $this->ignored);
  567. return $input;
  568. }
  569. /**
  570. * Get data for insert or update.
  571. *
  572. * @return array
  573. */
  574. public function getUpdates(): array
  575. {
  576. return $this->updates;
  577. }
  578. /**
  579. * Set data for insert or update.
  580. *
  581. * @param array $updates
  582. * @return $this
  583. */
  584. public function setUpdates(array $updates)
  585. {
  586. $this->updates = array_merge($this->updates, $updates);
  587. return $this;
  588. }
  589. /**
  590. * Handle orderable update.
  591. *
  592. * @param int $id
  593. * @param array $input
  594. *
  595. * @return bool
  596. */
  597. protected function handleOrderable(array $input = [])
  598. {
  599. if (array_key_exists('_orderable', $input)) {
  600. $input['_orderable'] == 1 ? $this->repository->moveOrderUp() : $this->repository->moveOrderDown();
  601. return $this->ajaxResponse(__('admin.update_succeeded'));
  602. }
  603. }
  604. /**
  605. * Handle update.
  606. *
  607. * @param $id
  608. * @param array|null $data
  609. * @param string|null $redirectTo
  610. * @return $this|bool|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|mixed|null
  611. */
  612. public function update(
  613. $id,
  614. ?array $data = null,
  615. $redirectTo = null
  616. )
  617. {
  618. $data = $data ?: request()->all();
  619. $this->builder->setResourceId($id);
  620. $this->builder->setMode(Builder::MODE_EDIT);
  621. $this->buildField();
  622. if (($response = $this->callSubmitted())) {
  623. return $response;
  624. }
  625. if ($uploadFileResponse = $this->handleUploadFile($data)) {
  626. return $uploadFileResponse;
  627. }
  628. $isEditable = $this->isEditable($data);
  629. $data = $this->handleEditable($data);
  630. $data = $this->handleFileDelete($data);
  631. $this->setModel(new Fluent($this->repository->getDataWhenUpdating($this)));
  632. $this->setFieldOriginalValue();
  633. if ($response = $this->handleOrderable($data)) {
  634. return $response;
  635. }
  636. // Handle validation errors.
  637. if ($validationMessages = $this->validationMessages($data)) {
  638. if (!$isEditable && !$this->isAjaxRequest()) {
  639. return back()->withInput()->withErrors($validationMessages);
  640. } else {
  641. return response()->json([
  642. 'errors' => $isEditable ? Arr::dot($validationMessages->getMessages()) : $validationMessages->getMessages()
  643. ], 422);
  644. }
  645. }
  646. if (($response = $this->prepare($data))) {
  647. return $response;
  648. }
  649. $this->updates = $this->prepareUpdate($this->updates);
  650. $this->repository->update($this);
  651. if (($result = $this->callSaved())) {
  652. return $result;
  653. }
  654. return $this->redirect(
  655. $this->getRedirectUrl($id, $redirectTo),
  656. trans('admin.update_succeeded')
  657. );
  658. }
  659. /**
  660. * Get redirect response.
  661. *
  662. * @param string $url
  663. * @param array|string $options
  664. * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
  665. */
  666. public function redirect(?string $url, $options = null)
  667. {
  668. if (is_string($options)) {
  669. $message = $options;
  670. $options = [];
  671. } else {
  672. $message = $options['message'] ?? trans('admin.save_succeeded');
  673. }
  674. $status = (bool) ($options['status'] ?? true);
  675. // 判断是否是ajax请求
  676. if ($response = $this->ajaxResponse($message, $url, $status)) {
  677. return $response;
  678. }
  679. // 非ajax请求
  680. $status = (int) ($options['status_code'] ?? 302);
  681. admin_alert($message);
  682. return redirect($url, $status);
  683. }
  684. /**
  685. * @param $key
  686. * @param $redirectTo
  687. * @return string|false
  688. */
  689. public function getRedirectUrl($key, $redirectTo = null)
  690. {
  691. if ($redirectTo) return $redirectTo;
  692. $resourcesPath = $this->builder->isCreating() ?
  693. $this->getResource(0) : $this->getResource(-1);
  694. if (request('after-save') == 1) {
  695. // continue editing
  696. if ($this->builder->isEditing() && $this->isAjaxRequest()) {
  697. return false;
  698. }
  699. return rtrim($resourcesPath, '/')."/{$key}/edit";
  700. }
  701. if (request('after-save') == 2) {
  702. // continue creating
  703. return rtrim($resourcesPath, '/').'/create';
  704. }
  705. if (request('after-save') == 3) {
  706. // view resource
  707. return rtrim($resourcesPath, '/')."/{$key}";
  708. }
  709. return request(Builder::PREVIOUS_URL_KEY) ?: $resourcesPath;
  710. }
  711. /**
  712. * Check if request is from editable.
  713. *
  714. * @param array $input
  715. *
  716. * @return bool
  717. */
  718. protected function isEditable(array $input = [])
  719. {
  720. return array_key_exists('_editable', $input);
  721. }
  722. /**
  723. * Handle editable update.
  724. *
  725. * @param array $input
  726. *
  727. * @return array
  728. */
  729. protected function handleEditable(array $input = [])
  730. {
  731. if (array_key_exists('_editable', $input)) {
  732. $name = $input['name'];
  733. $value = $input['value'];
  734. Arr::forget($input, ['pk', 'value', 'name']);
  735. Arr::set($input, $name, $value);
  736. }
  737. return $input;
  738. }
  739. /**
  740. * Prepare input data for update.
  741. *
  742. * @param array $updates
  743. * @param bool $oneToOneRelation If column is one-to-one relation.
  744. *
  745. * @return array
  746. */
  747. public function prepareUpdate(array $updates, $oneToOneRelation = false)
  748. {
  749. $prepared = [];
  750. /** @var Field $field */
  751. foreach ($this->builder->fields() as $field) {
  752. $columns = $field->column();
  753. // If column not in input array data, then continue.
  754. if (!Arr::has($updates, $columns)) {
  755. continue;
  756. }
  757. if ($this->invalidColumn($columns, $oneToOneRelation)) {
  758. continue;
  759. }
  760. $value = $this->getDataByColumn($updates, $columns);
  761. $value = $field->prepareInputValue($value);
  762. if (is_array($columns)) {
  763. foreach ($columns as $name => $column) {
  764. Arr::set($prepared, $column, $value[$name]);
  765. }
  766. } elseif (is_string($columns)) {
  767. Arr::set($prepared, $columns, $value);
  768. }
  769. }
  770. return $prepared;
  771. }
  772. /**
  773. * @param string|array $columns
  774. * @param bool $oneToOneRelation
  775. *
  776. * @return bool
  777. */
  778. protected function invalidColumn($columns, $oneToOneRelation = false)
  779. {
  780. foreach ((array) $columns as $column) {
  781. if ((!$oneToOneRelation && Str::contains($column, '.')) ||
  782. ($oneToOneRelation && !Str::contains($column, '.'))) {
  783. return true;
  784. }
  785. }
  786. return false;
  787. }
  788. /**
  789. * Prepare input data for insert.
  790. *
  791. * @param $inserts
  792. *
  793. * @return array
  794. */
  795. public function prepareInsert($inserts)
  796. {
  797. $this->prepareHasOneRelation($inserts);
  798. foreach ($inserts as $column => $value) {
  799. if (is_null($field = $this->getFieldByColumn($column))) {
  800. unset($inserts[$column]);
  801. continue;
  802. }
  803. $inserts[$column] = $field->prepareInputValue($value);
  804. }
  805. $prepared = [];
  806. foreach ($inserts as $key => $value) {
  807. Arr::set($prepared, $key, $value);
  808. }
  809. return $prepared;
  810. }
  811. /**
  812. * Is input data is has-one relation.
  813. *
  814. * @param array $inserts
  815. *
  816. */
  817. function prepareHasOneRelation(array &$inserts)
  818. {
  819. $relations = [];
  820. $this->builder->fields()->each(function ($field) use (&$relations) {
  821. $column = $field->column();
  822. if (is_array($column)) {
  823. foreach ($column as $v) {
  824. if (Str::contains($v, '.')) {
  825. $first = explode('.', $v)[0];
  826. $relations[$first] = null;
  827. }
  828. }
  829. return;
  830. }
  831. if (Str::contains($column, '.')) {
  832. $first = explode('.', $column)[0];
  833. $relations[$first] = null;
  834. }
  835. });
  836. foreach ($relations as $first => $v) {
  837. if (isset($inserts[$first])) {
  838. $inserts = array_merge($inserts, Arr::dot([$first => $inserts[$first]]));
  839. }
  840. }
  841. }
  842. /**
  843. * Ignore fields to save.
  844. *
  845. * @param string|array $fields
  846. *
  847. * @return $this
  848. */
  849. public function ignore($fields)
  850. {
  851. $this->ignored = array_merge($this->ignored, (array) $fields);
  852. return $this;
  853. }
  854. /**
  855. * Get primary key name of model.
  856. *
  857. * @return string
  858. */
  859. public function getKeyName()
  860. {
  861. return $this->repository->getKeyName();
  862. }
  863. /**
  864. * @return Repository
  865. */
  866. public function getRepository(): Repository
  867. {
  868. return $this->repository;
  869. }
  870. /**
  871. * @param array $data
  872. * @param string|array $columns
  873. *
  874. * @return array|mixed
  875. */
  876. protected function getDataByColumn($data, $columns)
  877. {
  878. if (is_string($columns)) {
  879. return Arr::get($data, $columns);
  880. }
  881. if (is_array($columns)) {
  882. $value = [];
  883. foreach ($columns as $name => $column) {
  884. if (!Arr::has($data, $column)) {
  885. continue;
  886. }
  887. $value[$name] = Arr::get($data, $column);
  888. }
  889. return $value;
  890. }
  891. }
  892. /**
  893. * Find field object by column.
  894. *
  895. * @param $column
  896. *
  897. * @return mixed
  898. */
  899. protected function getFieldByColumn($column)
  900. {
  901. return $this->builder->fields()->first(
  902. function (Field $field) use ($column) {
  903. if (is_array($field->column())) {
  904. return in_array($column, $field->column());
  905. }
  906. return $field->column() == $column;
  907. }
  908. );
  909. }
  910. /**
  911. * Set original data for each field.
  912. *
  913. * @return void
  914. */
  915. protected function setFieldOriginalValue()
  916. {
  917. $values = $this->model->toArray();
  918. $this->builder->fields()->each(function (Field $field) use ($values) {
  919. $field->setOriginal($values);
  920. });
  921. }
  922. /**
  923. * Set all fields value in form.
  924. *
  925. * @return void
  926. */
  927. protected function setFieldValue()
  928. {
  929. $this->callEditing();
  930. $data = $this->model->toArray();
  931. $this->builder->fields()->each(function (Field $field) use ($data) {
  932. if (!in_array($field->column(), $this->ignored)) {
  933. $field->fill($data);
  934. }
  935. });
  936. }
  937. /**
  938. * @example
  939. * $form->if(true)->next(function (Form $form) {
  940. * $form->text('name');
  941. * });
  942. *
  943. * $form->if(function (Form $form) {
  944. * return $form->model()->id > 5;
  945. * })->next(function (Form $form) {
  946. * $form->text('name');
  947. * });
  948. *
  949. * $form->if(true)->then(function (Form $form) {
  950. * $form->text('name');
  951. * });
  952. *
  953. * $form->if(true)->creating(function (Form $form) {});
  954. *
  955. * $form->if(true)->removeField('name');
  956. *
  957. * @param bool|\Closure $condition
  958. *
  959. * @return Condition|$this
  960. */
  961. public function if($condition)
  962. {
  963. return $this->conditions[] = new Condition($condition, $this);
  964. }
  965. /**
  966. * @return void
  967. */
  968. protected function rendering()
  969. {
  970. if ($isEditing = $this->isEditing()) {
  971. $this->setModel(new Fluent($this->repository->edit($this)));
  972. }
  973. $this->buildField();
  974. if ($isEditing) {
  975. $this->setFieldValue();
  976. } else {
  977. $this->callCreating();
  978. }
  979. }
  980. /**
  981. * @return void
  982. */
  983. protected function buildField()
  984. {
  985. if ($callback = $this->fieldBuilder) {
  986. $callback($this);
  987. }
  988. foreach ($this->conditions as $condition) {
  989. $condition->then();
  990. }
  991. }
  992. /**
  993. * Get validation messages.
  994. *
  995. * @param array $input
  996. *
  997. * @return MessageBag|bool
  998. */
  999. public function validationMessages($input)
  1000. {
  1001. $failedValidators = [];
  1002. /** @var Field $field */
  1003. foreach ($this->builder->fields() as $field) {
  1004. if (!$validator = $field->getValidator($input)) {
  1005. continue;
  1006. }
  1007. if (($validator instanceof Validator) && !$validator->passes()) {
  1008. $failedValidators[] = $validator;
  1009. }
  1010. }
  1011. $message = $this->mergeValidationMessages($failedValidators);
  1012. if ($message->any() && $this->builder->isCreating()) {
  1013. $this->deleteFilesWhenCreating($input);
  1014. }
  1015. return $message->any() ? $message : false;
  1016. }
  1017. /**
  1018. * @param string|array|MessageProvider $column
  1019. * @param string|array $messages
  1020. *
  1021. * @return $this
  1022. */
  1023. public function responseValidationMessages($column, $messages = null)
  1024. {
  1025. if ($column instanceof MessageProvider) {
  1026. return $this->responseValidationMessages($column->getMessageBag()->getMessages());
  1027. }
  1028. if (!$this->validationMessages) {
  1029. $this->validationMessages = new MessageBag;
  1030. }
  1031. if (!$column) {
  1032. return $this;
  1033. }
  1034. if (is_array($column)) {
  1035. foreach ($column as $k => &$v) {
  1036. $v = (array)$v;
  1037. }
  1038. $this->validationMessages->merge($column);
  1039. } elseif ($messages) {
  1040. $this->validationMessages->merge([$column => (array)$messages]);
  1041. }
  1042. return $this;
  1043. }
  1044. /**
  1045. * Merge validation messages from input validators.
  1046. *
  1047. * @param \Illuminate\Validation\Validator[] $validators
  1048. *
  1049. * @return MessageBag
  1050. */
  1051. protected function mergeValidationMessages($validators)
  1052. {
  1053. $messageBag = new MessageBag();
  1054. foreach ($validators as $validator) {
  1055. $messageBag = $messageBag->merge($validator->messages());
  1056. }
  1057. if ($this->validationMessages) {
  1058. return $messageBag->merge($this->validationMessages);
  1059. }
  1060. return $messageBag;
  1061. }
  1062. /**
  1063. * Set action for form.
  1064. *
  1065. * @param string $action
  1066. *
  1067. * @return $this
  1068. */
  1069. public function setAction($action)
  1070. {
  1071. $this->builder->setAction($action);
  1072. return $this;
  1073. }
  1074. /**
  1075. * @return string
  1076. */
  1077. public function getAction()
  1078. {
  1079. return $this->builder->getAction();
  1080. }
  1081. /**
  1082. * Set field and label width in current form.
  1083. *
  1084. * @param int $fieldWidth
  1085. * @param int $labelWidth
  1086. *
  1087. * @return $this
  1088. */
  1089. public function setWidth($fieldWidth = 8, $labelWidth = 2)
  1090. {
  1091. $this->builder->fields()->each(function ($field) use ($fieldWidth, $labelWidth) {
  1092. /* @var Field $field */
  1093. $field->setWidth($fieldWidth, $labelWidth);
  1094. });
  1095. $this->builder->setWidth($fieldWidth, $labelWidth);
  1096. return $this;
  1097. }
  1098. /**
  1099. * Set view for form.
  1100. *
  1101. * @param string $view
  1102. *
  1103. * @return $this
  1104. */
  1105. public function setView($view)
  1106. {
  1107. $this->builder->setView($view);
  1108. return $this;
  1109. }
  1110. /**
  1111. * Set title for form.
  1112. *
  1113. * @param string $title
  1114. *
  1115. * @return $this
  1116. */
  1117. public function setTitle($title = '')
  1118. {
  1119. $this->builder->setTitle($title);
  1120. return $this;
  1121. }
  1122. /**
  1123. * Add a row in form.
  1124. *
  1125. * @param Closure $callback
  1126. *
  1127. * @return $this
  1128. */
  1129. public function row(Closure $callback)
  1130. {
  1131. $this->rows[] = new Row($callback, $this);
  1132. return $this;
  1133. }
  1134. /**
  1135. * Tools setting for form.
  1136. *
  1137. * @param Closure $callback
  1138. */
  1139. public function tools(Closure $callback)
  1140. {
  1141. $callback->call($this, $this->builder->getTools());
  1142. }
  1143. /**
  1144. * @param bool $disable
  1145. * @return $this
  1146. */
  1147. public function disableHeader(bool $disable = true)
  1148. {
  1149. $this->builder->disableHeader($disable);
  1150. return $this;
  1151. }
  1152. /**
  1153. * @param bool $disable
  1154. * @return $this
  1155. */
  1156. public function disableFooter(bool $disable = true)
  1157. {
  1158. $this->builder->disableFooter($disable);
  1159. return $this;
  1160. }
  1161. /**
  1162. * Disable form submit.
  1163. *
  1164. * @return $this
  1165. */
  1166. public function disableSubmitButton(bool $disable = true)
  1167. {
  1168. $this->builder->getFooter()->disableSubmit($disable);
  1169. return $this;
  1170. }
  1171. /**
  1172. * Disable form reset.
  1173. *
  1174. * @return $this
  1175. */
  1176. public function disableResetButton(bool $disable = true)
  1177. {
  1178. $this->builder->getFooter()->disableReset($disable);
  1179. return $this;
  1180. }
  1181. /**
  1182. * Disable View Checkbox on footer.
  1183. *
  1184. * @return $this
  1185. */
  1186. public function disableViewCheck(bool $disable = true)
  1187. {
  1188. $this->builder->getFooter()->disableViewCheck($disable);
  1189. return $this;
  1190. }
  1191. /**
  1192. * Disable Editing Checkbox on footer.
  1193. *
  1194. * @return $this
  1195. */
  1196. public function disableEditingCheck(bool $disable = true)
  1197. {
  1198. $this->builder->getFooter()->disableEditingCheck($disable);
  1199. return $this;
  1200. }
  1201. /**
  1202. * Disable Creating Checkbox on footer.
  1203. *
  1204. * @return $this
  1205. */
  1206. public function disableCreatingCheck(bool $disable = true)
  1207. {
  1208. $this->builder->getFooter()->disableCreatingCheck($disable);
  1209. return $this;
  1210. }
  1211. /**
  1212. * Disable `view` tool.
  1213. *
  1214. * @return $this
  1215. */
  1216. public function disableViewButton(bool $disable = true)
  1217. {
  1218. $this->builder->getTools()->disableView($disable);
  1219. return $this;
  1220. }
  1221. /**
  1222. * Disable `list` tool.
  1223. *
  1224. * @return $this
  1225. */
  1226. public function disableListButton(bool $disable = true)
  1227. {
  1228. $this->builder->getTools()->disableList($disable);
  1229. return $this;
  1230. }
  1231. /**
  1232. * Disable `delete` tool.
  1233. *
  1234. * @return $this
  1235. */
  1236. public function disableDeleteButton(bool $disable = true)
  1237. {
  1238. $this->builder->getTools()->disableDelete($disable);
  1239. return $this;
  1240. }
  1241. /**
  1242. * Footer setting for form.
  1243. *
  1244. * @param Closure $callback
  1245. */
  1246. public function footer(Closure $callback)
  1247. {
  1248. call_user_func($callback, $this->builder->getFooter());
  1249. }
  1250. /**
  1251. * Get current resource route url.
  1252. *
  1253. * @param int $slice
  1254. *
  1255. * @return string
  1256. */
  1257. public function getResource($slice = -2)
  1258. {
  1259. $path = $this->resource ?: app('request')->getUri();
  1260. $segments = explode('/', trim($path, '/'));
  1261. if ($slice != 0) {
  1262. $segments = array_slice($segments, 0, $slice);
  1263. }
  1264. return \url(implode('/', $segments));
  1265. }
  1266. /**
  1267. * Set resource path.
  1268. *
  1269. * @param string $resource
  1270. * @return $this
  1271. */
  1272. public function resource(string $resource)
  1273. {
  1274. if ($resource) {
  1275. $this->resource = admin_url($resource);
  1276. }
  1277. return $this;
  1278. }
  1279. /**
  1280. * Render the form contents.
  1281. *
  1282. * @return string
  1283. */
  1284. public function render()
  1285. {
  1286. try {
  1287. $this->rendering();
  1288. $this->callComposing();
  1289. return $this->builder->render();
  1290. } catch (\Throwable $e) {
  1291. return Admin::makeExceptionHandler()->renderException($e);
  1292. }
  1293. }
  1294. /**
  1295. * Get or set input data.
  1296. *
  1297. * @param string $key
  1298. * @param null $value
  1299. *
  1300. * @return array|mixed
  1301. */
  1302. public function input($key, $value = null)
  1303. {
  1304. if (is_null($value)) {
  1305. return Arr::get($this->inputs, $key);
  1306. }
  1307. return Arr::set($this->inputs, $key, $value);
  1308. }
  1309. /**
  1310. * @param string|array $keys
  1311. *
  1312. * @return void
  1313. */
  1314. public function deleteInput($keys)
  1315. {
  1316. Arr::forget($this->inputs, $keys);
  1317. }
  1318. /**
  1319. * @param int $width
  1320. * @param Closure $callback
  1321. */
  1322. public function block(int $width, \Closure $callback)
  1323. {
  1324. $layout = $this->builder->layout();
  1325. $layout->column($width, $callback($layout->form()));
  1326. }
  1327. /**
  1328. * @param int $width
  1329. * @return $this
  1330. */
  1331. public function setDefaultBlockWidth(int $width)
  1332. {
  1333. $this->builder->setDefaultBlockWidth($width);
  1334. return $this;
  1335. }
  1336. /**
  1337. * @return $this
  1338. */
  1339. protected function prepareDialogForm()
  1340. {
  1341. DialogForm::prepare($this);
  1342. return $this;
  1343. }
  1344. /**
  1345. * @return bool
  1346. */
  1347. public static function inDialog()
  1348. {
  1349. return DialogForm::is();
  1350. }
  1351. /**
  1352. * Create a dialog form.
  1353. *
  1354. * @param string|null $title
  1355. * @return DialogForm
  1356. */
  1357. public static function popup(?string $title = null)
  1358. {
  1359. return new DialogForm($title);
  1360. }
  1361. /**
  1362. * Register custom field.
  1363. *
  1364. * @param string $abstract
  1365. * @param string $class
  1366. *
  1367. * @return void
  1368. */
  1369. public static function extend($abstract, $class)
  1370. {
  1371. static::$availableFields[$abstract] = $class;
  1372. }
  1373. /**
  1374. * @return array
  1375. */
  1376. public static function getExtensions()
  1377. {
  1378. return static::$availableFields;
  1379. }
  1380. /**
  1381. * Set form field alias.
  1382. *
  1383. * @param string $field
  1384. * @param string $alias
  1385. *
  1386. * @return void
  1387. */
  1388. public static function alias($field, $alias)
  1389. {
  1390. static::$fieldAlias[$alias] = $field;
  1391. }
  1392. /**
  1393. * Find field class.
  1394. *
  1395. * @param string $method
  1396. *
  1397. * @return bool|mixed
  1398. */
  1399. public static function findFieldClass($method)
  1400. {
  1401. // If alias exists.
  1402. if (isset(static::$fieldAlias[$method])) {
  1403. $method = static::$fieldAlias[$method];
  1404. }
  1405. $class = Arr::get(static::$availableFields, $method);
  1406. if (class_exists($class)) {
  1407. return $class;
  1408. }
  1409. return false;
  1410. }
  1411. /**
  1412. * Getter.
  1413. *
  1414. * @param string $name
  1415. *
  1416. * @return array|mixed
  1417. */
  1418. public function __get($name)
  1419. {
  1420. return $this->input($name);
  1421. }
  1422. /**
  1423. * Setter.
  1424. *
  1425. * @param string $name
  1426. * @param $value
  1427. */
  1428. public function __set($name, $value)
  1429. {
  1430. return Arr::set($this->inputs, $name, $value);
  1431. }
  1432. /**
  1433. * Generate a Field object and add to form builder if Field exists.
  1434. *
  1435. * @param string $method
  1436. * @param array $arguments
  1437. *
  1438. * @return Field
  1439. */
  1440. public function __call($method, $arguments)
  1441. {
  1442. if (static::hasMacro($method)) {
  1443. return $this->macroCall($method, $arguments);
  1444. }
  1445. if ($className = static::findFieldClass($method)) {
  1446. $column = Arr::get($arguments, 0, '');
  1447. $element = new $className($column, array_slice($arguments, 1));
  1448. $this->pushField($element);
  1449. return $element;
  1450. }
  1451. admin_error('Error', "Field type [$method] does not exist.");
  1452. return new Field\Nullable();
  1453. }
  1454. }