NestedForm.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. namespace Dcat\Admin\Form;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Form;
  5. use Dcat\Admin\Widgets\Form as WidgetForm;
  6. use Illuminate\Support\Arr;
  7. use Illuminate\Support\Collection;
  8. /**
  9. * Class Form.
  10. *
  11. * @method Field\Text text($column, $label = '')
  12. * @method Field\Checkbox checkbox($column, $label = '')
  13. * @method Field\Radio radio($column, $label = '')
  14. * @method Field\Select select($column, $label = '')
  15. * @method Field\MultipleSelect multipleSelect($column, $label = '')
  16. * @method Field\Textarea textarea($column, $label = '')
  17. * @method Field\Hidden hidden($column, $label = '')
  18. * @method Field\Id id($column, $label = '')
  19. * @method Field\Ip ip($column, $label = '')
  20. * @method Field\Url url($column, $label = '')
  21. * @method Field\Color color($column, $label = '')
  22. * @method Field\Email email($column, $label = '')
  23. * @method Field\Mobile mobile($column, $label = '')
  24. * @method Field\Slider slider($column, $label = '')
  25. * @method Field\Map map($latitude, $longitude, $label = '')
  26. * @method Field\Editor editor($column, $label = '')
  27. * @method Field\Date date($column, $label = '')
  28. * @method Field\Datetime datetime($column, $label = '')
  29. * @method Field\Time time($column, $label = '')
  30. * @method Field\Year year($column, $label = '')
  31. * @method Field\Month month($column, $label = '')
  32. * @method Field\DateRange dateRange($start, $end, $label = '')
  33. * @method Field\DateTimeRange datetimeRange($start, $end, $label = '')
  34. * @method Field\TimeRange timeRange($start, $end, $label = '')
  35. * @method Field\Number number($column, $label = '')
  36. * @method Field\Currency currency($column, $label = '')
  37. * @method Field\SwitchField switch($column, $label = '')
  38. * @method Field\Display display($column, $label = '')
  39. * @method Field\Rate rate($column, $label = '')
  40. * @method Field\Divide divider()
  41. * @method Field\Password password($column, $label = '')
  42. * @method Field\Decimal decimal($column, $label = '')
  43. * @method Field\Html html($html, $label = '')
  44. * @method Field\Tags tags($column, $label = '')
  45. * @method Field\Icon icon($column, $label = '')
  46. * @method Field\Embeds embeds($column, $label = '')
  47. * @method Field\Captcha captcha()
  48. * @method Field\Listbox listbox($column, $label = '')
  49. * @method Field\SelectResource selectResource($column, $label = '')
  50. * @method Field\File file($column, $label = '')
  51. * @method Field\Image image($column, $label = '')
  52. * @method Field\MultipleFile multipleFile($column, $label = '')
  53. * @method Field\MultipleImage multipleImage($column, $label = '')
  54. * @method Field\HasMany hasMany($column, $labelOrCallback, $callback = null)
  55. * @method Field\Tree tree($column, $label = '')
  56. * @method Field\Table table($column, $labelOrCallback, $callback = null)
  57. * @method Field\ListField list($column, $label = '')
  58. * @method Field\Timezone timezone($column, $label = '')
  59. * @method Field\KeyValue keyValue($column, $label = '')
  60. * @method Field\Tel tel($column, $label = '')
  61. * @method Field\BootstrapFile bootstrapFile($column, $label = '')
  62. * @method Field\BootstrapImage bootstrapImage($column, $label = '')
  63. * @method Field\BootstrapMultipleImage bootstrapMultipleImage($column, $label = '')
  64. * @method Field\BootstrapMultipleFile bootstrapMultipleFile($column, $label = '')
  65. */
  66. class NestedForm
  67. {
  68. const DEFAULT_KEY_NAME = '__LA_KEY__';
  69. const REMOVE_FLAG_NAME = '_remove_';
  70. const REMOVE_FLAG_CLASS = 'fom-removed';
  71. /**
  72. * @var string
  73. */
  74. protected $relationName;
  75. /**
  76. * NestedForm key.
  77. *
  78. * @var
  79. */
  80. protected $key;
  81. /**
  82. * Fields in form.
  83. *
  84. * @var Collection
  85. */
  86. protected $fields;
  87. /**
  88. * Original data for this field.
  89. *
  90. * @var array
  91. */
  92. protected $original = [];
  93. /**
  94. * @var Form|WidgetForm
  95. */
  96. protected $form;
  97. /**
  98. * Create a new NestedForm instance.
  99. *
  100. * NestedForm constructor.
  101. *
  102. * @param string $relation
  103. * @param null $key
  104. */
  105. public function __construct($relation, $key = null)
  106. {
  107. $this->relationName = $relation;
  108. $this->key = $key;
  109. $this->fields = new Collection();
  110. }
  111. /**
  112. * Set Form.
  113. *
  114. * @param Form|WidgetForm $form
  115. *
  116. * @return $this
  117. */
  118. public function setForm($form = null)
  119. {
  120. $this->form = $form;
  121. return $this;
  122. }
  123. /**
  124. * Get form.
  125. *
  126. * @return Form
  127. */
  128. public function getForm()
  129. {
  130. return $this->form;
  131. }
  132. /**
  133. * Set original values for fields.
  134. *
  135. * @param array $data
  136. * @param string $relatedKeyName
  137. *
  138. * @return $this
  139. */
  140. public function setOriginal($data, $relatedKeyName)
  141. {
  142. if (empty($data)) {
  143. return $this;
  144. }
  145. foreach ($data as $value) {
  146. if (! isset($value[$relatedKeyName])) {
  147. continue;
  148. }
  149. /*
  150. * like $this->original[30] = [ id = 30, .....]
  151. */
  152. $this->original[$value[$relatedKeyName]] = $value;
  153. }
  154. return $this;
  155. }
  156. /**
  157. * Prepare for insert or update.
  158. *
  159. * @param array $input
  160. *
  161. * @return mixed
  162. */
  163. public function prepare($input)
  164. {
  165. foreach ($input as $key => $record) {
  166. $this->setFieldOriginalValue($key);
  167. $input[$key] = $this->prepareRecord($record);
  168. }
  169. return $input;
  170. }
  171. /**
  172. * Set key for current form.
  173. *
  174. * @param mixed $key
  175. *
  176. * @return $this
  177. */
  178. public function setKey($key)
  179. {
  180. $this->key = $key;
  181. return $this;
  182. }
  183. /**
  184. * Set original data for each field.
  185. *
  186. * @param string $key
  187. *
  188. * @return void
  189. */
  190. protected function setFieldOriginalValue($key)
  191. {
  192. $values = [];
  193. if (array_key_exists($key, $this->original)) {
  194. $values = $this->original[$key];
  195. }
  196. $this->fields->each(function (Field $field) use ($values) {
  197. $field->setOriginal($values);
  198. });
  199. }
  200. /**
  201. * Do prepare work before store and update.
  202. *
  203. * @param array $record
  204. *
  205. * @return array
  206. */
  207. protected function prepareRecord($record)
  208. {
  209. if ($record[static::REMOVE_FLAG_NAME] == 1) {
  210. return $record;
  211. }
  212. $prepared = [];
  213. /* @var Field $field */
  214. foreach ($this->fields as $field) {
  215. $columns = $field->column();
  216. $value = $this->fetchColumnValue($record, $columns);
  217. if (is_null($value)) {
  218. continue;
  219. }
  220. if (method_exists($field, 'prepare')) {
  221. $value = $field->prepare($value);
  222. }
  223. if (($field instanceof \Dcat\Admin\Form\Field\Hidden) || $value != $field->original()) {
  224. if (is_array($columns)) {
  225. foreach ($columns as $name => $column) {
  226. Arr::set($prepared, $column, $value[$name]);
  227. }
  228. } elseif (is_string($columns)) {
  229. Arr::set($prepared, $columns, $value);
  230. }
  231. }
  232. }
  233. $prepared[static::REMOVE_FLAG_NAME] = $record[static::REMOVE_FLAG_NAME];
  234. return $prepared;
  235. }
  236. /**
  237. * Fetch value in input data by column name.
  238. *
  239. * @param array $data
  240. * @param string|array $columns
  241. *
  242. * @return array|mixed
  243. */
  244. protected function fetchColumnValue($data, $columns)
  245. {
  246. if (is_string($columns)) {
  247. return Arr::get($data, $columns);
  248. }
  249. if (is_array($columns)) {
  250. $value = [];
  251. foreach ($columns as $name => $column) {
  252. if (! Arr::has($data, $column)) {
  253. continue;
  254. }
  255. $value[$name] = Arr::get($data, $column);
  256. }
  257. return $value;
  258. }
  259. }
  260. /**
  261. * @param Field $field
  262. *
  263. * @return $this
  264. */
  265. public function pushField(Field $field)
  266. {
  267. $this->fields->push($field);
  268. $field::collectAssets();
  269. return $this;
  270. }
  271. /**
  272. * Get fields of this form.
  273. *
  274. * @return Collection
  275. */
  276. public function fields()
  277. {
  278. return $this->fields;
  279. }
  280. /**
  281. * Fill data to all fields in form.
  282. *
  283. * @param array $data
  284. *
  285. * @return $this
  286. */
  287. public function fill(array $data)
  288. {
  289. /* @var Field $field */
  290. foreach ($this->fields() as $field) {
  291. $field->fill($data);
  292. }
  293. return $this;
  294. }
  295. /**
  296. * Get the html and script of template.
  297. *
  298. * @return array
  299. */
  300. public function getTemplateHtmlAndScript()
  301. {
  302. $html = '';
  303. $scripts = [];
  304. /* @var Field $field */
  305. foreach ($this->fields() as $field) {
  306. //when field render, will push $script to Admin
  307. $html .= $field->render();
  308. /*
  309. * Get and remove the last script of Admin::$script stack.
  310. */
  311. if ($field->getScript()) {
  312. $scripts[] = array_pop(Admin::$script);
  313. }
  314. }
  315. return [$html, implode("\r\n", $scripts)];
  316. }
  317. /**
  318. * Set `errorKey` `elementName` `elementClass` for fields inside hasmany fields.
  319. *
  320. * @param Field $field
  321. *
  322. * @return Field
  323. */
  324. protected function formatField(Field $field)
  325. {
  326. $column = $field->column();
  327. $elementName = $elementClass = $errorKey = [];
  328. $key = $this->key ?: 'new_'.static::DEFAULT_KEY_NAME;
  329. if (is_array($column)) {
  330. foreach ($column as $k => $name) {
  331. $errorKey[$k] = sprintf('%s.%s.%s', $this->relationName, $key, $name);
  332. $elementName[$k] = sprintf('%s[%s][%s]', $this->relationName, $key, $name);
  333. $elementClass[$k] = [$this->relationName, $name];
  334. }
  335. } else {
  336. $errorKey = sprintf('%s.%s.%s', $this->relationName, $key, $column);
  337. $elementName = sprintf('%s[%s][%s]', $this->relationName, $key, $column);
  338. $elementClass = [$this->relationName, $column];
  339. }
  340. return $field->setErrorKey($errorKey)
  341. ->setElementName($elementName)
  342. ->setElementClass($elementClass);
  343. }
  344. /**
  345. * Add nested-form fields dynamically.
  346. *
  347. * @param string $method
  348. * @param array $arguments
  349. *
  350. * @return mixed
  351. */
  352. public function __call($method, $arguments)
  353. {
  354. if ($className = Form::findFieldClass($method)) {
  355. $column = Arr::get($arguments, 0, '');
  356. /* @var Field $field */
  357. $field = new $className($column, array_slice($arguments, 1));
  358. $field->setForm($this->form);
  359. $field = $this->formatField($field);
  360. $this->pushField($field);
  361. return $field;
  362. }
  363. return $this;
  364. }
  365. }