Form.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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\HasHtmlAttributes;
  8. use Dcat\EasyExcel\Support\Traits\Macroable;
  9. use Illuminate\Contracts\Support\Arrayable;
  10. use Illuminate\Contracts\Support\Renderable;
  11. use Illuminate\Support\Arr;
  12. use Illuminate\Support\Fluent;
  13. use Illuminate\Support\Str;
  14. /**
  15. * Class Form.
  16. *
  17. * @method Field\Text text($column, $label = '')
  18. * @method Field\Checkbox checkbox($column, $label = '')
  19. * @method Field\Radio radio($column, $label = '')
  20. * @method Field\Select select($column, $label = '')
  21. * @method Field\MultipleSelect multipleSelect($column, $label = '')
  22. * @method Field\Textarea textarea($column, $label = '')
  23. * @method Field\Hidden hidden($column, $label = '')
  24. * @method Field\Id id($column, $label = '')
  25. * @method Field\Ip ip($column, $label = '')
  26. * @method Field\Url url($column, $label = '')
  27. * @method Field\Color color($column, $label = '')
  28. * @method Field\Email email($column, $label = '')
  29. * @method Field\Mobile mobile($column, $label = '')
  30. * @method Field\Slider slider($column, $label = '')
  31. * @method Field\Map map($latitude, $longitude, $label = '')
  32. * @method Field\Editor editor($column, $label = '')
  33. * @method Field\Date date($column, $label = '')
  34. * @method Field\Datetime datetime($column, $label = '')
  35. * @method Field\Time time($column, $label = '')
  36. * @method Field\Year year($column, $label = '')
  37. * @method Field\Month month($column, $label = '')
  38. * @method Field\DateRange dateRange($start, $end, $label = '')
  39. * @method Field\DateTimeRange datetimeRange($start, $end, $label = '')
  40. * @method Field\TimeRange timeRange($start, $end, $label = '')
  41. * @method Field\Number number($column, $label = '')
  42. * @method Field\Currency currency($column, $label = '')
  43. * @method Field\SwitchField switch($column, $label = '')
  44. * @method Field\Display display($column, $label = '')
  45. * @method Field\Rate rate($column, $label = '')
  46. * @method Field\Divide divider()
  47. * @method Field\Password password($column, $label = '')
  48. * @method Field\Decimal decimal($column, $label = '')
  49. * @method Field\Html html($html, $label = '')
  50. * @method Field\Tags tags($column, $label = '')
  51. * @method Field\Icon icon($column, $label = '')
  52. * @method Field\Embeds embeds($column, $label = '')
  53. * @method Field\Captcha captcha($column, $label = '')
  54. * @method Field\Listbox listbox($column, $label = '')
  55. * @method Field\SelectResource selectResource($column, $label = '')
  56. * @method Field\File file($column, $label = '')
  57. * @method Field\Image image($column, $label = '')
  58. * @method Field\MultipleFile multipleFile($column, $label = '')
  59. * @method Field\MultipleImage multipleImage($column, $label = '')
  60. * @method Field\HasMany hasMany($column, \Closure $callback)
  61. * @method Field\Tree tree($column, $label = '')
  62. * @method Field\Table table($column, $callback)
  63. * @method Field\ListField list($column, $label = '')
  64. * @method Field\Timezone timezone($column, $label = '')
  65. * @method Field\KeyValue keyValue($column, $label = '')
  66. * @method Field\Tel tel($column, $label = '')
  67. *
  68. * @method Field\BootstrapFile bootstrapFile($column, $label = '')
  69. * @method Field\BootstrapImage bootstrapImage($column, $label = '')
  70. * @method Field\BootstrapMultipleImage bootstrapMultipleImage($column, $label = '')
  71. * @method Field\BootstrapMultipleFile bootstrapMultipleFile($column, $label = '')
  72. */
  73. class Form implements Renderable
  74. {
  75. use HasHtmlAttributes, Macroable {
  76. __call as macroCall;
  77. }
  78. /**
  79. * @var Field[]
  80. */
  81. protected $fields = [];
  82. /**
  83. * @var bool
  84. */
  85. protected $useAjaxSubmit = true;
  86. /**
  87. * @var Fluent
  88. */
  89. protected $data;
  90. /**
  91. * @var mixed
  92. */
  93. protected $primaryKey;
  94. /**
  95. * Available buttons.
  96. *
  97. * @var array
  98. */
  99. protected $buttons = ['reset', 'submit'];
  100. /**
  101. * @var bool
  102. */
  103. protected $useFormTag = true;
  104. /**
  105. * @var string
  106. */
  107. protected $formId;
  108. /**
  109. * @var array
  110. */
  111. protected $width = [
  112. 'label' => 2,
  113. 'field' => 8,
  114. ];
  115. /**
  116. * Form constructor.
  117. *
  118. * @param array $data
  119. * @param mixed $key
  120. */
  121. public function __construct($data = [], $key = null)
  122. {
  123. $this->data($data);
  124. $this->key($key);
  125. $this->initFormAttributes();
  126. }
  127. /**
  128. * Initialize the form attributes.
  129. */
  130. protected function initFormAttributes()
  131. {
  132. $this->setHtmlAttribute([
  133. 'method' => 'POST',
  134. 'action' => '',
  135. 'class' => 'form-horizontal',
  136. 'accept-charset' => 'UTF-8',
  137. 'pjax-container' => true,
  138. ]);
  139. }
  140. /**
  141. * Action uri of the form.
  142. *
  143. * @param string $action
  144. *
  145. * @return $this
  146. */
  147. public function action($action)
  148. {
  149. return $this->setHtmlAttribute('action', $action);
  150. }
  151. /**
  152. * @return mixed
  153. */
  154. public function getAction()
  155. {
  156. return $this->getHtmlAttribute('action');
  157. }
  158. /**
  159. * Method of the form.
  160. *
  161. * @param string $method
  162. *
  163. * @return $this
  164. */
  165. public function method($method = 'POST')
  166. {
  167. return $this->setHtmlAttribute('method', strtoupper($method));
  168. }
  169. /**
  170. * Set primary key.
  171. *
  172. * @param mixed $value
  173. * @return $this
  174. */
  175. public function key($value)
  176. {
  177. $this->primaryKey = $value;
  178. return $this;
  179. }
  180. /**
  181. * @return mixed
  182. */
  183. public function getKey()
  184. {
  185. return $this->primaryKey;
  186. }
  187. /**
  188. * @param $data
  189. * @return $this
  190. */
  191. public function data($data)
  192. {
  193. $this->data = new Fluent(Helper::array($data));
  194. return $this;
  195. }
  196. /**
  197. * @return Fluent
  198. */
  199. public function model()
  200. {
  201. return $this->data;
  202. }
  203. /**
  204. * Add a fieldset to form.
  205. *
  206. * @param string $title
  207. * @param Closure $setCallback
  208. *
  209. * @return Field\Fieldset
  210. */
  211. public function fieldset(string $title, Closure $setCallback)
  212. {
  213. $fieldset = new Field\Fieldset();
  214. $this->html($fieldset->start($title))->plain();
  215. $setCallback($this);
  216. $this->html($fieldset->end())->plain();
  217. return $fieldset;
  218. }
  219. /**
  220. * Get specify field.
  221. *
  222. * @param string $name
  223. * @return Field|null
  224. */
  225. public function field($name)
  226. {
  227. foreach ($this->fields as $field) {
  228. if ($field->column() === $name) {
  229. return $field;
  230. }
  231. }
  232. }
  233. /**
  234. * Disable Pjax.
  235. *
  236. * @return $this
  237. */
  238. public function disablePjax()
  239. {
  240. $this->forgetHtmlAttribute('pjax-container');
  241. return $this;
  242. }
  243. /**
  244. * Disable form tag.
  245. *
  246. * @return $this;
  247. */
  248. public function disableFormTag()
  249. {
  250. $this->useFormTag = false;
  251. return $this;
  252. }
  253. /**
  254. * Disable reset button.
  255. *
  256. * @return $this
  257. */
  258. public function disableResetButton()
  259. {
  260. array_delete($this->buttons, 'reset');
  261. return $this;
  262. }
  263. /**
  264. * Disable submit button.
  265. *
  266. * @return $this
  267. */
  268. public function disableSubmitButton()
  269. {
  270. array_delete($this->buttons, 'submit');
  271. return $this;
  272. }
  273. /**
  274. * Set field and label width in current form.
  275. *
  276. * @param int $fieldWidth
  277. * @param int $labelWidth
  278. *
  279. * @return $this
  280. */
  281. public function setWidth($fieldWidth = 8, $labelWidth = 2)
  282. {
  283. $this->width = [
  284. 'label' => $labelWidth,
  285. 'field' => $fieldWidth,
  286. ];
  287. collect($this->fields)->each(function ($field) use ($fieldWidth, $labelWidth) {
  288. /* @var Field $field */
  289. $field->setWidth($fieldWidth, $labelWidth);
  290. });
  291. return $this;
  292. }
  293. /**
  294. * Find field class with given name.
  295. *
  296. * @param string $method
  297. *
  298. * @return bool|string
  299. */
  300. public static function findFieldClass($method)
  301. {
  302. $class = Arr::get(\Dcat\Admin\Form::getExtensions(), $method);
  303. if (class_exists($class)) {
  304. return $class;
  305. }
  306. return false;
  307. }
  308. /**
  309. * Add a form field to form.
  310. *
  311. * @param Field $field
  312. *
  313. * @return $this
  314. */
  315. public function pushField(Field &$field)
  316. {
  317. array_push($this->fields, $field);
  318. $field->setForm($this);
  319. $field->setWidth($this->width['field'], $this->width['label']);
  320. $field::collectAssets();
  321. return $this;
  322. }
  323. /**
  324. * Get variables for render form.
  325. *
  326. * @return array
  327. */
  328. protected function getVariables()
  329. {
  330. $this->setHtmlAttribute('id', $this->getFormId());
  331. foreach ($this->fields as $field) {
  332. $field->fill($this->data->toArray());
  333. }
  334. return [
  335. 'start' => $this->open(),
  336. 'end' => $this->close(),
  337. 'fields' => $this->fields,
  338. 'method' => $this->getHtmlAttribute('method'),
  339. 'buttons' => $this->buttons,
  340. ];
  341. }
  342. /**
  343. * @return string
  344. */
  345. protected function open()
  346. {
  347. return <<<HTML
  348. <form {$this->formatHtmlAttributes()}>
  349. HTML;
  350. }
  351. /**
  352. * @return string
  353. */
  354. protected function close()
  355. {
  356. return '</form>';
  357. }
  358. /**
  359. * Determine if form fields has files.
  360. *
  361. * @return bool
  362. */
  363. public function hasFile()
  364. {
  365. foreach ($this->fields as $field) {
  366. if ($field instanceof Field\File) {
  367. return true;
  368. }
  369. }
  370. return false;
  371. }
  372. /**
  373. * @param $id
  374. * @return $this
  375. */
  376. public function setFormId($id)
  377. {
  378. $this->formId = $id;
  379. return $this;
  380. }
  381. /**
  382. * @return string
  383. */
  384. public function getFormId()
  385. {
  386. return $this->formId ?: ($this->formId = 'form-'.Str::random(8));
  387. }
  388. /**
  389. * Generate a Field object and add to form builder if Field exists.
  390. *
  391. * @param string $method
  392. * @param array $arguments
  393. *
  394. * @return Field|null
  395. */
  396. public function __call($method, $arguments)
  397. {
  398. if ($className = static::findFieldClass($method)) {
  399. $name = Arr::get($arguments, 0, '');
  400. $element = new $className($name, array_slice($arguments, 1));
  401. $this->pushField($element);
  402. return $element;
  403. }
  404. if (static::hasMacro($method)) {
  405. return $this->macroCall($method, $arguments);
  406. }
  407. }
  408. /**
  409. * Disable submit with ajax.
  410. *
  411. * @param bool $disable
  412. * @return $this
  413. */
  414. public function disableAjaxSubmit(bool $disable = true)
  415. {
  416. $this->useAjaxSubmit = !$disable;
  417. return $this;
  418. }
  419. /**
  420. * @return bool
  421. */
  422. public function allowAjaxSubmit()
  423. {
  424. return $this->useAjaxSubmit === true;
  425. }
  426. protected function setupSubmitScript()
  427. {
  428. Admin::script(
  429. <<<JS
  430. var f = $('#{$this->getFormId()}');
  431. f.find('[type="submit"]').click(function () {
  432. var t = $(this);
  433. LA.Form({
  434. \$form: f,
  435. before: function () {
  436. f.validator('validate');
  437. if (f.find('.has-error').length > 0) {
  438. return false;
  439. }
  440. t.button('loading');
  441. },
  442. after: function () {
  443. t.button('reset');
  444. }
  445. });
  446. return false;
  447. });
  448. JS
  449. );
  450. }
  451. /**
  452. * Render the form.
  453. *
  454. * @return string
  455. */
  456. public function render()
  457. {
  458. $this->useAjaxSubmit && $this->setupSubmitScript();
  459. return view('admin::widgets.form', $this->getVariables())->render();
  460. }
  461. /**
  462. * Output as string.
  463. *
  464. * @return string
  465. */
  466. public function __toString()
  467. {
  468. return $this->render();
  469. }
  470. }