Form.php 42 KB

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