Form.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  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\Color color($column, $label = '')
  42. * @method Field\Email email($column, $label = '')
  43. * @method Field\Mobile mobile($column, $label = '')
  44. * @method Field\Slider slider($column, $label = '')
  45. * @method Field\Map map($latitude, $longitude, $label = '')
  46. * @method Field\Editor editor($column, $label = '')
  47. * @method Field\Date date($column, $label = '')
  48. * @method Field\Datetime datetime($column, $label = '')
  49. * @method Field\Time time($column, $label = '')
  50. * @method Field\Year year($column, $label = '')
  51. * @method Field\Month month($column, $label = '')
  52. * @method Field\DateRange dateRange($start, $end, $label = '')
  53. * @method Field\DateTimeRange datetimeRange($start, $end, $label = '')
  54. * @method Field\TimeRange timeRange($start, $end, $label = '')
  55. * @method Field\Number number($column, $label = '')
  56. * @method Field\Currency currency($column, $label = '')
  57. * @method Field\SwitchField switch($column, $label = '')
  58. * @method Field\Display display($column, $label = '')
  59. * @method Field\Rate rate($column, $label = '')
  60. * @method Field\Divide divider()
  61. * @method Field\Password password($column, $label = '')
  62. * @method Field\Decimal decimal($column, $label = '')
  63. * @method Field\Html html($html, $label = '')
  64. * @method Field\Tags tags($column, $label = '')
  65. * @method Field\Icon icon($column, $label = '')
  66. * @method Field\Embeds embeds($column, $label = '')
  67. * @method Field\Captcha captcha()
  68. * @method Field\Listbox listbox($column, $label = '')
  69. * @method Field\SelectResource selectResource($column, $label = '')
  70. * @method Field\File file($column, $label = '')
  71. * @method Field\Image image($column, $label = '')
  72. * @method Field\MultipleFile multipleFile($column, $label = '')
  73. * @method Field\MultipleImage multipleImage($column, $label = '')
  74. * @method Field\HasMany hasMany($column, $labelOrCallback, $callback = null)
  75. * @method Field\Tree tree($column, $label = '')
  76. * @method Field\Table table($column, $labelOrCallback, $callback = null)
  77. * @method Field\ListField list($column, $label = '')
  78. * @method Field\Timezone timezone($column, $label = '')
  79. * @method Field\KeyValue keyValue($column, $label = '')
  80. * @method Field\Tel tel($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. 'color' => Field\Color::class,
  105. 'currency' => Field\Currency::class,
  106. 'date' => Field\Date::class,
  107. 'dateRange' => Field\DateRange::class,
  108. 'datetime' => Field\Datetime::class,
  109. 'datetimeRange' => Field\DatetimeRange::class,
  110. 'decimal' => Field\Decimal::class,
  111. 'display' => Field\Display::class,
  112. 'divider' => Field\Divide::class,
  113. 'embeds' => Field\Embeds::class,
  114. 'editor' => Field\Editor::class,
  115. 'email' => Field\Email::class,
  116. 'hidden' => Field\Hidden::class,
  117. 'id' => Field\Id::class,
  118. 'ip' => Field\Ip::class,
  119. 'map' => Field\Map::class,
  120. 'mobile' => Field\Mobile::class,
  121. 'month' => Field\Month::class,
  122. 'multipleSelect' => Field\MultipleSelect::class,
  123. 'number' => Field\Number::class,
  124. 'password' => Field\Password::class,
  125. 'radio' => Field\Radio::class,
  126. 'rate' => Field\Rate::class,
  127. 'select' => Field\Select::class,
  128. 'slider' => Field\Slider::class,
  129. 'switch' => Field\SwitchField::class,
  130. 'text' => Field\Text::class,
  131. 'textarea' => Field\Textarea::class,
  132. 'time' => Field\Time::class,
  133. 'timeRange' => Field\TimeRange::class,
  134. 'url' => Field\Url::class,
  135. 'year' => Field\Year::class,
  136. 'html' => Field\Html::class,
  137. 'tags' => Field\Tags::class,
  138. 'icon' => Field\Icon::class,
  139. 'captcha' => Field\Captcha::class,
  140. 'listbox' => Field\Listbox::class,
  141. 'selectResource' => Field\SelectResource::class,
  142. 'file' => Field\File::class,
  143. 'image' => Field\Image::class,
  144. 'multipleFile' => Field\MultipleFile::class,
  145. 'multipleImage' => Field\MultipleImage::class,
  146. 'hasMany' => Field\HasMany::class,
  147. 'tree' => Field\Tree::class,
  148. 'table' => Field\Table::class,
  149. 'list' => Field\ListField::class,
  150. 'timezone' => Field\Timezone::class,
  151. 'keyValue' => Field\KeyValue::class,
  152. 'tel' => Field\Tel::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->build();
  468. if (($response = $this->callDeleting()) instanceof Response) {
  469. return $response;
  470. }
  471. $this->repository->destroy($this, $data);
  472. if (($response = $this->callDeleted()) instanceof Response) {
  473. return $response;
  474. }
  475. $response = [
  476. 'status' => true,
  477. 'message' => trans('admin.delete_succeeded'),
  478. ];
  479. } catch (\Throwable $exception) {
  480. $response = Admin::makeExceptionHandler()->handleDestroyException($exception);
  481. $response = $response ?: [
  482. 'status' => false,
  483. 'message' => $exception->getMessage() ?: trans('admin.delete_failed'),
  484. ];
  485. }
  486. return response()->json($response);
  487. }
  488. /**
  489. * Store a new record.
  490. *
  491. * @param array|null $data
  492. * @param string|string $redirectTo
  493. *
  494. * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\Http\JsonResponse|Response
  495. */
  496. public function store(?array $data = null, $redirectTo = null)
  497. {
  498. $data = $data ?: $this->request->all();
  499. if ($response = $this->beforeStore($data)) {
  500. return $response;
  501. }
  502. $this->updates = $this->prepareInsert($this->updates);
  503. $id = $this->repository->store($this);
  504. $this->builder->setResourceId($id);
  505. if (($response = $this->callSaved())) {
  506. return $response;
  507. }
  508. if ($response = $this->responseMultipleStepsDonePage()) {
  509. return $response;
  510. }
  511. return $this->redirect(
  512. $this->redirectUrl($id, $redirectTo),
  513. trans('admin.save_succeeded')
  514. );
  515. }
  516. /**
  517. * Before store.
  518. *
  519. * @param array $data
  520. *
  521. * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|Response|void
  522. */
  523. protected function beforeStore(array $data)
  524. {
  525. $this->build();
  526. $this->prepareStepFormFields($data);
  527. if (($response = $this->callSubmitted())) {
  528. return $response;
  529. }
  530. // Validate step form.
  531. if ($this->isStepFormValidationRequest()) {
  532. return $this->validateStepForm($data);
  533. }
  534. if ($response = $this->handleUploadFile($data)) {
  535. return $response;
  536. }
  537. if ($response = $this->handleFileDeleteBeforeCreate($data)) {
  538. $this->deleteFileInStepFormStashData($data);
  539. return $response;
  540. }
  541. if ($response = $this->handleFileDeleteWhenCreating($data)) {
  542. $this->deleteFileInStepFormStashData($data);
  543. return $response;
  544. }
  545. // Handle validation errors.
  546. if ($validationMessages = $this->validationMessages($data)) {
  547. return $this->validationErrorsResponse($validationMessages);
  548. }
  549. if (($response = $this->prepare($data))) {
  550. $this->deleteFilesWhenCreating($data);
  551. return $response;
  552. }
  553. }
  554. /**
  555. * Prepare input data for insert or update.
  556. *
  557. * @param array $data
  558. *
  559. * @return Response|null
  560. */
  561. protected function prepare($data = [])
  562. {
  563. $this->inputs = array_merge($this->removeIgnoredFields($data), $this->inputs);
  564. if (($response = $this->callSaving()) instanceof Response) {
  565. return $response;
  566. }
  567. $this->updates = $this->inputs;
  568. }
  569. /**
  570. * Remove ignored fields from input.
  571. *
  572. * @param array $input
  573. *
  574. * @return array
  575. */
  576. protected function removeIgnoredFields($input)
  577. {
  578. Arr::forget($input, $this->ignored);
  579. return $input;
  580. }
  581. /**
  582. * Get or Set data for insert or update.
  583. *
  584. * @param array $updates
  585. *
  586. * @return $this|array
  587. */
  588. public function updates(array $updates = null)
  589. {
  590. if ($updates === null) {
  591. return $this->updates;
  592. }
  593. $this->updates = array_merge($this->updates, $updates);
  594. return $this;
  595. }
  596. /**
  597. * Handle orderable update.
  598. *
  599. * @param int $id
  600. * @param array $input
  601. *
  602. * @return Response
  603. */
  604. protected function handleOrderable(array $input = [])
  605. {
  606. if (array_key_exists('_orderable', $input)) {
  607. $updated = $input['_orderable'] == 1
  608. ? $this->repository->moveOrderUp()
  609. : $this->repository->moveOrderDown();
  610. return $updated
  611. ? $this->ajaxResponse(__('admin.update_succeeded'))
  612. : $this->error(__('admin.nothing_updated'));
  613. }
  614. }
  615. /**
  616. * Handle update.
  617. *
  618. * @param $id
  619. * @param array|null $data
  620. * @param string|null $redirectTo
  621. *
  622. * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse||Response
  623. */
  624. public function update(
  625. $id,
  626. ?array $data = null,
  627. $redirectTo = null
  628. ) {
  629. $data = $data ?: $this->request->all();
  630. if ($response = $this->beforeUpdate($id, $data)) {
  631. return $response;
  632. }
  633. $this->updates = $this->prepareUpdate($this->updates);
  634. $this->repository->update($this);
  635. if (($result = $this->callSaved())) {
  636. return $result;
  637. }
  638. return $this->redirect(
  639. $this->redirectUrl($id, $redirectTo),
  640. trans('admin.update_succeeded')
  641. );
  642. }
  643. /**
  644. * Before update.
  645. *
  646. * @param array $data
  647. *
  648. * @return Response|void
  649. */
  650. protected function beforeUpdate($id, array &$data)
  651. {
  652. $this->builder->setResourceId($id);
  653. $this->builder->mode(Builder::MODE_EDIT);
  654. $this->model(new Fluent($this->repository->getDataWhenUpdating($this)));
  655. $this->setFieldOriginalValue();
  656. $this->build();
  657. if ($response = $this->callSubmitted()) {
  658. return $response;
  659. }
  660. if ($uploadFileResponse = $this->handleUploadFile($data)) {
  661. return $uploadFileResponse;
  662. }
  663. $isEditable = $this->isEditable($data);
  664. $data = $this->handleEditable($data);
  665. $data = $this->handleFileDelete($data);
  666. if ($response = $this->handleOrderable($data)) {
  667. return $response;
  668. }
  669. // Handle validation errors.
  670. if ($validationMessages = $this->validationMessages($data)) {
  671. return $this->validationErrorsResponse(
  672. $isEditable ? Arr::dot($validationMessages->toArray()) : $validationMessages
  673. );
  674. }
  675. if ($response = $this->prepare($data)) {
  676. return $response;
  677. }
  678. }
  679. /**
  680. * @param $key
  681. * @param $redirectTo
  682. *
  683. * @return string|false
  684. */
  685. public function redirectUrl($key, $redirectTo = null)
  686. {
  687. if ($redirectTo) {
  688. return $redirectTo;
  689. }
  690. $resourcesPath = $this->builder->isCreating() ?
  691. $this->getResource(0) : $this->getResource(-1);
  692. if ($this->request->get('after-save') == 1) {
  693. // continue editing
  694. if ($this->builder->isEditing() && $this->isAjaxRequest()) {
  695. return false;
  696. }
  697. return rtrim($resourcesPath, '/')."/{$key}/edit";
  698. }
  699. if ($this->request->get('after-save') == 2) {
  700. // continue creating
  701. return rtrim($resourcesPath, '/').'/create';
  702. }
  703. if ($this->request->get('after-save') == 3) {
  704. // view resource
  705. return rtrim($resourcesPath, '/')."/{$key}";
  706. }
  707. return $this->request->get(Builder::PREVIOUS_URL_KEY) ?: $resourcesPath;
  708. }
  709. /**
  710. * Check if request is from editable.
  711. *
  712. * @param array $input
  713. *
  714. * @return bool
  715. */
  716. protected function isEditable(array $input = [])
  717. {
  718. return array_key_exists('_editable', $input);
  719. }
  720. /**
  721. * Handle editable update.
  722. *
  723. * @param array $input
  724. *
  725. * @return array
  726. */
  727. protected function handleEditable(array $input = [])
  728. {
  729. if (array_key_exists('_editable', $input)) {
  730. $name = $input['name'];
  731. $value = $input['value'];
  732. Arr::forget($input, ['pk', 'value', 'name']);
  733. Arr::set($input, $name, $value);
  734. }
  735. return $input;
  736. }
  737. /**
  738. * Prepare input data for update.
  739. *
  740. * @param array $updates
  741. * @param bool $oneToOneRelation If column is one-to-one relation.
  742. *
  743. * @return array
  744. */
  745. public function prepareUpdate(array $updates, $oneToOneRelation = false)
  746. {
  747. $prepared = [];
  748. /** @var Field $field */
  749. foreach ($this->builder->fields() as $field) {
  750. $columns = $field->column();
  751. // If column not in input array data, then continue.
  752. if (! Arr::has($updates, $columns)) {
  753. continue;
  754. }
  755. if ($this->invalidColumn($columns, $oneToOneRelation)) {
  756. continue;
  757. }
  758. $value = $this->getDataByColumn($updates, $columns);
  759. $value = $field->prepare($value);
  760. if (is_array($columns)) {
  761. foreach ($columns as $name => $column) {
  762. Arr::set($prepared, $column, $value[$name]);
  763. }
  764. } elseif (is_string($columns)) {
  765. Arr::set($prepared, $columns, $value);
  766. }
  767. }
  768. return $prepared;
  769. }
  770. /**
  771. * @param string|array $columns
  772. * @param bool $oneToOneRelation
  773. *
  774. * @return bool
  775. */
  776. protected function invalidColumn($columns, $oneToOneRelation = false)
  777. {
  778. foreach ((array) $columns as $column) {
  779. if ((! $oneToOneRelation && Str::contains($column, '.')) ||
  780. ($oneToOneRelation && ! Str::contains($column, '.'))) {
  781. return true;
  782. }
  783. }
  784. return false;
  785. }
  786. /**
  787. * Prepare input data for insert.
  788. *
  789. * @param $inserts
  790. *
  791. * @return array
  792. */
  793. public function prepareInsert($inserts)
  794. {
  795. $this->prepareHasOneRelation($inserts);
  796. foreach ($inserts as $column => $value) {
  797. if (is_null($field = $this->getFieldByColumn($column))) {
  798. unset($inserts[$column]);
  799. continue;
  800. }
  801. $inserts[$column] = $field->prepare($value);
  802. }
  803. $prepared = [];
  804. foreach ($inserts as $key => $value) {
  805. Arr::set($prepared, $key, $value);
  806. }
  807. return $prepared;
  808. }
  809. /**
  810. * Is input data is has-one relation.
  811. *
  812. * @param array $inserts
  813. */
  814. public function prepareHasOneRelation(array &$inserts)
  815. {
  816. $relations = [];
  817. $this->builder->fields()->each(function ($field) use (&$relations) {
  818. $column = $field->column();
  819. if (is_array($column)) {
  820. foreach ($column as $v) {
  821. if (Str::contains($v, '.')) {
  822. $first = explode('.', $v)[0];
  823. $relations[$first] = null;
  824. }
  825. }
  826. return;
  827. }
  828. if (Str::contains($column, '.')) {
  829. $first = explode('.', $column)[0];
  830. $relations[$first] = null;
  831. }
  832. });
  833. foreach ($relations as $first => $v) {
  834. if (isset($inserts[$first])) {
  835. $inserts = array_merge($inserts, Arr::dot([$first => $inserts[$first]]));
  836. }
  837. }
  838. }
  839. /**
  840. * Ignore fields to save.
  841. *
  842. * @param string|array $fields
  843. *
  844. * @return $this
  845. */
  846. public function ignore($fields)
  847. {
  848. $this->ignored = array_merge($this->ignored, (array) $fields);
  849. return $this;
  850. }
  851. /**
  852. * Get primary key name of model.
  853. *
  854. * @return string
  855. */
  856. public function keyName()
  857. {
  858. if (! $this->repository) {
  859. return 'id';
  860. }
  861. return $this->repository->getKeyName();
  862. }
  863. /**
  864. * @return string|void
  865. */
  866. public function createdAtColumn()
  867. {
  868. if (! $this->repository) {
  869. return;
  870. }
  871. return $this->repository->getCreatedAtColumn();
  872. }
  873. /**
  874. * @return string|void
  875. */
  876. public function updatedAtColumn()
  877. {
  878. if (! $this->repository) {
  879. return;
  880. }
  881. return $this->repository->getUpdatedAtColumn();
  882. }
  883. /**
  884. * @param array $data
  885. * @param string|array $columns
  886. *
  887. * @return array|mixed
  888. */
  889. protected function getDataByColumn($data, $columns)
  890. {
  891. if (is_string($columns)) {
  892. return Arr::get($data, $columns);
  893. }
  894. if (is_array($columns)) {
  895. $value = [];
  896. foreach ($columns as $name => $column) {
  897. if (! Arr::has($data, $column)) {
  898. continue;
  899. }
  900. $value[$name] = Arr::get($data, $column);
  901. }
  902. return $value;
  903. }
  904. }
  905. /**
  906. * Find field object by column.
  907. *
  908. * @param $column
  909. *
  910. * @return mixed
  911. */
  912. protected function getFieldByColumn($column)
  913. {
  914. return $this->builder->fields()->first(
  915. function (Field $field) use ($column) {
  916. if (is_array($field->column())) {
  917. return in_array($column, $field->column());
  918. }
  919. return $field->column() == $column;
  920. }
  921. );
  922. }
  923. /**
  924. * Set original data for each field.
  925. *
  926. * @return void
  927. */
  928. protected function setFieldOriginalValue()
  929. {
  930. $this->fillFields($this->model->toArray());
  931. }
  932. /**
  933. * @example
  934. * $form->if(true)->then(function (Form $form) {
  935. * $form->text('name');
  936. * });
  937. *
  938. * $form->if(function (Form $form) {
  939. * return $form->model()->id > 5;
  940. * })->then(function (Form $form) {
  941. * $form->text('name');
  942. * });
  943. *
  944. * $form->if(true)->now(function (Form $form) {
  945. * $form->text('name');
  946. * });
  947. *
  948. * $form->if(true)->creating(function (Form $form) {});
  949. *
  950. * $form->if(true)->removeField('name');
  951. *
  952. * @param bool|\Closure $condition
  953. *
  954. * @return Condition
  955. */
  956. public function if($condition)
  957. {
  958. return $this->conditions[] = new Condition($condition, $this);
  959. }
  960. /**
  961. * @return void
  962. */
  963. protected function rendering()
  964. {
  965. $this->build();
  966. if ($this->isCreating()) {
  967. $this->callCreating();
  968. return;
  969. }
  970. $this->callEditing();
  971. $this->setFieldOriginalValue();
  972. }
  973. /**
  974. * @param array $data
  975. *
  976. * @return void
  977. */
  978. public function fillFields(array $data)
  979. {
  980. $this->builder->fields()->each(function (Field $field) use ($data) {
  981. if (! in_array($field->column(), $this->ignored, true)) {
  982. $field->fill($data);
  983. }
  984. });
  985. }
  986. /**
  987. * @return void
  988. */
  989. protected function build()
  990. {
  991. if ($callback = $this->callback) {
  992. $callback($this);
  993. }
  994. foreach ($this->conditions as $condition) {
  995. $condition->process();
  996. }
  997. }
  998. /**
  999. * Get validation messages.
  1000. *
  1001. * @param array $input
  1002. *
  1003. * @return MessageBag|bool
  1004. */
  1005. public function validationMessages($input)
  1006. {
  1007. $failedValidators = [];
  1008. /** @var Field $field */
  1009. foreach ($this->builder->fields() as $field) {
  1010. if (! $validator = $field->getValidator($input)) {
  1011. continue;
  1012. }
  1013. if (($validator instanceof Validator) && ! $validator->passes()) {
  1014. $failedValidators[] = $validator;
  1015. }
  1016. }
  1017. $message = $this->mergeValidationMessages($failedValidators);
  1018. if ($message->any() && $this->builder->isCreating()) {
  1019. $this->deleteFilesWhenCreating($input);
  1020. }
  1021. return $message->any() ? $message : false;
  1022. }
  1023. /**
  1024. * @param string|array|MessageProvider $column
  1025. * @param string|array $messages
  1026. *
  1027. * @return $this
  1028. */
  1029. public function responseValidationMessages($column, $messages = null)
  1030. {
  1031. if ($column instanceof MessageProvider) {
  1032. return $this->responseValidationMessages($column->getMessageBag()->getMessages());
  1033. }
  1034. if (! $this->validationMessages) {
  1035. $this->validationMessages = new MessageBag();
  1036. }
  1037. if (! $column) {
  1038. return $this;
  1039. }
  1040. if (is_array($column)) {
  1041. foreach ($column as $k => &$v) {
  1042. $v = (array) $v;
  1043. }
  1044. $this->validationMessages->merge($column);
  1045. } elseif ($messages) {
  1046. $this->validationMessages->merge([$column => (array) $messages]);
  1047. }
  1048. return $this;
  1049. }
  1050. /**
  1051. * Merge validation messages from input validators.
  1052. *
  1053. * @param \Illuminate\Validation\Validator[] $validators
  1054. *
  1055. * @return MessageBag
  1056. */
  1057. protected function mergeValidationMessages($validators)
  1058. {
  1059. $messageBag = new MessageBag();
  1060. foreach ($validators as $validator) {
  1061. $messageBag = $messageBag->merge($validator->messages());
  1062. }
  1063. if ($this->validationMessages) {
  1064. return $messageBag->merge($this->validationMessages);
  1065. }
  1066. return $messageBag;
  1067. }
  1068. /**
  1069. * Get or set action for form.
  1070. *
  1071. * @param string|null $action
  1072. *
  1073. * @return $this|string
  1074. */
  1075. public function action($action = null)
  1076. {
  1077. $value = $this->builder->action($action);
  1078. if ($action === null) {
  1079. return $value;
  1080. }
  1081. return $this;
  1082. }
  1083. /**
  1084. * Set field and label width in current form.
  1085. *
  1086. * @param int $fieldWidth
  1087. * @param int $labelWidth
  1088. *
  1089. * @return $this
  1090. */
  1091. public function width($fieldWidth = 8, $labelWidth = 2)
  1092. {
  1093. $this->builder->fields()->each(function ($field) use ($fieldWidth, $labelWidth) {
  1094. /* @var Field $field */
  1095. $field->width($fieldWidth, $labelWidth);
  1096. });
  1097. $this->builder->width($fieldWidth, $labelWidth);
  1098. return $this;
  1099. }
  1100. /**
  1101. * Set view for form.
  1102. *
  1103. * @param string $view
  1104. *
  1105. * @return $this
  1106. */
  1107. public function view($view)
  1108. {
  1109. $this->builder->view($view);
  1110. return $this;
  1111. }
  1112. /**
  1113. * Get or set title for form.
  1114. *
  1115. * @param string $title
  1116. *
  1117. * @return $this
  1118. */
  1119. public function title($title = null)
  1120. {
  1121. $this->builder->title($title);
  1122. return $this;
  1123. }
  1124. /**
  1125. * Add a row in form.
  1126. *
  1127. * @param Closure $callback
  1128. *
  1129. * @return $this
  1130. */
  1131. public function row(Closure $callback)
  1132. {
  1133. $this->rows[] = new Row($callback, $this);
  1134. return $this;
  1135. }
  1136. /**
  1137. * @return Row[]
  1138. */
  1139. public function rows()
  1140. {
  1141. return $this->rows;
  1142. }
  1143. /**
  1144. * Tools setting for form.
  1145. *
  1146. * @param Closure|string|AbstractTool|Renderable|Action|array $callback
  1147. *
  1148. * @return $this;
  1149. */
  1150. public function tools($callback)
  1151. {
  1152. if ($callback instanceof Closure) {
  1153. $callback->call($this, $this->builder->tools());
  1154. return $this;
  1155. }
  1156. if (! is_array($callback)) {
  1157. $callback = [$callback];
  1158. }
  1159. foreach ($callback as $tool) {
  1160. $this->builder->tools()->append($tool);
  1161. }
  1162. return $this;
  1163. }
  1164. /**
  1165. * @param bool $disable
  1166. *
  1167. * @return $this
  1168. */
  1169. public function disableHeader(bool $disable = true)
  1170. {
  1171. $this->builder->disableHeader($disable);
  1172. return $this;
  1173. }
  1174. /**
  1175. * @param bool $disable
  1176. *
  1177. * @return $this
  1178. */
  1179. public function disableFooter(bool $disable = true)
  1180. {
  1181. $this->builder->disableFooter($disable);
  1182. return $this;
  1183. }
  1184. /**
  1185. * Disable form submit.
  1186. *
  1187. * @return $this
  1188. */
  1189. public function disableSubmitButton(bool $disable = true)
  1190. {
  1191. $this->builder->footer()->disableSubmit($disable);
  1192. return $this;
  1193. }
  1194. /**
  1195. * Disable form reset.
  1196. *
  1197. * @return $this
  1198. */
  1199. public function disableResetButton(bool $disable = true)
  1200. {
  1201. $this->builder->footer()->disableReset($disable);
  1202. return $this;
  1203. }
  1204. /**
  1205. * Disable View Checkbox on footer.
  1206. *
  1207. * @return $this
  1208. */
  1209. public function disableViewCheck(bool $disable = true)
  1210. {
  1211. $this->builder->footer()->disableViewCheck($disable);
  1212. return $this;
  1213. }
  1214. /**
  1215. * Disable Editing Checkbox on footer.
  1216. *
  1217. * @return $this
  1218. */
  1219. public function disableEditingCheck(bool $disable = true)
  1220. {
  1221. $this->builder->footer()->disableEditingCheck($disable);
  1222. return $this;
  1223. }
  1224. /**
  1225. * Disable Creating Checkbox on footer.
  1226. *
  1227. * @return $this
  1228. */
  1229. public function disableCreatingCheck(bool $disable = true)
  1230. {
  1231. $this->builder->footer()->disableCreatingCheck($disable);
  1232. return $this;
  1233. }
  1234. /**
  1235. * Disable `view` tool.
  1236. *
  1237. * @return $this
  1238. */
  1239. public function disableViewButton(bool $disable = true)
  1240. {
  1241. $this->builder->tools()->disableView($disable);
  1242. return $this;
  1243. }
  1244. /**
  1245. * Disable `list` tool.
  1246. *
  1247. * @return $this
  1248. */
  1249. public function disableListButton(bool $disable = true)
  1250. {
  1251. $this->builder->tools()->disableList($disable);
  1252. return $this;
  1253. }
  1254. /**
  1255. * Disable `delete` tool.
  1256. *
  1257. * @return $this
  1258. */
  1259. public function disableDeleteButton(bool $disable = true)
  1260. {
  1261. $this->builder->tools()->disableDelete($disable);
  1262. return $this;
  1263. }
  1264. /**
  1265. * Footer setting for form.
  1266. *
  1267. * @param Closure $callback
  1268. *
  1269. * @return $this
  1270. */
  1271. public function footer(Closure $callback)
  1272. {
  1273. call_user_func($callback, $this->builder->footer());
  1274. return $this;
  1275. }
  1276. /**
  1277. * Get current resource route url.
  1278. *
  1279. * @param int $slice
  1280. *
  1281. * @return string
  1282. */
  1283. public function getResource($slice = -2)
  1284. {
  1285. $path = $this->resource ?: $this->request->getUri();
  1286. $segments = explode('/', trim($path, '/'));
  1287. if ($slice != 0) {
  1288. $segments = array_slice($segments, 0, $slice);
  1289. }
  1290. return url(implode('/', $segments));
  1291. }
  1292. /**
  1293. * Set resource path.
  1294. *
  1295. * @param string $resource
  1296. *
  1297. * @return $this
  1298. */
  1299. public function resource(string $resource)
  1300. {
  1301. if ($resource) {
  1302. $this->resource = admin_url($resource);
  1303. }
  1304. return $this;
  1305. }
  1306. /**
  1307. * Render the form contents.
  1308. *
  1309. * @return string
  1310. */
  1311. public function render()
  1312. {
  1313. try {
  1314. $this->rendering();
  1315. $this->callComposing();
  1316. return $this->builder->render();
  1317. } catch (\Throwable $e) {
  1318. return Admin::makeExceptionHandler()->renderException($e);
  1319. }
  1320. }
  1321. /**
  1322. * Get or set input data.
  1323. *
  1324. * @param string $key
  1325. * @param null $value
  1326. *
  1327. * @return array|mixed
  1328. */
  1329. public function input($key, $value = null)
  1330. {
  1331. if (is_null($value)) {
  1332. return Arr::get($this->inputs, $key);
  1333. }
  1334. return Arr::set($this->inputs, $key, $value);
  1335. }
  1336. /**
  1337. * @param string|array $keys
  1338. *
  1339. * @return void
  1340. */
  1341. public function deleteInput($keys)
  1342. {
  1343. Arr::forget($this->inputs, $keys);
  1344. }
  1345. /**
  1346. * @param int $width
  1347. * @param Closure $callback
  1348. */
  1349. public function block(int $width, \Closure $callback)
  1350. {
  1351. $layout = $this->builder->layout();
  1352. $layout->column($width, $callback($layout->form()));
  1353. }
  1354. /**
  1355. * @param int $width
  1356. *
  1357. * @return $this
  1358. */
  1359. public function setDefaultBlockWidth(int $width)
  1360. {
  1361. $this->builder->setDefaultBlockWidth($width);
  1362. return $this;
  1363. }
  1364. /**
  1365. * @return $this
  1366. */
  1367. protected function prepareDialogForm()
  1368. {
  1369. DialogForm::prepare($this);
  1370. return $this;
  1371. }
  1372. /**
  1373. * @param Closure $callback
  1374. *
  1375. * @return bool|void
  1376. */
  1377. public function inModal(\Closure $callback = null)
  1378. {
  1379. if (! $callback) {
  1380. return DialogForm::is();
  1381. }
  1382. if (DialogForm::is()) {
  1383. $callback($this);
  1384. }
  1385. }
  1386. /**
  1387. * Create a dialog form.
  1388. *
  1389. * @param string|null $title
  1390. *
  1391. * @return DialogForm
  1392. */
  1393. public static function dialog(?string $title = null)
  1394. {
  1395. return new DialogForm($title);
  1396. }
  1397. /**
  1398. * Register custom field.
  1399. *
  1400. * @param string $abstract
  1401. * @param string $class
  1402. *
  1403. * @return void
  1404. */
  1405. public static function extend($abstract, $class)
  1406. {
  1407. static::$availableFields[$abstract] = $class;
  1408. }
  1409. /**
  1410. * @return array
  1411. */
  1412. public static function extensions()
  1413. {
  1414. return static::$availableFields;
  1415. }
  1416. /**
  1417. * Set form field alias.
  1418. *
  1419. * @param string $field
  1420. * @param string $alias
  1421. *
  1422. * @return void
  1423. */
  1424. public static function alias($field, $alias)
  1425. {
  1426. static::$fieldAlias[$alias] = $field;
  1427. }
  1428. /**
  1429. * Find field class.
  1430. *
  1431. * @param string $method
  1432. *
  1433. * @return bool|mixed
  1434. */
  1435. public static function findFieldClass($method)
  1436. {
  1437. // If alias exists.
  1438. if (isset(static::$fieldAlias[$method])) {
  1439. $method = static::$fieldAlias[$method];
  1440. }
  1441. $class = Arr::get(static::$availableFields, $method);
  1442. if (class_exists($class)) {
  1443. return $class;
  1444. }
  1445. return false;
  1446. }
  1447. /**
  1448. * Getter.
  1449. *
  1450. * @param string $name
  1451. *
  1452. * @return array|mixed
  1453. */
  1454. public function __get($name)
  1455. {
  1456. return $this->input($name);
  1457. }
  1458. /**
  1459. * Setter.
  1460. *
  1461. * @param string $name
  1462. * @param mixed $value
  1463. */
  1464. public function __set($name, $value)
  1465. {
  1466. return Arr::set($this->inputs, $name, $value);
  1467. }
  1468. /**
  1469. * Generate a Field object and add to form builder if Field exists.
  1470. *
  1471. * @param string $method
  1472. * @param array $arguments
  1473. *
  1474. * @return Field
  1475. */
  1476. public function __call($method, $arguments)
  1477. {
  1478. if (static::hasMacro($method)) {
  1479. return $this->macroCall($method, $arguments);
  1480. }
  1481. if ($className = static::findFieldClass($method)) {
  1482. $column = Arr::get($arguments, 0, '');
  1483. $element = new $className($column, array_slice($arguments, 1));
  1484. $this->pushField($element);
  1485. return $element;
  1486. }
  1487. admin_error('Error', "Field type [$method] does not exist.");
  1488. return new Field\Nullable();
  1489. }
  1490. }