Form.php 44 KB

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