Form.vue 8.7 KB

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