Form.php 44 KB

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