Form.vue 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <!--
  2. Formulaire générique
  3. Assure la validation des données, les actions de base (enregistrement, annulation, ...), et la confirmation avant
  4. de quitter si des données ont été modifiées.
  5. @see https://vuetifyjs.com/en/components/forms/#usage
  6. -->
  7. <template>
  8. <LayoutContainer>
  9. <v-form
  10. v-model="isValid"
  11. ref="form"
  12. :readonly="readonly"
  13. @submit.prevent=""
  14. >
  15. <!-- Top action bar -->
  16. <v-container
  17. v-if="actionPosition === 'both' || actionPosition === 'top'"
  18. :fluid="true"
  19. class="container btnActions"
  20. >
  21. <v-row>
  22. <v-col cols="12" sm="12">
  23. <slot name="form.button" />
  24. <UiButtonSubmit
  25. v-if="!readonly"
  26. @submit="submit"
  27. :actions="actions"
  28. :validation-pending="validationPending || !isValid"
  29. ></UiButtonSubmit>
  30. </v-col>
  31. </v-row>
  32. </v-container>
  33. <!-- Content -->
  34. <slot v-bind="{ model, entity }" />
  35. <!-- Bottom action bar -->
  36. <v-container
  37. v-if="actionPosition === 'both' || actionPosition === 'bottom'"
  38. :fluid="true"
  39. class="container btnActions mt-6"
  40. >
  41. <v-row>
  42. <v-col cols="12" sm="12">
  43. <slot name="form.button" />
  44. <UiButtonSubmit
  45. @submit="submit"
  46. :actions="actions"
  47. :validation-pending="validationPending || !isValid"
  48. ></UiButtonSubmit>
  49. </v-col>
  50. </v-row>
  51. </v-container>
  52. </v-form>
  53. <!-- Confirmation dialog -->
  54. <LazyLayoutDialog :show="isConfirmationDialogShowing">
  55. <template #dialogText>
  56. <v-card-title class="text-h5 theme-neutral">
  57. {{ $t('caution') }}
  58. </v-card-title>
  59. <v-card-text>
  60. <br />
  61. <p>{{ $t('quit_without_saving_warning') }}</p>
  62. </v-card-text>
  63. </template>
  64. <template #dialogBtn>
  65. <v-btn
  66. class="mr-4 submitBtn theme-primary"
  67. @click="closeConfirmationDialog"
  68. >
  69. {{ $t('back_to_form') }}
  70. </v-btn>
  71. <v-btn class="mr-4 submitBtn theme-primary" @click="saveAndQuit">
  72. {{ $t('save_and_quit') }}
  73. </v-btn>
  74. <v-btn class="mr-4 submitBtn theme-danger" @click="cancel">
  75. {{ $t('quit_form') }}
  76. </v-btn>
  77. </template>
  78. </LazyLayoutDialog>
  79. </LayoutContainer>
  80. </template>
  81. <script setup lang="ts">
  82. import { computed, ref } from '@vue/reactivity'
  83. import type { ComputedRef, Ref } from '@vue/reactivity'
  84. import { FORM_FUNCTION, SUBMIT_TYPE, TYPE_ALERT } from '~/types/enum/enums'
  85. import { useFormStore } from '~/stores/form'
  86. import type { Route, RouteLocationRaw } from '@intlify/vue-router-bridge'
  87. import { useEntityManager } from '~/composables/data/useEntityManager'
  88. import ApiModel from '~/models/ApiModel'
  89. import { usePageStore } from '~/stores/page'
  90. import { watch } from '@vue/runtime-core'
  91. import type { PropType } from '@vue/runtime-core'
  92. import type { AnyJson } from '~/types/data'
  93. import * as _ from 'lodash-es'
  94. import { useRefreshProfile } from '~/composables/data/useRefreshProfile'
  95. const props = defineProps({
  96. /**
  97. * Classe de l'ApiModel (ex: Organization, Notification, ...)
  98. */
  99. model: {
  100. type: Function as any as () => typeof ApiModel,
  101. required: true,
  102. },
  103. /**
  104. * Instance de l'objet
  105. */
  106. entity: {
  107. type: Object as () => ApiModel,
  108. required: true,
  109. },
  110. /**
  111. * TODO: compléter
  112. */
  113. onChanged: {
  114. type: Function,
  115. required: false,
  116. },
  117. goBackRoute: {
  118. type: Object as PropType<RouteLocationRaw>,
  119. required: false,
  120. default: null,
  121. },
  122. /**
  123. * Types de soumission disponibles (enregistrer / enregistrer et quitter)
  124. */
  125. submitActions: {
  126. type: Object,
  127. required: false,
  128. default: () => {
  129. let actions: AnyJson = {}
  130. actions[SUBMIT_TYPE.SAVE] = {}
  131. return actions
  132. },
  133. },
  134. /**
  135. * La validation est en cours
  136. */
  137. validationPending: {
  138. type: Boolean,
  139. required: false,
  140. default: false,
  141. },
  142. /**
  143. * Faut-il rafraichir le profil à la soumission du formulaire?
  144. */
  145. refreshProfile: {
  146. type: Boolean,
  147. required: false,
  148. default: false,
  149. },
  150. actionPosition: {
  151. type: String as PropType<'top' | 'bottom' | 'both'>,
  152. required: false,
  153. default: 'both',
  154. },
  155. })
  156. // ### Définitions
  157. const i18n = useI18n()
  158. const router = useRouter()
  159. const { em } = useEntityManager()
  160. const { refreshProfile } = useRefreshProfile()
  161. // Le formulaire est-il valide
  162. const isValid: Ref<boolean> = ref(true)
  163. // Erreurs de validation
  164. const errors: Ref<Array<string>> = ref([])
  165. // Référence au component v-form
  166. const form: Ref = ref(null)
  167. // Le formulaire est-il en lecture seule
  168. const readonly: ComputedRef<boolean> = computed(() => {
  169. return useFormStore().readonly
  170. })
  171. // La fenêtre de confirmation est-elle affichée
  172. const isConfirmationDialogShowing: ComputedRef<boolean> = computed(() => {
  173. return useFormStore().showConfirmToLeave
  174. })
  175. /**
  176. * Ferme la fenêtre de confirmation
  177. */
  178. const closeConfirmationDialog = () => {
  179. useFormStore().setShowConfirmToLeave(false)
  180. }
  181. // ### Actions du formulaire
  182. /**
  183. * Soumet le formulaire
  184. *
  185. * @param next
  186. */
  187. const submit = async (next: string | null = null) => {
  188. if (props.validationPending) {
  189. return
  190. }
  191. // Valide les données
  192. await validate()
  193. if (!isValid.value) {
  194. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  195. return
  196. }
  197. try {
  198. usePageStore().loading = true
  199. // TODO: est-ce qu'il faut re-fetch l'entité après le persist?
  200. const updatedEntity = await em.persist(props.model, props.entity)
  201. if (props.refreshProfile) {
  202. await refreshProfile()
  203. }
  204. usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['saveSuccess'])
  205. // On retire l'état 'dirty'
  206. setIsDirty(false)
  207. const actionArgs = next ? props.submitActions[next] : null
  208. if (next === SUBMIT_TYPE.SAVE) {
  209. onSaveAction(actionArgs, updatedEntity.id)
  210. } else if (next === SUBMIT_TYPE.SAVE_AND_BACK) {
  211. onSaveAndQuitAction(actionArgs)
  212. }
  213. } catch (error: any) {
  214. if (
  215. error.response &&
  216. error.response.status === 422 &&
  217. error.response.data['violations']
  218. ) {
  219. // TODO: à revoir
  220. const violations: Array<string> = []
  221. let fields: AnyJson = {}
  222. for (const violation of error.response.data['violations']) {
  223. violations.push(i18n.t(violation['message']) as string)
  224. fields = Object.assign(fields, {
  225. [violation['propertyPath']]: violation['message'],
  226. })
  227. }
  228. useFormStore().addViolation(fields)
  229. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  230. } else {
  231. throw error
  232. }
  233. } finally {
  234. usePageStore().loading = false
  235. }
  236. }
  237. /**
  238. * Enregistre et quitte
  239. */
  240. const saveAndQuit = async () => {
  241. await submit()
  242. cancel()
  243. }
  244. /**
  245. * Après l'action Sauvegarder
  246. *
  247. * Si on était en mode édition, on reste sur cette page (on ne fait rien).
  248. * Si on était en mode création, on bascule sur le mode édition
  249. *
  250. * @param route
  251. * @param id
  252. */
  253. function onSaveAction(route: Route, id: number) {
  254. if (useFormStore().formFunction === FORM_FUNCTION.CREATE) {
  255. route.path += id
  256. navigateTo(route)
  257. }
  258. }
  259. /**
  260. * Après l'action Sauvegarder et Quitter
  261. *
  262. * On redirige vers la route donnée
  263. *
  264. * @param route
  265. */
  266. function onSaveAndQuitAction(route: Route) {
  267. navigateTo(route)
  268. }
  269. /**
  270. * Quitte le formulaire sans enregistrer
  271. */
  272. const cancel = () => {
  273. setIsDirty(false)
  274. useFormStore().setShowConfirmToLeave(false)
  275. em.reset(props.model, props.entity.value)
  276. if (router) {
  277. // @ts-ignore
  278. router.push(useFormStore().goAfterLeave) // TODO: voir si on peut pas passer ça comme prop du component
  279. }
  280. }
  281. const actions = computed(() => {
  282. return _.keys(props.submitActions)
  283. })
  284. // #### Validation et store
  285. /**
  286. * Update store when form is changed (if valid)
  287. */
  288. const onFormChange = async () => {
  289. if (isValid.value) {
  290. em.save(props.model, props.entity)
  291. setIsDirty(true)
  292. if (props.onChanged) {
  293. // Execute the custom onChange method, if defined
  294. // TODO: voir quelles variables passer à cette méthode custom ; d'ailleurs, vérifier aussi si cette méthode est utilisée
  295. props.onChanged()
  296. }
  297. }
  298. }
  299. /**
  300. * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
  301. *
  302. * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
  303. */
  304. const validate = async function () {
  305. const validation = await form.value.validate()
  306. isValid.value = validation.valid
  307. errors.value = validation.errors
  308. }
  309. // #### Gestion de l'état dirty
  310. watch(props.entity, async (newEntity, oldEntity) => {
  311. setIsDirty(true)
  312. })
  313. /**
  314. * Handle events if the form is dirty to prevent submission
  315. * @param e
  316. */
  317. // TODO: voir si encore nécessaire avec le @submit.prevent
  318. const preventSubmit = (e: any) => {
  319. // Cancel the event
  320. e.preventDefault()
  321. // Chrome requires returnValue to be set
  322. e.returnValue = ''
  323. }
  324. /**
  325. * Applique ou retire l'état dirty (modifié) du formulaire
  326. */
  327. const setIsDirty = (dirty: boolean) => {
  328. useFormStore().setDirty(dirty)
  329. }
  330. defineExpose({ validate })
  331. </script>
  332. <style scoped>
  333. .btnActions {
  334. text-align: right;
  335. }
  336. </style>