Form.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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\Tree tree($column, $label = '')
  57. * @method Field\Table table($column, $callback)
  58. * @method Field\ListField list($column, $label = '')
  59. * @method Field\Timezone timezone($column, $label = '')
  60. * @method Field\KeyValue keyValue($column, $label = '')
  61. *
  62. * @method Field\BootstrapFile bootstrapFile($column, $label = '')
  63. * @method Field\BootstrapImage bootstrapImage($column, $label = '')
  64. * @method Field\BootstrapMultipleImage bootstrapMultipleImage($column, $label = '')
  65. * @method Field\BootstrapMultipleFile bootstrapMultipleFile($column, $label = '')
  66. */
  67. class Form implements Renderable
  68. {
  69. /**
  70. * @var Field[]
  71. */
  72. protected $fields = [];
  73. /**
  74. * @var bool
  75. */
  76. protected $useAjaxSubmit = true;
  77. /**
  78. * @var array
  79. */
  80. protected $data = [];
  81. /**
  82. * @var array
  83. */
  84. protected $attributes = [];
  85. /**
  86. * Available buttons.
  87. *
  88. * @var array
  89. */
  90. protected $buttons = ['reset', 'submit'];
  91. /**
  92. * @var bool
  93. */
  94. protected $useFormTag = true;
  95. /**
  96. * @var string
  97. */
  98. protected $formId;
  99. /**
  100. * Form constructor.
  101. *
  102. * @param array $data
  103. */
  104. public function __construct($data = [])
  105. {
  106. if ($data instanceof Arrayable) {
  107. $data = $data->toArray();
  108. }
  109. if (!empty($data)) {
  110. $this->data = $data;
  111. }
  112. $this->initFormAttributes();
  113. }
  114. /**
  115. * Initialize the form attributes.
  116. */
  117. protected function initFormAttributes()
  118. {
  119. $this->attributes = [
  120. 'method' => 'POST',
  121. 'action' => '',
  122. 'class' => 'form-horizontal',
  123. 'accept-charset' => 'UTF-8',
  124. 'pjax-container' => true,
  125. ];
  126. }
  127. /**
  128. * Action uri of the form.
  129. *
  130. * @param string $action
  131. *
  132. * @return $this
  133. */
  134. public function action($action)
  135. {
  136. return $this->attribute('action', $action);
  137. }
  138. /**
  139. * @return mixed
  140. */
  141. public function getAction()
  142. {
  143. return $this->attributes['action'];
  144. }
  145. /**
  146. * Method of the form.
  147. *
  148. * @param string $method
  149. *
  150. * @return $this
  151. */
  152. public function method($method = 'POST')
  153. {
  154. return $this->attribute('method', strtoupper($method));
  155. }
  156. /**
  157. * Add a fieldset to form.
  158. *
  159. * @param string $title
  160. * @param Closure $setCallback
  161. *
  162. * @return Field\Fieldset
  163. */
  164. public function fieldset(string $title, Closure $setCallback)
  165. {
  166. $fieldset = new Field\Fieldset();
  167. $this->html($fieldset->start($title))->plain();
  168. $setCallback($this);
  169. $this->html($fieldset->end())->plain();
  170. return $fieldset;
  171. }
  172. /**
  173. * Add form attributes.
  174. *
  175. * @param string|array $attr
  176. * @param string $value
  177. *
  178. * @return $this
  179. */
  180. public function attribute($attr, $value = '')
  181. {
  182. if (is_array($attr)) {
  183. foreach ($attr as $key => $value) {
  184. $this->attribute($key, $value);
  185. }
  186. } else {
  187. $this->attributes[$attr] = $value;
  188. }
  189. return $this;
  190. }
  191. /**
  192. * Disable Pjax.
  193. *
  194. * @return $this
  195. */
  196. public function disablePjax()
  197. {
  198. Arr::forget($this->attributes, 'pjax-container');
  199. return $this;
  200. }
  201. /**
  202. * Disable form tag.
  203. *
  204. * @return $this;
  205. */
  206. public function disableFormTag()
  207. {
  208. $this->useFormTag = false;
  209. return $this;
  210. }
  211. /**
  212. * Disable reset button.
  213. *
  214. * @return $this
  215. */
  216. public function disableResetButton()
  217. {
  218. array_delete($this->buttons, 'reset');
  219. return $this;
  220. }
  221. /**
  222. * Disable submit button.
  223. *
  224. * @return $this
  225. */
  226. public function disableSubmitButton()
  227. {
  228. array_delete($this->buttons, 'submit');
  229. return $this;
  230. }
  231. /**
  232. * Set field and label width in current form.
  233. *
  234. * @param int $fieldWidth
  235. * @param int $labelWidth
  236. *
  237. * @return $this
  238. */
  239. public function setWidth($fieldWidth = 8, $labelWidth = 2)
  240. {
  241. collect($this->fields)->each(function ($field) use ($fieldWidth, $labelWidth) {
  242. /* @var Field $field */
  243. $field->setWidth($fieldWidth, $labelWidth);
  244. });
  245. return $this;
  246. }
  247. /**
  248. * Find field class with given name.
  249. *
  250. * @param string $method
  251. *
  252. * @return bool|string
  253. */
  254. public static function findFieldClass($method)
  255. {
  256. $class = Arr::get(\Dcat\Admin\Form::getExtensions(), $method);
  257. if (class_exists($class)) {
  258. return $class;
  259. }
  260. return false;
  261. }
  262. /**
  263. * Add a form field to form.
  264. *
  265. * @param Field $field
  266. *
  267. * @return $this
  268. */
  269. public function pushField(Field &$field)
  270. {
  271. array_push($this->fields, $field);
  272. $field::collectAssets();
  273. return $this;
  274. }
  275. /**
  276. * Get variables for render form.
  277. *
  278. * @return array
  279. */
  280. protected function getVariables()
  281. {
  282. foreach ($this->fields as $field) {
  283. $field->fill($this->data);
  284. }
  285. return [
  286. 'fields' => $this->fields,
  287. 'attributes' => $this->formatAttribute(),
  288. 'method' => $this->attributes['method'],
  289. 'buttons' => $this->buttons,
  290. ];
  291. }
  292. /**
  293. * Format form attributes form array to html.
  294. *
  295. * @param array $attributes
  296. *
  297. * @return string
  298. */
  299. public function formatAttribute($attributes = [])
  300. {
  301. $attributes = $attributes ?: $this->attributes;
  302. if ($this->hasFile()) {
  303. $attributes['enctype'] = 'multipart/form-data';
  304. }
  305. $html = [];
  306. foreach ($attributes as $key => $val) {
  307. $html[] = "$key=\"$val\"";
  308. }
  309. return implode(' ', $html) ?: '';
  310. }
  311. /**
  312. * Determine if form fields has files.
  313. *
  314. * @return bool
  315. */
  316. public function hasFile()
  317. {
  318. foreach ($this->fields as $field) {
  319. if ($field instanceof Field\File) {
  320. return true;
  321. }
  322. }
  323. return false;
  324. }
  325. /**
  326. * @param $id
  327. * @return $this
  328. */
  329. public function setFormId($id)
  330. {
  331. $this->formId = $id;
  332. return $this;
  333. }
  334. /**
  335. * @return string
  336. */
  337. public function getFormId()
  338. {
  339. return $this->formId ?: ($this->formId = 'form-'.Str::random(8));
  340. }
  341. /**
  342. * Generate a Field object and add to form builder if Field exists.
  343. *
  344. * @param string $method
  345. * @param array $arguments
  346. *
  347. * @return Field|null
  348. */
  349. public function __call($method, $arguments)
  350. {
  351. if ($className = static::findFieldClass($method)) {
  352. $name = Arr::get($arguments, 0, '');
  353. $element = new $className($name, array_slice($arguments, 1));
  354. $this->pushField($element);
  355. return $element;
  356. }
  357. }
  358. /**
  359. * Disable submit with ajax.
  360. *
  361. * @param bool $disable
  362. * @return $this
  363. */
  364. public function disableAjaxSubmit(bool $disable = true)
  365. {
  366. $this->useAjaxSubmit = !$disable;
  367. return $this;
  368. }
  369. /**
  370. * @return bool
  371. */
  372. public function allowAjaxSubmit()
  373. {
  374. return $this->useAjaxSubmit === true;
  375. }
  376. protected function setupSubmitScript()
  377. {
  378. Admin::script(
  379. <<<JS
  380. var f = $('#{$this->getFormId()}');
  381. f.find('[type="submit"]').click(function () {
  382. var t = $(this);
  383. t.button('loading');
  384. LA.Form({
  385. \$form: f,
  386. after: function () {
  387. t.button('reset');
  388. }
  389. });
  390. return false;
  391. });
  392. JS
  393. );
  394. }
  395. /**
  396. * Render the form.
  397. *
  398. * @return string
  399. */
  400. public function render()
  401. {
  402. $this->useAjaxSubmit && $this->setupSubmitScript();
  403. return view('admin::widgets.form', $this->getVariables())->render();
  404. }
  405. /**
  406. * Output as string.
  407. *
  408. * @return string
  409. */
  410. public function __toString()
  411. {
  412. return $this->render();
  413. }
  414. }