Skip to content

Instantly share code, notes, and snippets.

@tuanna-hsp
Last active September 30, 2021 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuanna-hsp/fce7190709d5e4d605992e2363568a8b to your computer and use it in GitHub Desktop.
Save tuanna-hsp/fce7190709d5e4d605992e2363568a8b to your computer and use it in GitHub Desktop.
<template>
<div>
<form ref="form" class="mt-4" autocomplete="off" @submit.stop.prevent="handleSubmit">
<div v-for="attr in allAttributes" :key="attr">
<form-input-integration
v-model="$v.form[attr].$model"
:attribute-name="attr"
:state="validateForm(attr)"
/>
</div>
<div class="text-center">
<base-button type="primary" :disabled="disableSubmit" @click="handleSubmit()">
{{ $t("buttons.integrate") }}
</base-button>
</div>
</form>
</div>
</template>
<script lang="ts">
import Vue, { PropType } from "vue";
import { requiredIf } from "vuelidate/lib/validators";
export default Vue.extend({
props: {
saas: {
type: Object as PropType<SaaS>,
required: true,
},
},
data() {
return {
form: {} as CredentialForm,
};
},
computed: {
disableSubmit(): boolean {
return this.$v.$invalid;
},
allAttributes(): string[] {
return [...this.requiredFields, ...this.optionalFields];
},
requiredFields(): string[] {
this.saas.requiredAttributes;
},
optionalFields(): string[] {
this.saas.optionalAttributes;
},
},
watch: {
saas: {
immediate: true,
handler(value): void {
if (value) {
// Clear current attr values
this.clearFormAttributes();
// Initialize form attributes for new service, note that we must use $set to preserve Vue reactiviy on `form` object
// (which is required for Vuelidate to work correctly)
this.allAttributes.forEach(attr => this.$set(this.form, attr, ""));
}
},
},
},
validations() {
const form: { [rule: string]: any } = {};
this.allAttributes.forEach(attr => {
form[attr] = {
required: requiredIf(function(this: any): boolean {
return this.isAttributeRequired(attr);
}),
};
});
return { form };
},
methods: {
validateForm(name: string): boolean | null {
const formAttribute = this.$v.form[name];
return formAttribute?.$dirty ? !formAttribute.$error : null;
},
clearFormAttributes(): void {
for (const key in this.form) {
// Making sure we dont leave any `null` attributes when the `service` object changed via prop
this.form[key] = undefined;
}
},
isAttributeRequired(attr: string): boolean {
return this.requiredFields?.includes(attr);
},
handleSubmit(): void {
if (this.$v.$invalid) {
return;
}
this.$emit("onSubmit",this.form);
},
},
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment