Form.php 11 KB

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