Form.php 41 KB

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