Form.php 42 KB

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