Form.php 41 KB

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