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