Form.php 36 KB

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