Form.php 41 KB

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