Form.php 41 KB

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