Form.vue 9.2 KB

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