Form.vue 9.5 KB

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