Form.vue 9.0 KB

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