Form.vue 9.0 KB

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