Form.php 42 KB

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