NestedForm.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. namespace Dcat\Admin\Form;
  3. use Dcat\Admin\Form;
  4. use Dcat\Admin\Support\Helper;
  5. use Dcat\Admin\Widgets\Form as WidgetForm;
  6. use Illuminate\Support\Arr;
  7. use Illuminate\Support\Collection;
  8. class NestedForm extends WidgetForm
  9. {
  10. const DEFAULT_KEY_NAME = '__LA_KEY__';
  11. const REMOVE_FLAG_NAME = '_remove_';
  12. const REMOVE_FLAG_CLASS = 'form-removed';
  13. /**
  14. * @var string
  15. */
  16. protected $relationName;
  17. /**
  18. * NestedForm key.
  19. *
  20. * @var
  21. */
  22. protected $key;
  23. /**
  24. * Fields in form.
  25. *
  26. * @var Collection
  27. */
  28. protected $fields;
  29. /**
  30. * Original data for this field.
  31. *
  32. * @var array
  33. */
  34. protected $original = [];
  35. /**
  36. * @var Form|WidgetForm
  37. */
  38. protected $form;
  39. /**
  40. * Create a new NestedForm instance.
  41. *
  42. * NestedForm constructor.
  43. *
  44. * @param string $relation
  45. * @param null $key
  46. */
  47. public function __construct($relation = null, $key = null)
  48. {
  49. parent::__construct();
  50. $this->relationName = $relation;
  51. $this->key = $key;
  52. $this->resetButton(false);
  53. $this->submitButton(false);
  54. $this->ajax(false);
  55. $this->useFormTag(false);
  56. }
  57. /**
  58. * Set Form.
  59. *
  60. * @param Form|WidgetForm $form
  61. *
  62. * @return $this
  63. */
  64. public function setForm($form = null)
  65. {
  66. $this->form = $form;
  67. return $this;
  68. }
  69. /**
  70. * Get form.
  71. *
  72. * @return Form
  73. */
  74. public function form()
  75. {
  76. return $this->form;
  77. }
  78. public function model()
  79. {
  80. return $this->form->model();
  81. }
  82. /**
  83. * Set original values for fields.
  84. *
  85. * @param array $data
  86. * @param string $relatedKeyName
  87. *
  88. * @return $this
  89. */
  90. public function setOriginal($data, $relatedKeyName)
  91. {
  92. if (empty($data)) {
  93. return $this;
  94. }
  95. foreach ($data as $value) {
  96. if (! isset($value[$relatedKeyName])) {
  97. continue;
  98. }
  99. /*
  100. * like $this->original[30] = [ id = 30, .....]
  101. */
  102. $this->original[$value[$relatedKeyName]] = $value;
  103. }
  104. return $this;
  105. }
  106. /**
  107. * Prepare for insert or update.
  108. *
  109. * @param array $input
  110. *
  111. * @return mixed
  112. */
  113. public function prepare($input)
  114. {
  115. foreach ($input as $key => $record) {
  116. if (! array_key_exists(static::REMOVE_FLAG_NAME, $record)) {
  117. continue;
  118. }
  119. $this->setFieldOriginalValue($key);
  120. $input[$key] = $this->prepareRecord($record);
  121. }
  122. return $input;
  123. }
  124. /**
  125. * Get key for current form.
  126. *
  127. * @return string
  128. */
  129. public function getKey()
  130. {
  131. return $this->key;
  132. }
  133. /**
  134. * Set key for current form.
  135. *
  136. * @param mixed $key
  137. *
  138. * @return $this
  139. */
  140. public function setKey($key)
  141. {
  142. $this->key = $key;
  143. return $this;
  144. }
  145. /**
  146. * Set original data for each field.
  147. *
  148. * @param string $key
  149. *
  150. * @return void
  151. */
  152. protected function setFieldOriginalValue($key)
  153. {
  154. $values = [];
  155. if (array_key_exists($key, $this->original)) {
  156. $values = $this->original[$key];
  157. }
  158. $this->fields->each(function (Field $field) use ($values) {
  159. $field->setOriginal($values);
  160. });
  161. }
  162. /**
  163. * Do prepare work before store and update.
  164. *
  165. * @param array $record
  166. *
  167. * @return array
  168. */
  169. protected function prepareRecord($record)
  170. {
  171. if ($record[static::REMOVE_FLAG_NAME] == 1) {
  172. return $record;
  173. }
  174. $prepared = [];
  175. /* @var Field $field */
  176. foreach ($this->fields as $field) {
  177. $columns = $field->column();
  178. $value = $this->fetchColumnValue($record, $columns);
  179. if ($value === false) {
  180. continue;
  181. }
  182. if (method_exists($field, 'prepare')) {
  183. $value = $field->prepare($value);
  184. }
  185. if (($field instanceof Form\Field\Hidden) || ! Helper::equal($field->original(), $value)) {
  186. if (is_array($columns)) {
  187. foreach ($columns as $name => $column) {
  188. Arr::set($prepared, $column, $value[$name]);
  189. }
  190. } elseif (is_string($columns)) {
  191. Arr::set($prepared, $columns, $value);
  192. }
  193. }
  194. }
  195. $prepared[static::REMOVE_FLAG_NAME] = $record[static::REMOVE_FLAG_NAME];
  196. return $prepared;
  197. }
  198. /**
  199. * Fetch value in input data by column name.
  200. *
  201. * @param array $data
  202. * @param string|array $columns
  203. *
  204. * @return array|mixed
  205. */
  206. protected function fetchColumnValue($data, $columns)
  207. {
  208. if (is_string($columns)) {
  209. if (! Arr::has($data, $columns)) {
  210. return false;
  211. }
  212. return Arr::get($data, $columns);
  213. }
  214. if (is_array($columns)) {
  215. $value = [];
  216. foreach ($columns as $name => $column) {
  217. if (! Arr::has($data, $column)) {
  218. continue;
  219. }
  220. $value[$name] = Arr::get($data, $column);
  221. }
  222. return $value;
  223. }
  224. return false;
  225. }
  226. /**
  227. * {@inheritDoc}
  228. */
  229. public function pushField(Field $field)
  230. {
  231. $this->fields->push($field);
  232. $field->setForm($this->form);
  233. $field->setParent($this);
  234. if ($this->layout()->hasColumns()) {
  235. $this->layout()->addField($field);
  236. }
  237. $field->attribute(Field::BUILD_IGNORE, true);
  238. if (method_exists($this->form, 'builder')) {
  239. $this->form->builder()->pushField((clone $field)->display(false));
  240. }
  241. $field->setRelation([
  242. 'relation' => $this->relationName,
  243. 'key' => $this->key,
  244. ]);
  245. $field::requireAssets();
  246. $field->width($this->width['field'], $this->width['label']);
  247. return $this;
  248. }
  249. protected function resolveField($method, $arguments)
  250. {
  251. if ($className = Form::findFieldClass($method)) {
  252. $column = Arr::get($arguments, 0, '');
  253. /* @var Field $field */
  254. $field = new $className($column, array_slice($arguments, 1));
  255. return $this->formatField($field);
  256. }
  257. }
  258. /**
  259. * Get fields of this form.
  260. *
  261. * @return Collection
  262. */
  263. public function fields()
  264. {
  265. return $this->fields;
  266. }
  267. /**
  268. * Fill data to all fields in form.
  269. *
  270. * @param array $data
  271. *
  272. * @return $this
  273. */
  274. public function fill($data)
  275. {
  276. /* @var Field $field */
  277. foreach ($this->fields() as $field) {
  278. $field->fill($data);
  279. }
  280. return $this;
  281. }
  282. /**
  283. * Set `errorKey` `elementName` `elementClass` for fields inside hasmany fields.
  284. *
  285. * @param Field $field
  286. *
  287. * @return Field
  288. */
  289. protected function formatField(Field $field)
  290. {
  291. $column = $field->column();
  292. $elementName = $elementClass = $errorKey = [];
  293. $key = $this->key ?: 'new_'.static::DEFAULT_KEY_NAME;
  294. if (is_array($column)) {
  295. foreach ($column as $k => $name) {
  296. $errorKey[$k] = sprintf('%s.%s.%s', $this->relationName, $key, $name);
  297. $elementName[$k] = sprintf('%s[%s][%s]', $this->formatName(), $key, $name);
  298. $elementClass[$k] = [$this->formatClass(), $this->formatClass($name), $this->formatClass($name, false)];
  299. }
  300. } else {
  301. $errorKey = sprintf('%s.%s.%s', $this->relationName, $key, $column);
  302. $elementName = sprintf('%s[%s][%s]', $this->formatName(), $key, $column);
  303. $elementClass = [$this->formatClass(), $this->formatClass($column), $this->formatClass($column, false)];
  304. }
  305. return $field->setErrorKey($errorKey)
  306. ->setElementName($elementName)
  307. ->setElementClass($elementClass);
  308. }
  309. protected function formatClass($name = null, bool $append = true)
  310. {
  311. $class = str_replace('.', '_', $name ?: $this->relationName);
  312. return $append ? ($class.'_'.$this->key) : $class;
  313. }
  314. protected function formatName($name = null)
  315. {
  316. return Helper::formatElementName($name ?: $this->relationName);
  317. }
  318. /**
  319. * Add nested-form fields dynamically.
  320. *
  321. * @param string $method
  322. * @param array $arguments
  323. *
  324. * @return mixed
  325. */
  326. public function __call($method, $arguments)
  327. {
  328. if ($field = $this->resolveField($method, $arguments)) {
  329. $this->pushField($field);
  330. return $field;
  331. }
  332. return $this;
  333. }
  334. }