Form.php 43 KB

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