Form.php 42 KB

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