Form.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  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. $fields = $this->builder->fields();
  296. if ($steps = $this->builder->stepBuilder()) {
  297. $fields = $fields->merge($steps->fields());
  298. }
  299. return $fields;
  300. }
  301. /**
  302. * @param $column
  303. *
  304. * @return $this
  305. */
  306. public function removeField($column)
  307. {
  308. $this->builder->removeField($column);
  309. return $this;
  310. }
  311. /**
  312. * @return bool
  313. */
  314. public function isCreating()
  315. {
  316. return $this->builder->isCreating();
  317. }
  318. /**
  319. * @return bool
  320. */
  321. public function isEditing()
  322. {
  323. return $this->builder->isEditing();
  324. }
  325. /**
  326. * @return bool
  327. */
  328. public function isDeleting()
  329. {
  330. return $this->builder->isDeleting();
  331. }
  332. /**
  333. * @param Fluent $model
  334. *
  335. * @return Fluent|void
  336. */
  337. public function model(Fluent $model = null)
  338. {
  339. if ($model === null) {
  340. return $this->model;
  341. }
  342. $this->model = $model;
  343. }
  344. /**
  345. * Get resource id.
  346. *
  347. * @return mixed
  348. */
  349. public function getKey()
  350. {
  351. return $this->builder()->getResourceId();
  352. }
  353. /**
  354. * Disable submit with ajax.
  355. *
  356. * @param bool $disable
  357. *
  358. * @return $this
  359. */
  360. public function disableAjaxSubmit(bool $disable = true)
  361. {
  362. $this->useAjaxSubmit = ! $disable;
  363. return $this;
  364. }
  365. /**
  366. * @return bool
  367. */
  368. public function allowAjaxSubmit()
  369. {
  370. return $this->useAjaxSubmit === true;
  371. }
  372. /**
  373. * @param \Closure $closure
  374. *
  375. * @return $this;
  376. */
  377. public function wrap(\Closure $closure)
  378. {
  379. $this->builder->wrap($closure);
  380. return $this;
  381. }
  382. /**
  383. * @return Builder
  384. */
  385. public function builder()
  386. {
  387. return $this->builder;
  388. }
  389. /**
  390. * @return string
  391. */
  392. public function getElementId()
  393. {
  394. return $this->builder->getElementId();
  395. }
  396. /**
  397. * @return Repository
  398. */
  399. public function repository()
  400. {
  401. return $this->repository;
  402. }
  403. /**
  404. * Generate a edit form.
  405. *
  406. * @param $id
  407. *
  408. * @return $this
  409. */
  410. public function edit($id)
  411. {
  412. $this->builder->mode(Builder::MODE_EDIT);
  413. $this->builder->setResourceId($id);
  414. $this->model(new Fluent($this->repository->edit($this)));
  415. return $this;
  416. }
  417. /**
  418. * Add a fieldset to form.
  419. *
  420. * @param string $title
  421. * @param Closure $setCallback
  422. *
  423. * @return Field\Fieldset
  424. */
  425. public function fieldset(string $title, Closure $setCallback)
  426. {
  427. $fieldset = new Field\Fieldset();
  428. $this->html($fieldset->start($title))->plain();
  429. $setCallback($this);
  430. $this->html($fieldset->end())->plain();
  431. return $fieldset;
  432. }
  433. /**
  434. * Destroy data entity and remove files.
  435. *
  436. * @param $id
  437. *
  438. * @return mixed
  439. */
  440. public function destroy($id)
  441. {
  442. try {
  443. $this->builder->setResourceId($id);
  444. $this->builder->mode(Builder::MODE_DELETE);
  445. $data = $this->repository->getDataWhenDeleting($this);
  446. $this->model(new Fluent($data));
  447. $this->setFieldOriginalValue();
  448. $this->build();
  449. if (($response = $this->callDeleting()) instanceof Response) {
  450. return $response;
  451. }
  452. $result = $this->repository->destroy($this, $data);
  453. if (($response = $this->callDeleted($result)) instanceof Response) {
  454. return $response;
  455. }
  456. $response = [
  457. 'status' => $result ? true : false,
  458. 'message' => $result ? trans('admin.delete_succeeded') : trans('admin.delete_failed'),
  459. ];
  460. } catch (\Throwable $exception) {
  461. $response = Admin::makeExceptionHandler()->handle($exception);
  462. if ($response instanceof Response) {
  463. return $response;
  464. }
  465. $response = $response ?: [
  466. 'status' => false,
  467. 'message' => $exception->getMessage() ?: trans('admin.delete_failed'),
  468. ];
  469. }
  470. return response()->json($response);
  471. }
  472. /**
  473. * Store a new record.
  474. *
  475. * @param array|null $data
  476. * @param string|string $redirectTo
  477. *
  478. * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\Http\JsonResponse|Response
  479. */
  480. public function store(?array $data = null, $redirectTo = null)
  481. {
  482. if ($data) {
  483. $this->request->replace($data);
  484. }
  485. $data = $data ?: $this->request->all();
  486. if ($response = $this->beforeStore($data)) {
  487. return $response;
  488. }
  489. $this->updates = $this->prepareInsert($this->updates);
  490. $id = $this->repository->store($this);
  491. $this->builder->setResourceId($id);
  492. if (($response = $this->callSaved($id))) {
  493. return $response;
  494. }
  495. if ($response = $this->responseMultipleStepsDonePage()) {
  496. return $response;
  497. }
  498. if (! $id) {
  499. return $this->error(trans('admin.save_failed'));
  500. }
  501. return $this->redirect(
  502. $this->redirectUrl($id, $redirectTo),
  503. trans('admin.save_succeeded')
  504. );
  505. }
  506. /**
  507. * Before store.
  508. *
  509. * @param array $data
  510. *
  511. * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|Response|void
  512. */
  513. protected function beforeStore(array $data)
  514. {
  515. $this->inputs = $data;
  516. $this->build();
  517. $this->prepareStepFormFields($this->inputs);
  518. if (($response = $this->callSubmitted())) {
  519. return $response;
  520. }
  521. // Validate step form.
  522. if ($this->isStepFormValidationRequest()) {
  523. return $this->validateStepForm($this->inputs);
  524. }
  525. if ($response = $this->handleUploadFile($this->inputs)) {
  526. return $response;
  527. }
  528. if ($response = $this->handleFileDeleteBeforeCreate($this->inputs)) {
  529. $this->deleteFileInStepFormStashData($this->inputs);
  530. return $response;
  531. }
  532. if ($response = $this->handleFileDeleteWhenCreating($this->inputs)) {
  533. $this->deleteFileInStepFormStashData($this->inputs);
  534. return $response;
  535. }
  536. // Handle validation errors.
  537. if ($validationMessages = $this->validationMessages($this->inputs)) {
  538. return $this->validationErrorsResponse($validationMessages);
  539. }
  540. if (($response = $this->prepare($this->inputs))) {
  541. $this->deleteFilesWhenCreating($this->inputs);
  542. return $response;
  543. }
  544. }
  545. /**
  546. * Prepare input data for insert or update.
  547. *
  548. * @param array $data
  549. *
  550. * @return Response|null
  551. */
  552. protected function prepare($data = [])
  553. {
  554. $this->inputs = $this->removeIgnoredFields($data);
  555. if (($response = $this->callSaving()) instanceof Response) {
  556. return $response;
  557. }
  558. $this->updates = $this->inputs;
  559. }
  560. /**
  561. * Remove ignored fields from input.
  562. *
  563. * @param array $input
  564. *
  565. * @return array
  566. */
  567. public function removeIgnoredFields($input)
  568. {
  569. Arr::forget($input, $this->ignored);
  570. $ignored = $this->fields()->map(function (Field $field) {
  571. if ($field instanceof Field\Display || $field->getAttribute('readonly') || $field->getAttribute('disabled')) {
  572. return $field->column();
  573. }
  574. })->filter()->toArray();
  575. if ($ignored) {
  576. Arr::forget($input, $ignored);
  577. }
  578. return $input;
  579. }
  580. /**
  581. * Get or set data for insert or update.
  582. *
  583. * @param array $updates
  584. *
  585. * @return $this|array
  586. */
  587. public function updates(array $updates = null)
  588. {
  589. if ($updates === null) {
  590. return $this->updates;
  591. }
  592. $this->updates = array_merge($this->updates, $updates);
  593. return $this;
  594. }
  595. /**
  596. * Handle orderable update.
  597. *
  598. * @param int $id
  599. * @param array $input
  600. *
  601. * @return Response
  602. */
  603. protected function handleOrderable(array $input = [])
  604. {
  605. if (array_key_exists('_orderable', $input)) {
  606. $updated = $input['_orderable'] == 1
  607. ? $this->repository->moveOrderUp()
  608. : $this->repository->moveOrderDown();
  609. return $updated
  610. ? $this->ajaxResponse(__('admin.update_succeeded'))
  611. : $this->error(__('admin.nothing_updated'));
  612. }
  613. }
  614. /**
  615. * Handle update.
  616. *
  617. * @param $id
  618. * @param array|null $data
  619. * @param string|null $redirectTo
  620. *
  621. * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse||Response
  622. */
  623. public function update(
  624. $id,
  625. ?array $data = null,
  626. $redirectTo = null
  627. ) {
  628. if ($data) {
  629. $this->request->replace($data);
  630. }
  631. $data = $data ?: $this->request->all();
  632. if ($response = $this->beforeUpdate($id, $data)) {
  633. return $response;
  634. }
  635. $this->updates = $this->prepareUpdate($this->updates);
  636. $updated = $this->repository->update($this);
  637. if (($response = $this->callSaved($updated))) {
  638. return $response;
  639. }
  640. if (! $updated) {
  641. return $this->error(trans('admin.update_succeeded'));
  642. }
  643. return $this->redirect(
  644. $this->redirectUrl($id, $redirectTo),
  645. trans('admin.update_succeeded')
  646. );
  647. }
  648. /**
  649. * Before update.
  650. *
  651. * @param array $data
  652. *
  653. * @return Response|void
  654. */
  655. protected function beforeUpdate($id, array &$data)
  656. {
  657. $this->builder->setResourceId($id);
  658. $this->builder->mode(Builder::MODE_EDIT);
  659. $this->inputs = $data;
  660. $this->model(new Fluent($this->repository->getDataWhenUpdating($this)));
  661. $this->build();
  662. $this->setFieldOriginalValue();
  663. if ($response = $this->callSubmitted()) {
  664. return $response;
  665. }
  666. if ($uploadFileResponse = $this->handleUploadFile($this->inputs)) {
  667. return $uploadFileResponse;
  668. }
  669. $isEditable = $this->isEditable($this->inputs);
  670. $this->inputs = $this->handleEditable($this->inputs);
  671. $this->inputs = $this->handleFileDelete($this->inputs);
  672. $this->inputs = $this->handleHasManyValues($this->inputs);
  673. if ($response = $this->handleOrderable($this->inputs)) {
  674. return $response;
  675. }
  676. // Handle validation errors.
  677. if ($validationMessages = $this->validationMessages($this->inputs)) {
  678. return $this->validationErrorsResponse(
  679. $isEditable ? Arr::dot($validationMessages->toArray()) : $validationMessages
  680. );
  681. }
  682. if ($response = $this->prepare($this->inputs)) {
  683. return $response;
  684. }
  685. }
  686. /**
  687. * @param array $inputs
  688. *
  689. * @return array
  690. */
  691. protected function handleHasManyValues(array $inputs)
  692. {
  693. foreach ($inputs as $column => &$input) {
  694. $field = $this->builder()->field($column);
  695. if (is_array($input) && $field instanceof Field\HasMany) {
  696. $keyName = $field->getKeyName();
  697. foreach ($input as $k => &$v) {
  698. if (! array_key_exists($keyName, $v)) {
  699. $v[$keyName] = $k;
  700. }
  701. if (empty($v[NestedForm::REMOVE_FLAG_NAME])) {
  702. $v[NestedForm::REMOVE_FLAG_NAME] = null;
  703. }
  704. }
  705. }
  706. }
  707. return $inputs;
  708. }
  709. /**
  710. * @param $key
  711. * @param $redirectTo
  712. *
  713. * @return string|null
  714. */
  715. public function redirectUrl($key, $redirectTo = null)
  716. {
  717. if ($redirectTo) {
  718. return $redirectTo;
  719. }
  720. $resourcesPath = $this->builder->isCreating() ?
  721. $this->getResource(0) : $this->getResource(-1);
  722. if ($this->request->get('after-save') == 1) {
  723. // continue editing
  724. if ($this->builder->isEditing() && $this->isAjaxRequest()) {
  725. return;
  726. }
  727. return rtrim($resourcesPath, '/')."/{$key}/edit";
  728. }
  729. if ($this->request->get('after-save') == 2) {
  730. // continue creating
  731. return rtrim($resourcesPath, '/').'/create';
  732. }
  733. if ($this->request->get('after-save') == 3) {
  734. // view resource
  735. return rtrim($resourcesPath, '/')."/{$key}";
  736. }
  737. return $this->request->get(Builder::PREVIOUS_URL_KEY) ?: $resourcesPath;
  738. }
  739. /**
  740. * Check if request is from editable.
  741. *
  742. * @param array $input
  743. *
  744. * @return bool
  745. */
  746. protected function isEditable(array $input = [])
  747. {
  748. return array_key_exists('_editable', $input);
  749. }
  750. /**
  751. * Handle editable update.
  752. *
  753. * @param array $input
  754. *
  755. * @return array
  756. */
  757. protected function handleEditable(array $input = [])
  758. {
  759. if (array_key_exists('_editable', $input)) {
  760. $name = $input['name'];
  761. $value = $input['value'];
  762. Arr::forget($input, ['pk', 'value', 'name']);
  763. Arr::set($input, $name, $value);
  764. }
  765. return $input;
  766. }
  767. /**
  768. * Prepare input data for update.
  769. *
  770. * @param array $updates
  771. *
  772. * @return array
  773. */
  774. public function prepareUpdate(array $updates)
  775. {
  776. $prepared = [];
  777. /** @var Field $field */
  778. foreach ($this->builder->fields() as $field) {
  779. $columns = $field->column();
  780. // If column not in input array data, then continue.
  781. if (! Arr::has($updates, $columns)) {
  782. continue;
  783. }
  784. $value = $this->getDataByColumn($updates, $columns);
  785. $value = $field->prepare($value);
  786. if (is_array($columns)) {
  787. foreach ($columns as $name => $column) {
  788. Arr::set($prepared, $column, $value[$name]);
  789. }
  790. } elseif (is_string($columns)) {
  791. Arr::set($prepared, $columns, $value);
  792. }
  793. }
  794. return $prepared;
  795. }
  796. /**
  797. * Prepare input data for insert.
  798. *
  799. * @param $inserts
  800. *
  801. * @return array
  802. */
  803. public function prepareInsert($inserts)
  804. {
  805. $this->prepareHasOneRelation($inserts);
  806. foreach ($inserts as $column => $value) {
  807. if (is_null($field = $this->getFieldByColumn($column))) {
  808. unset($inserts[$column]);
  809. continue;
  810. }
  811. $inserts[$column] = $field->prepare($value);
  812. }
  813. $prepared = [];
  814. foreach ($inserts as $key => $value) {
  815. Arr::set($prepared, $key, $value);
  816. }
  817. return $prepared;
  818. }
  819. /**
  820. * Is input data is has-one relation.
  821. *
  822. * @param array $inserts
  823. */
  824. public function prepareHasOneRelation(array &$inserts)
  825. {
  826. $relations = [];
  827. $this->builder->fields()->each(function ($field) use (&$relations) {
  828. $column = $field->column();
  829. if (is_array($column)) {
  830. foreach ($column as $v) {
  831. if (Str::contains($v, '.')) {
  832. $first = explode('.', $v)[0];
  833. $relations[$first] = null;
  834. }
  835. }
  836. return;
  837. }
  838. if (Str::contains($column, '.')) {
  839. $first = explode('.', $column)[0];
  840. $relations[$first] = null;
  841. }
  842. });
  843. foreach ($relations as $first => $v) {
  844. if (isset($inserts[$first])) {
  845. $inserts = array_merge($inserts, Arr::dot([$first => $inserts[$first]]));
  846. }
  847. }
  848. }
  849. /**
  850. * Ignore fields to save.
  851. *
  852. * @param string|array $fields
  853. *
  854. * @return $this
  855. */
  856. public function ignore($fields)
  857. {
  858. $this->ignored = array_merge($this->ignored, (array) $fields);
  859. return $this;
  860. }
  861. /**
  862. * Get primary key name of model.
  863. *
  864. * @return string
  865. */
  866. public function keyName()
  867. {
  868. if (! $this->repository) {
  869. return 'id';
  870. }
  871. return $this->repository->getKeyName();
  872. }
  873. /**
  874. * @return string|void
  875. */
  876. public function createdAtColumn()
  877. {
  878. if (! $this->repository) {
  879. return;
  880. }
  881. return $this->repository->getCreatedAtColumn();
  882. }
  883. /**
  884. * @return string|void
  885. */
  886. public function updatedAtColumn()
  887. {
  888. if (! $this->repository) {
  889. return;
  890. }
  891. return $this->repository->getUpdatedAtColumn();
  892. }
  893. /**
  894. * @param array $data
  895. * @param string|array $columns
  896. *
  897. * @return array|mixed
  898. */
  899. protected function getDataByColumn($data, $columns)
  900. {
  901. if (is_string($columns)) {
  902. return Arr::get($data, $columns);
  903. }
  904. if (is_array($columns)) {
  905. $value = [];
  906. foreach ($columns as $name => $column) {
  907. if (! Arr::has($data, $column)) {
  908. continue;
  909. }
  910. $value[$name] = Arr::get($data, $column);
  911. }
  912. return $value;
  913. }
  914. }
  915. /**
  916. * Find field object by column.
  917. *
  918. * @param $column
  919. *
  920. * @return mixed
  921. */
  922. protected function getFieldByColumn($column)
  923. {
  924. return $this->builder->fields()->first(
  925. function (Field $field) use ($column) {
  926. if (is_array($field->column())) {
  927. return in_array($column, $field->column());
  928. }
  929. return $field->column() == $column;
  930. }
  931. );
  932. }
  933. /**
  934. * Set original data for each field.
  935. *
  936. * @return void
  937. */
  938. protected function setFieldOriginalValue()
  939. {
  940. $data = $this->model()->toArray();
  941. $this->builder->fields()->each(function (Field $field) use ($data) {
  942. $field->setOriginal($data);
  943. });
  944. }
  945. /**
  946. * @example
  947. * $form->if(true)->then(function (Form $form) {
  948. * $form->text('name');
  949. * });
  950. *
  951. * $form->if(function (Form $form) {
  952. * return $form->model()->id > 5;
  953. * })->then(function (Form $form) {
  954. * $form->text('name');
  955. * });
  956. *
  957. * $form->if(true)->now(function (Form $form) {
  958. * $form->text('name');
  959. * });
  960. *
  961. * $form->if(true)->creating(function (Form $form) {});
  962. *
  963. * $form->if(true)->removeField('name');
  964. *
  965. * @param bool|\Closure $condition
  966. *
  967. * @return Condition
  968. */
  969. public function if($condition)
  970. {
  971. return $this->conditions[] = new Condition($condition, $this);
  972. }
  973. /**
  974. * @return void
  975. */
  976. protected function rendering()
  977. {
  978. $this->build();
  979. if ($this->isCreating()) {
  980. $this->callCreating();
  981. return;
  982. }
  983. $this->fillFields($this->model()->toArray());
  984. $this->callEditing();
  985. }
  986. /**
  987. * @param array $data
  988. *
  989. * @return void
  990. */
  991. public function fillFields(array $data)
  992. {
  993. $this->builder->fields()->each(function (Field $field) use ($data) {
  994. if (! in_array($field->column(), $this->ignored, true)) {
  995. $field->fill($data);
  996. }
  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[] = [$field, $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 array $validators
  1067. *
  1068. * @return MessageBag
  1069. */
  1070. protected function mergeValidationMessages($validators)
  1071. {
  1072. $messageBag = new MessageBag();
  1073. foreach ($validators as $value) {
  1074. [$field, $validator] = $value;
  1075. $messageBag = $messageBag->merge($field->formatValidatorMessages($validator->messages()));
  1076. }
  1077. if ($this->validationMessages) {
  1078. return $messageBag->merge($this->validationMessages);
  1079. }
  1080. return $messageBag;
  1081. }
  1082. /**
  1083. * Get or set action for form.
  1084. *
  1085. * @param string|null $action
  1086. *
  1087. * @return $this|string
  1088. */
  1089. public function action($action = null)
  1090. {
  1091. $value = $this->builder->action($action);
  1092. if ($action === null) {
  1093. return $value;
  1094. }
  1095. return $this;
  1096. }
  1097. /**
  1098. * Set field and label width in current form.
  1099. *
  1100. * @param int $fieldWidth
  1101. * @param int $labelWidth
  1102. *
  1103. * @return $this
  1104. */
  1105. public function width($fieldWidth = 8, $labelWidth = 2)
  1106. {
  1107. $this->builder->fields()->each(function ($field) use ($fieldWidth, $labelWidth) {
  1108. /* @var Field $field */
  1109. $field->width($fieldWidth, $labelWidth);
  1110. });
  1111. $this->builder->width($fieldWidth, $labelWidth);
  1112. return $this;
  1113. }
  1114. /**
  1115. * Set view for form.
  1116. *
  1117. * @param string $view
  1118. *
  1119. * @return $this
  1120. */
  1121. public function view($view)
  1122. {
  1123. $this->builder->view($view);
  1124. return $this;
  1125. }
  1126. /**
  1127. * Get or set title for form.
  1128. *
  1129. * @param string $title
  1130. *
  1131. * @return $this
  1132. */
  1133. public function title($title = null)
  1134. {
  1135. $this->builder->title($title);
  1136. return $this;
  1137. }
  1138. /**
  1139. * Tools setting for form.
  1140. *
  1141. * @param Closure|string|AbstractTool|Renderable|Action|array $callback
  1142. *
  1143. * @return $this;
  1144. */
  1145. public function tools($callback)
  1146. {
  1147. if ($callback instanceof Closure) {
  1148. $callback->call($this, $this->builder->tools());
  1149. return $this;
  1150. }
  1151. if (! is_array($callback)) {
  1152. $callback = [$callback];
  1153. }
  1154. foreach ($callback as $tool) {
  1155. $this->builder->tools()->append($tool);
  1156. }
  1157. return $this;
  1158. }
  1159. /**
  1160. * @param bool $disable
  1161. *
  1162. * @return $this
  1163. */
  1164. public function disableHeader(bool $disable = true)
  1165. {
  1166. $this->builder->disableHeader($disable);
  1167. return $this;
  1168. }
  1169. /**
  1170. * @param bool $disable
  1171. *
  1172. * @return $this
  1173. */
  1174. public function disableFooter(bool $disable = true)
  1175. {
  1176. $this->builder->disableFooter($disable);
  1177. return $this;
  1178. }
  1179. /**
  1180. * Disable form submit.
  1181. *
  1182. * @return $this
  1183. */
  1184. public function disableSubmitButton(bool $disable = true)
  1185. {
  1186. $this->builder->footer()->disableSubmit($disable);
  1187. return $this;
  1188. }
  1189. /**
  1190. * Disable form reset.
  1191. *
  1192. * @return $this
  1193. */
  1194. public function disableResetButton(bool $disable = true)
  1195. {
  1196. $this->builder->footer()->disableReset($disable);
  1197. return $this;
  1198. }
  1199. /**
  1200. * Disable View Checkbox on footer.
  1201. *
  1202. * @return $this
  1203. */
  1204. public function disableViewCheck(bool $disable = true)
  1205. {
  1206. $this->builder->footer()->disableViewCheck($disable);
  1207. return $this;
  1208. }
  1209. /**
  1210. * Disable Editing Checkbox on footer.
  1211. *
  1212. * @return $this
  1213. */
  1214. public function disableEditingCheck(bool $disable = true)
  1215. {
  1216. $this->builder->footer()->disableEditingCheck($disable);
  1217. return $this;
  1218. }
  1219. /**
  1220. * Disable Creating Checkbox on footer.
  1221. *
  1222. * @return $this
  1223. */
  1224. public function disableCreatingCheck(bool $disable = true)
  1225. {
  1226. $this->builder->footer()->disableCreatingCheck($disable);
  1227. return $this;
  1228. }
  1229. /**
  1230. * Disable `view` tool.
  1231. *
  1232. * @return $this
  1233. */
  1234. public function disableViewButton(bool $disable = true)
  1235. {
  1236. $this->builder->tools()->disableView($disable);
  1237. return $this;
  1238. }
  1239. /**
  1240. * Disable `list` tool.
  1241. *
  1242. * @return $this
  1243. */
  1244. public function disableListButton(bool $disable = true)
  1245. {
  1246. $this->builder->tools()->disableList($disable);
  1247. return $this;
  1248. }
  1249. /**
  1250. * Disable `delete` tool.
  1251. *
  1252. * @return $this
  1253. */
  1254. public function disableDeleteButton(bool $disable = true)
  1255. {
  1256. $this->builder->tools()->disableDelete($disable);
  1257. return $this;
  1258. }
  1259. /**
  1260. * Footer setting for form.
  1261. *
  1262. * @param Closure $callback
  1263. *
  1264. * @return $this
  1265. */
  1266. public function footer(Closure $callback)
  1267. {
  1268. call_user_func($callback, $this->builder->footer());
  1269. return $this;
  1270. }
  1271. /**
  1272. * Get current resource route url.
  1273. *
  1274. * @param int $slice
  1275. *
  1276. * @return string
  1277. */
  1278. public function getResource($slice = -2)
  1279. {
  1280. $path = $this->resource ?: $this->request->getUri();
  1281. $segments = explode('/', trim($path, '/'));
  1282. if ($slice != 0) {
  1283. $segments = array_slice($segments, 0, $slice);
  1284. }
  1285. return url(implode('/', $segments));
  1286. }
  1287. /**
  1288. * Set resource path.
  1289. *
  1290. * @param string $resource
  1291. *
  1292. * @return $this
  1293. */
  1294. public function resource(string $resource)
  1295. {
  1296. if ($resource) {
  1297. $this->resource = admin_url($resource);
  1298. }
  1299. return $this;
  1300. }
  1301. /**
  1302. * Render the form contents.
  1303. *
  1304. * @return string
  1305. */
  1306. public function render()
  1307. {
  1308. try {
  1309. $this->rendering();
  1310. $this->callComposing();
  1311. return $this->builder->render();
  1312. } catch (\Throwable $e) {
  1313. return Admin::makeExceptionHandler()->handle($e);
  1314. }
  1315. }
  1316. /**
  1317. * Get or set input data.
  1318. *
  1319. * @param string $key
  1320. * @param null $value
  1321. *
  1322. * @return array|mixed
  1323. */
  1324. public function input($key, $value = null)
  1325. {
  1326. if (is_null($value)) {
  1327. return Arr::get($this->inputs, $key);
  1328. }
  1329. return Arr::set($this->inputs, $key, $value);
  1330. }
  1331. /**
  1332. * @param string|array $keys
  1333. *
  1334. * @return void
  1335. */
  1336. public function deleteInput($keys)
  1337. {
  1338. Arr::forget($this->inputs, $keys);
  1339. }
  1340. /**
  1341. * @param int $width
  1342. * @param Closure $callback
  1343. *
  1344. * @return $this
  1345. */
  1346. public function block(int $width, \Closure $callback)
  1347. {
  1348. $layout = $this->builder->layout();
  1349. $callback($form = $layout->form());
  1350. $layout->column($width, $form);
  1351. return $this;
  1352. }
  1353. /**
  1354. * @param int $width
  1355. *
  1356. * @return $this
  1357. */
  1358. public function setDefaultBlockWidth(int $width)
  1359. {
  1360. $this->builder->setDefaultBlockWidth($width);
  1361. return $this;
  1362. }
  1363. /**
  1364. * @return $this
  1365. */
  1366. protected function prepareDialogForm()
  1367. {
  1368. DialogForm::prepare($this);
  1369. return $this;
  1370. }
  1371. /**
  1372. * @param Closure $callback
  1373. *
  1374. * @return bool|void
  1375. */
  1376. public function inDialog(\Closure $callback = null)
  1377. {
  1378. if (! $callback) {
  1379. return DialogForm::is();
  1380. }
  1381. if (DialogForm::is()) {
  1382. $callback($this);
  1383. }
  1384. }
  1385. /**
  1386. * Create a dialog form.
  1387. *
  1388. * @param string|null $title
  1389. *
  1390. * @return DialogForm
  1391. */
  1392. public static function dialog(?string $title = null)
  1393. {
  1394. return new DialogForm($title);
  1395. }
  1396. /**
  1397. * Register custom field.
  1398. *
  1399. * @param string $abstract
  1400. * @param string $class
  1401. *
  1402. * @return void
  1403. */
  1404. public static function extend($abstract, $class)
  1405. {
  1406. static::$availableFields[$abstract] = $class;
  1407. }
  1408. /**
  1409. * @return array
  1410. */
  1411. public static function extensions()
  1412. {
  1413. return static::$availableFields;
  1414. }
  1415. /**
  1416. * Set form field alias.
  1417. *
  1418. * @param string $field
  1419. * @param string $alias
  1420. *
  1421. * @return void
  1422. */
  1423. public static function alias($field, $alias)
  1424. {
  1425. static::$fieldAlias[$alias] = $field;
  1426. }
  1427. /**
  1428. * Find field class.
  1429. *
  1430. * @param string $method
  1431. *
  1432. * @return bool|mixed
  1433. */
  1434. public static function findFieldClass($method)
  1435. {
  1436. // If alias exists.
  1437. if (isset(static::$fieldAlias[$method])) {
  1438. $method = static::$fieldAlias[$method];
  1439. }
  1440. $class = Arr::get(static::$availableFields, $method);
  1441. if (class_exists($class)) {
  1442. return $class;
  1443. }
  1444. return false;
  1445. }
  1446. /**
  1447. * Getter.
  1448. *
  1449. * @param string $name
  1450. *
  1451. * @return array|mixed
  1452. */
  1453. public function __get($name)
  1454. {
  1455. return $this->input($name);
  1456. }
  1457. /**
  1458. * Setter.
  1459. *
  1460. * @param string $name
  1461. * @param mixed $value
  1462. */
  1463. public function __set($name, $value)
  1464. {
  1465. return Arr::set($this->inputs, $name, $value);
  1466. }
  1467. /**
  1468. * Generate a Field object and add to form builder if Field exists.
  1469. *
  1470. * @param string $method
  1471. * @param array $arguments
  1472. *
  1473. * @return Field
  1474. */
  1475. public function __call($method, $arguments)
  1476. {
  1477. if (static::hasMacro($method)) {
  1478. return $this->macroCall($method, $arguments);
  1479. }
  1480. if ($className = static::findFieldClass($method)) {
  1481. $column = Arr::get($arguments, 0, '');
  1482. $element = new $className($column, array_slice($arguments, 1));
  1483. $this->pushField($element);
  1484. return $element;
  1485. }
  1486. admin_error('Error', "Field type [$method] does not exist.");
  1487. return new Field\Nullable();
  1488. }
  1489. }