Form.php 36 KB

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