Form.vue 8.6 KB

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