Form.php 41 KB

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