Form.vue 8.4 KB

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