Form.php 42 KB

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