Form.vue 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. import {useRefreshProfile} from "~/composables/data/useRefreshProfile";
  86. const props = defineProps({
  87. /**
  88. * Classe de l'ApiModel (ex: Organization, Notification, ...)
  89. */
  90. model: {
  91. type: Function as any as () => typeof ApiModel,
  92. required: true
  93. },
  94. /**
  95. * Instance de l'objet
  96. */
  97. entity: {
  98. type: Object as () => ApiModel,
  99. required: true
  100. },
  101. /**
  102. * TODO: compléter
  103. */
  104. onChanged: {
  105. type: Function,
  106. required: false
  107. },
  108. /**
  109. * Types de soumission disponibles (enregistrer / enregistrer et quitter)
  110. */
  111. submitActions: {
  112. type: Object,
  113. required: false,
  114. default: () => {
  115. let actions: AnyJson = {}
  116. actions[SUBMIT_TYPE.SAVE] = {}
  117. return actions
  118. }
  119. },
  120. /**
  121. * La validation est en cours
  122. */
  123. validationPending: {
  124. type: Boolean,
  125. required: false,
  126. default: false
  127. },
  128. /**
  129. * Faut-il rafraichir le profil à la soumission du formulaire?
  130. */
  131. refreshProfile: {
  132. type: Boolean,
  133. required: false,
  134. default: false
  135. }
  136. })
  137. // ### Définitions
  138. const i18n = useI18n()
  139. const router = useRouter()
  140. const { em } = useEntityManager()
  141. const { refreshProfile } = useRefreshProfile()
  142. // Le formulaire est-il valide
  143. const isValid: Ref<boolean> = ref(true)
  144. // Erreurs de validation
  145. const errors: Ref<Array<string>> = ref([])
  146. // Référence au component v-form
  147. const form: Ref = ref(null)
  148. // Le formulaire est-il en lecture seule
  149. const readonly: ComputedRef<boolean> = computed(() => {
  150. return useFormStore().readonly
  151. })
  152. // La fenêtre de confirmation est-elle affichée
  153. const isConfirmationDialogShowing: ComputedRef<boolean> = computed(() => {
  154. return useFormStore().showConfirmToLeave
  155. })
  156. /**
  157. * Ferme la fenêtre de confirmation
  158. */
  159. const closeConfirmationDialog = () => {
  160. useFormStore().setShowConfirmToLeave(false)
  161. }
  162. // ### Actions du formulaire
  163. /**
  164. * Soumet le formulaire
  165. *
  166. * @param next
  167. */
  168. const submit = async (next: string|null = null) => {
  169. if (props.validationPending) {
  170. return
  171. }
  172. // Valide les données
  173. await validate()
  174. if (!isValid.value) {
  175. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  176. return
  177. }
  178. try {
  179. // TODO: est-ce qu'il faut re-fetch l'entité après le persist?
  180. const updatedEntity = await em.persist(props.model, props.entity)
  181. if (props.refreshProfile) {
  182. await refreshProfile()
  183. }
  184. usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['saveSuccess'])
  185. // On retire l'état 'dirty'
  186. setIsDirty(false)
  187. afterSubmissionAction(next, updatedEntity)
  188. } catch (error: any) {
  189. if (error.response.status === 422 && error.response.data['violations']) {
  190. // TODO: à revoir
  191. const violations: Array<string> = []
  192. let fields: AnyJson = {}
  193. for (const violation of error.response.data['violations']) {
  194. violations.push(i18n.t(violation['message']) as string)
  195. fields = Object.assign(fields, {[violation['propertyPath']] : violation['message']})
  196. }
  197. useFormStore().addViolation(fields)
  198. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  199. }
  200. }
  201. }
  202. /**
  203. * Enregistre et quitte
  204. */
  205. const saveAndQuit = async () => {
  206. await submit()
  207. quitForm()
  208. }
  209. /**
  210. * Retourne l'action à effectuer après la soumission du formulaire
  211. * @param action
  212. * @param updatedEntity
  213. */
  214. const afterSubmissionAction = (action: string | null, updatedEntity: AnyJson) => {
  215. if (action === null) {
  216. return
  217. }
  218. const actionArgs = props.submitActions[action]
  219. if (action === SUBMIT_TYPE.SAVE) {
  220. afterSaveAction(actionArgs, updatedEntity.id, router)
  221. } else if (action === SUBMIT_TYPE.SAVE_AND_BACK) {
  222. afterSaveAndQuitAction(actionArgs, router)
  223. }
  224. }
  225. /**
  226. * Après l'action Sauvegarder
  227. *
  228. * Si on était en mode édition, on reste sur cette page (on ne fait rien).
  229. * Si on était en mode création, on bascule sur le mode édition
  230. *
  231. * @param route
  232. * @param id
  233. * @param router
  234. */
  235. function afterSaveAction(route: Route, id: number, router: any){
  236. if (useFormStore().formFunction === FORM_FUNCTION.CREATE) {
  237. route.path += id
  238. router.push(route)
  239. }
  240. }
  241. /**
  242. * Après l'action Sauvegarder et Quitter
  243. *
  244. * On redirige vers la route donnée
  245. *
  246. * @param route
  247. * @param router
  248. */
  249. function afterSaveAndQuitAction(route: Route, router: any){
  250. router.push(route)
  251. }
  252. /**
  253. * Quitte le formulaire sans enregistrer
  254. */
  255. const quitForm = () => {
  256. setIsDirty(false)
  257. useFormStore().setShowConfirmToLeave(false)
  258. em.reset(props.model, props.entity.value)
  259. if (router) {
  260. // @ts-ignore
  261. router.push(useFormStore().goAfterLeave) // TODO: voir si on peut pas passer ça comme prop du component
  262. }
  263. }
  264. const actions = computed(()=>{
  265. return _.keys(props.submitActions)
  266. })
  267. // #### Validation et store
  268. /**
  269. * Update store when form is changed (if valid)
  270. */
  271. const onFormChange = async () => {
  272. await validate()
  273. if (isValid.value) {
  274. em.save(props.model, props.entity)
  275. setIsDirty(true)
  276. if (props.onChanged) {
  277. // Execute the custom onChange method, if defined
  278. // TODO: voir quelles variables passer à cette méthode custom ; d'ailleurs, vérifier aussi si cette méthode est utilisée
  279. props.onChanged()
  280. }
  281. }
  282. }
  283. /**
  284. * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
  285. *
  286. * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
  287. */
  288. const validate = async function () {
  289. const validation = await form.value.validate()
  290. isValid.value = validation.valid
  291. errors.value = validation.errors
  292. }
  293. // #### Gestion de l'état dirty
  294. watch(props.entity, async (newEntity, oldEntity) => {
  295. await onFormChange()
  296. })
  297. /**
  298. * Handle events if the form is dirty to prevent submission
  299. * @param e
  300. */
  301. // TODO: voir si encore nécessaire avec le @submit.prevent
  302. const preventSubmit = (e: any) => {
  303. // Cancel the event
  304. e.preventDefault()
  305. // Chrome requires returnValue to be set
  306. e.returnValue = ''
  307. }
  308. /**
  309. * Applique ou retire l'état dirty (modifié) du formulaire
  310. */
  311. const setIsDirty = (dirty: boolean) => {
  312. useFormStore().setDirty(dirty)
  313. // If dirty, add the preventSubmit event listener
  314. // TODO: voir si encore nécessaire avec le @submit.prevent
  315. if (process.browser) {
  316. if (dirty) {
  317. window.addEventListener('beforeunload', preventSubmit)
  318. } else {
  319. window.removeEventListener('beforeunload', preventSubmit)
  320. }
  321. }
  322. }
  323. defineExpose({ validate })
  324. </script>
  325. <style scoped>
  326. .btnActions {
  327. text-align: right;
  328. }
  329. </style>