Form.php 42 KB

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