Form.php 40 KB

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