Form.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. <?php
  2. namespace Dcat\Admin\Widgets;
  3. use Closure;
  4. use Dcat\Admin\Admin;
  5. use Dcat\Admin\Form\Field;
  6. use Dcat\Admin\Support\Helper;
  7. use Dcat\Admin\Traits\HasFormResponse;
  8. use Dcat\Admin\Traits\HasHtmlAttributes;
  9. use Illuminate\Contracts\Support\Arrayable;
  10. use Illuminate\Contracts\Support\Renderable;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Support\Arr;
  13. use Illuminate\Support\Collection;
  14. use Illuminate\Support\Fluent;
  15. use Illuminate\Support\MessageBag;
  16. use Illuminate\Support\Str;
  17. use Illuminate\Support\Traits\Macroable;
  18. use Illuminate\Validation\Validator;
  19. /**
  20. * Class Form.
  21. *
  22. * @method Field\Text text($column, $label = '')
  23. * @method Field\Checkbox checkbox($column, $label = '')
  24. * @method Field\Radio radio($column, $label = '')
  25. * @method Field\Select select($column, $label = '')
  26. * @method Field\MultipleSelect multipleSelect($column, $label = '')
  27. * @method Field\Textarea textarea($column, $label = '')
  28. * @method Field\Hidden hidden($column, $label = '')
  29. * @method Field\Id id($column, $label = '')
  30. * @method Field\Ip ip($column, $label = '')
  31. * @method Field\Url url($column, $label = '')
  32. * @method Field\Color color($column, $label = '')
  33. * @method Field\Email email($column, $label = '')
  34. * @method Field\Mobile mobile($column, $label = '')
  35. * @method Field\Slider slider($column, $label = '')
  36. * @method Field\Map map($latitude, $longitude, $label = '')
  37. * @method Field\Editor editor($column, $label = '')
  38. * @method Field\Date date($column, $label = '')
  39. * @method Field\Datetime datetime($column, $label = '')
  40. * @method Field\Time time($column, $label = '')
  41. * @method Field\Year year($column, $label = '')
  42. * @method Field\Month month($column, $label = '')
  43. * @method Field\DateRange dateRange($start, $end, $label = '')
  44. * @method Field\DateTimeRange datetimeRange($start, $end, $label = '')
  45. * @method Field\TimeRange timeRange($start, $end, $label = '')
  46. * @method Field\Number number($column, $label = '')
  47. * @method Field\Currency currency($column, $label = '')
  48. * @method Field\SwitchField switch($column, $label = '')
  49. * @method Field\Display display($column, $label = '')
  50. * @method Field\Rate rate($column, $label = '')
  51. * @method Field\Divide divider()
  52. * @method Field\Password password($column, $label = '')
  53. * @method Field\Decimal decimal($column, $label = '')
  54. * @method Field\Html html($html, $label = '')
  55. * @method Field\Tags tags($column, $label = '')
  56. * @method Field\Icon icon($column, $label = '')
  57. * @method Field\Embeds embeds($column, $label = '')
  58. * @method Field\Captcha captcha($column, $label = '')
  59. * @method Field\Listbox listbox($column, $label = '')
  60. * @method Field\SelectResource selectResource($column, $label = '')
  61. * @method Field\File file($column, $label = '')
  62. * @method Field\Image image($column, $label = '')
  63. * @method Field\MultipleFile multipleFile($column, $label = '')
  64. * @method Field\MultipleImage multipleImage($column, $label = '')
  65. * @method Field\HasMany hasMany($column, \Closure $callback)
  66. * @method Field\Tree tree($column, $label = '')
  67. * @method Field\Table table($column, $callback)
  68. * @method Field\ListField list($column, $label = '')
  69. * @method Field\Timezone timezone($column, $label = '')
  70. * @method Field\KeyValue keyValue($column, $label = '')
  71. * @method Field\Tel tel($column, $label = '')
  72. * @method Field\BootstrapFile bootstrapFile($column, $label = '')
  73. * @method Field\BootstrapImage bootstrapImage($column, $label = '')
  74. * @method Field\BootstrapMultipleImage bootstrapMultipleImage($column, $label = '')
  75. * @method Field\BootstrapMultipleFile bootstrapMultipleFile($column, $label = '')
  76. */
  77. class Form implements Renderable
  78. {
  79. use HasHtmlAttributes,
  80. HasFormResponse,
  81. Macroable {
  82. __call as macroCall;
  83. }
  84. /**
  85. * @var string
  86. */
  87. protected $view = 'admin::widgets.form';
  88. /**
  89. * @var Field[]|Collection
  90. */
  91. protected $fields;
  92. /**
  93. * @var bool
  94. */
  95. protected $useAjaxSubmit = true;
  96. /**
  97. * @var Fluent
  98. */
  99. protected $data;
  100. /**
  101. * @var mixed
  102. */
  103. protected $primaryKey;
  104. /**
  105. * Available buttons.
  106. *
  107. * @var array
  108. */
  109. protected $buttons = ['reset' => true, 'submit' => true];
  110. /**
  111. * @var bool
  112. */
  113. protected $useFormTag = true;
  114. /**
  115. * @var string
  116. */
  117. protected $elementId;
  118. /**
  119. * @var array
  120. */
  121. protected $width = [
  122. 'label' => 2,
  123. 'field' => 8,
  124. ];
  125. /**
  126. * Form constructor.
  127. *
  128. * @param array $data
  129. * @param mixed $key
  130. */
  131. public function __construct($data = [], $key = null)
  132. {
  133. if ($data) {
  134. $this->fill($data);
  135. }
  136. $this->key($key);
  137. $this->initFields();
  138. $this->initFormAttributes();
  139. }
  140. /**
  141. * Initialize the form fields.
  142. */
  143. protected function initFields()
  144. {
  145. $this->fields = new Collection();
  146. }
  147. /**
  148. * Initialize the form attributes.
  149. */
  150. protected function initFormAttributes()
  151. {
  152. $this->setHtmlAttribute([
  153. 'method' => 'POST',
  154. 'action' => '',
  155. 'class' => 'form-horizontal',
  156. 'accept-charset' => 'UTF-8',
  157. 'pjax-container' => true,
  158. ]);
  159. }
  160. /**
  161. * Action uri of the form.
  162. *
  163. * @param string $action
  164. *
  165. * @return $this|string
  166. */
  167. public function action($action = null)
  168. {
  169. if ($action === null) {
  170. return $this->getHtmlAttribute('action');
  171. }
  172. return $this->setHtmlAttribute('action', $action);
  173. }
  174. /**
  175. * Method of the form.
  176. *
  177. * @param string $method
  178. *
  179. * @return $this
  180. */
  181. public function method($method = 'POST')
  182. {
  183. return $this->setHtmlAttribute('method', strtoupper($method));
  184. }
  185. /**
  186. * Get or set primary key.
  187. *
  188. * @param mixed $value
  189. *
  190. * @return $this
  191. */
  192. public function key($value = null)
  193. {
  194. if ($value === null) {
  195. return $this->primaryKey;
  196. }
  197. $this->primaryKey = $value;
  198. return $this;
  199. }
  200. /**
  201. * @param array|Arrayable|Closure $data
  202. *
  203. * @return Fluent
  204. */
  205. public function data()
  206. {
  207. if (! $this->data) {
  208. $this->fill([]);
  209. }
  210. return $this->data;
  211. }
  212. /**
  213. * @param array|Arrayable|Closure $data
  214. *
  215. * @return $this
  216. */
  217. public function fill($data)
  218. {
  219. $this->data = new Fluent(Helper::array($data));
  220. return $this;
  221. }
  222. /**
  223. * @return Fluent
  224. */
  225. public function model()
  226. {
  227. return $this->data();
  228. }
  229. /**
  230. * Add a fieldset to form.
  231. *
  232. * @param string $title
  233. * @param Closure $setCallback
  234. *
  235. * @return Field\Fieldset
  236. */
  237. public function fieldset(string $title, Closure $setCallback)
  238. {
  239. $fieldset = new Field\Fieldset();
  240. $this->html($fieldset->start($title))->plain();
  241. $setCallback($this);
  242. $this->html($fieldset->end())->plain();
  243. return $fieldset;
  244. }
  245. /**
  246. * Get specify field.
  247. *
  248. * @param string|Field $name
  249. *
  250. * @return Field|null
  251. */
  252. public function field($name)
  253. {
  254. foreach ($this->fields as $field) {
  255. if ($field === $name || $field->column() === $name) {
  256. return $field;
  257. }
  258. }
  259. }
  260. /**
  261. * @return Field[]|Collection
  262. */
  263. public function fields()
  264. {
  265. return $this->fields;
  266. }
  267. /**
  268. * Validate this form fields.
  269. *
  270. * @param Request $request
  271. *
  272. * @return bool|MessageBag
  273. */
  274. public function validate(Request $request)
  275. {
  276. if (method_exists($this, 'form')) {
  277. $this->form();
  278. }
  279. $failedValidators = [];
  280. /** @var \Dcat\Admin\Form\Field $field */
  281. foreach ($this->fields() as $field) {
  282. if (! $validator = $field->getValidator($request->all())) {
  283. continue;
  284. }
  285. if (($validator instanceof Validator) && ! $validator->passes()) {
  286. $failedValidators[] = $validator;
  287. }
  288. }
  289. $message = $this->mergeValidationMessages($failedValidators);
  290. return $message->any() ? $message : false;
  291. }
  292. /**
  293. * Merge validation messages from input validators.
  294. *
  295. * @param \Illuminate\Validation\Validator[] $validators
  296. *
  297. * @return MessageBag
  298. */
  299. protected function mergeValidationMessages($validators)
  300. {
  301. $messageBag = new MessageBag();
  302. foreach ($validators as $validator) {
  303. $messageBag = $messageBag->merge($validator->messages());
  304. }
  305. return $messageBag;
  306. }
  307. /**
  308. * Disable Pjax.
  309. *
  310. * @return $this
  311. */
  312. public function disablePjax()
  313. {
  314. $this->forgetHtmlAttribute('pjax-container');
  315. return $this;
  316. }
  317. /**
  318. * Disable form tag.
  319. *
  320. * @return $this;
  321. */
  322. public function disableFormTag()
  323. {
  324. $this->useFormTag = false;
  325. return $this;
  326. }
  327. /**
  328. * Disable reset button.
  329. *
  330. * @return $this
  331. */
  332. public function disableResetButton()
  333. {
  334. $this->buttons['reset'] = false;
  335. return $this;
  336. }
  337. /**
  338. * Disable submit button.
  339. *
  340. * @return $this
  341. */
  342. public function disableSubmitButton()
  343. {
  344. $this->buttons['submit'] = false;
  345. return $this;
  346. }
  347. /**
  348. * Set field and label width in current form.
  349. *
  350. * @param int $fieldWidth
  351. * @param int $labelWidth
  352. *
  353. * @return $this
  354. */
  355. public function width($fieldWidth = 8, $labelWidth = 2)
  356. {
  357. $this->width = [
  358. 'label' => $labelWidth,
  359. 'field' => $fieldWidth,
  360. ];
  361. $this->fields->each(function ($field) use ($fieldWidth, $labelWidth) {
  362. /* @var Field $field */
  363. $field->width($fieldWidth, $labelWidth);
  364. });
  365. return $this;
  366. }
  367. /**
  368. * Find field class with given name.
  369. *
  370. * @param string $method
  371. *
  372. * @return bool|string
  373. */
  374. public static function findFieldClass($method)
  375. {
  376. $class = Arr::get(\Dcat\Admin\Form::extensions(), $method);
  377. if (class_exists($class)) {
  378. return $class;
  379. }
  380. return false;
  381. }
  382. /**
  383. * Add a form field to form.
  384. *
  385. * @param Field $field
  386. *
  387. * @return $this
  388. */
  389. public function pushField(Field &$field)
  390. {
  391. $this->fields->push($field);
  392. $field->setForm($this);
  393. $field->width($this->width['field'], $this->width['label']);
  394. $field::collectAssets();
  395. return $this;
  396. }
  397. /**
  398. * Get variables for render form.
  399. *
  400. * @return array
  401. */
  402. protected function variables()
  403. {
  404. $this->setHtmlAttribute('id', $this->elementId());
  405. foreach ($this->fields as $field) {
  406. $field->fill($this->model()->toArray());
  407. }
  408. return [
  409. 'start' => $this->open(),
  410. 'end' => $this->close(),
  411. 'fields' => $this->fields,
  412. 'method' => $this->getHtmlAttribute('method'),
  413. 'buttons' => $this->buttons,
  414. ];
  415. }
  416. /**
  417. * @return string
  418. */
  419. protected function open()
  420. {
  421. return <<<HTML
  422. <form {$this->formatHtmlAttributes()}>
  423. HTML;
  424. }
  425. /**
  426. * @return string
  427. */
  428. protected function close()
  429. {
  430. return '</form>';
  431. }
  432. /**
  433. * Determine if form fields has files.
  434. *
  435. * @return bool
  436. */
  437. public function hasFile()
  438. {
  439. foreach ($this->fields as $field) {
  440. if ($field instanceof Field\File) {
  441. return true;
  442. }
  443. }
  444. return false;
  445. }
  446. /**
  447. * @param $id
  448. *
  449. * @return $this
  450. */
  451. public function setFormId($id)
  452. {
  453. $this->elementId = $id;
  454. return $this;
  455. }
  456. /**
  457. * @return string
  458. */
  459. public function elementId()
  460. {
  461. return $this->elementId ?: ($this->elementId = 'form-'.Str::random(8));
  462. }
  463. /**
  464. * Generate a Field object and add to form builder if Field exists.
  465. *
  466. * @param string $method
  467. * @param array $arguments
  468. *
  469. * @return Field|null
  470. */
  471. public function __call($method, $arguments)
  472. {
  473. if ($className = static::findFieldClass($method)) {
  474. $name = Arr::get($arguments, 0, '');
  475. $element = new $className($name, array_slice($arguments, 1));
  476. $this->pushField($element);
  477. return $element;
  478. }
  479. if (static::hasMacro($method)) {
  480. return $this->macroCall($method, $arguments);
  481. }
  482. throw new \Exception("Field [{$method}] does not exist.");
  483. }
  484. /**
  485. * Disable submit with ajax.
  486. *
  487. * @param bool $disable
  488. *
  489. * @return $this
  490. */
  491. public function disableAjaxSubmit(bool $disable = true)
  492. {
  493. $this->useAjaxSubmit = ! $disable;
  494. return $this;
  495. }
  496. /**
  497. * @return bool
  498. */
  499. public function allowAjaxSubmit()
  500. {
  501. return $this->useAjaxSubmit === true;
  502. }
  503. /**
  504. * @return void
  505. */
  506. protected function setupSubmitScript()
  507. {
  508. Admin::script(
  509. <<<JS
  510. (function () {
  511. var f = $('#{$this->elementId()}');
  512. f.find('[type="submit"]').click(function () {
  513. var t = $(this);
  514. LA.Form({
  515. \$form: f,
  516. before: function () {
  517. f.validator('validate');
  518. if (f.find('.has-error').length > 0) {
  519. return false;
  520. }
  521. t.button('loading');
  522. },
  523. after: function () {
  524. t.button('reset');
  525. }
  526. });
  527. return false;
  528. });
  529. })()
  530. JS
  531. );
  532. }
  533. /**
  534. * @param array $input
  535. *
  536. * @return array
  537. */
  538. public function sanitize(array $input)
  539. {
  540. Arr::forget($input, ['_form_', '_token', '_current_']);
  541. return $input;
  542. }
  543. protected function prepareForm()
  544. {
  545. if (method_exists($this, 'form')) {
  546. $this->form();
  547. }
  548. if (! $this->data && method_exists($this, 'default')) {
  549. $data = $this->default();
  550. if (is_array($data)) {
  551. $this->fill($data);
  552. }
  553. }
  554. }
  555. protected function prepareHandle()
  556. {
  557. if (method_exists($this, 'handle')) {
  558. $this->method('POST');
  559. $this->action(admin_url('_handle_form_'));
  560. $this->hidden('_form_')->default(get_called_class());
  561. $this->hidden('_current_')->default($this->getCurrentUrl());
  562. }
  563. }
  564. /**
  565. * Render the form.
  566. *
  567. * @return string
  568. */
  569. public function render()
  570. {
  571. $this->prepareForm();
  572. $this->prepareHandle();
  573. if ($this->allowAjaxSubmit()) {
  574. $this->setupSubmitScript();
  575. }
  576. return view($this->view, $this->variables())->render();
  577. }
  578. /**
  579. * Output as string.
  580. *
  581. * @return string
  582. */
  583. public function __toString()
  584. {
  585. return $this->render();
  586. }
  587. /**
  588. * @param mixed ...$params
  589. *
  590. * @return $this
  591. */
  592. public static function make(...$params)
  593. {
  594. return new static(...$params);
  595. }
  596. }