Form.php 41 KB

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