Your Vue component for managing employment history is well-structured and leverages the Composition API effectively. However, there are a few areas that might be causing unexpected behavior, especially concerning the handling of country, city, and governorate selections. Let's walk through these potential issues and provide solutions to enhance your component's functionality.
1. Shared State for Selections
Issue:
Currently, you have selectedCountry and selectedCity as global refs. This means that all employment history entries share the same selected country and city. As a result, changing the country in one employment entry will affect all others, which is likely not the intended behavior.
Solution:
Instead of having a single selectedCountry and selectedCity, manage these selections individually for each employment entry. You can achieve this by storing the selected values within each employment object in employment_history.
2. Incorrect Event Handling
Issue:
- In your
Autocomp components for country and city, you're passing the index to the handleCountryChange and handleCityChange methods. However, these methods are designed to handle value changes, not indices.
- Additionally, for the city
Autocomp, you have @update:modelValue="handleCountryChange", which seems like a copy-paste error and should likely be handleCityChange.
Solution:
Update the event bindings to pass the actual selected value along with the index, ensuring that each employment entry manages its own selection state.
3. Dynamic Options Based on Selection
Issue:
The optionCity and optionGovernorate computed properties rely on selectedCountry and selectedCity respectively. With the current global state, they won’t correctly reflect the selections for individual employment entries.
Solution:
Move the logic for filtering cities and governorates inside each employment entry, using computed properties or methods that accept the selected country and city as parameters.
Revised Code Implementation
Below is the revised version of your component addressing the issues mentioned:
<template>
<div class="pt-3 container">
<h3 class="text-lg font-medium mb-3 text-black">Employment History</h3>
</div>
<div class="space-y-2">
<!-- Iterate Over Employment History -->
<FieldsToggleContainer
v-for="(employment, index) in request.doc.employment_history"
:key="employment.id"
:title="employment.company || `Employment ${index + 1}`"
>
<div class="lg:grid grid-cols-2 lg:gap-2">
<!-- Company Field -->
<FieldContainer>
<StyledInput
labelText="Company"
:isMandatory="true"
infoText="Company"
inputType="text"
name="company"
:id="`company-${employment.id}`"
v-model="employment.company"
:isValid="false"
validationMessage="You can edit the message."
/>
</FieldContainer>
<!-- Country Autocomplete -->
<FieldContainer>
<Autocomp
labelText="Country"
:isMandatory="true"
infoText="Country"
inputType="text"
name="country"
:id="`country-${employment.id}`"
:options="optionCountry"
v-model="employment.country"
@input-change="(value) => handleCountryChange(index, value)"
:isValid="false"
validationMessage="You can edit the message."
/>
</FieldContainer>
<!-- City Autocomplete -->
<FieldContainer>
<Autocomp
labelText="City"
:isMandatory="true"
infoText="City"
inputType="text"
name="city"
:id="`city-${employment.id}`"
:options="getOptionCity(employment)"
v-model="employment.city"
@input-change="(value) => handleCityChange(index, value)"
:isValid="false"
validationMessage="You can edit the message."
/>
</FieldContainer>
<!-- Governorate Autocomplete -->
<FieldContainer>
<Autocomp
labelText="Governorate"
:isMandatory="true"
infoText="Governorate"
inputType="text"
name="governorate"
:id="`governorate-${employment.id}`"
:options="getOptionGovernorate(employment)"
v-model="employment.governorate"
:isValid="false"
validationMessage="You can edit the message."
/>
</FieldContainer>
</div>
<!-- Save Employment Button -->
<div class="flex justify-end py-2">
<Button level="danger" @clicked="saveRequest">Save</Button>
</div>
</FieldsToggleContainer>
<!-- Add Employment Button -->
<div class="flex justify-center py-3">
<Button level="secondary" @clicked="addEmployment">+ Add Employment History</Button>
</div>
</div>
</template>
<script setup>
import { ref, computed, watch, reactive, nextTick } from 'vue'
import { createDocumentResource } from 'frappe-ui'
import { useToast } from 'vue-toastification'
import { v4 as uuidv4 } from 'uuid'
// Components
import Button from '../../components/button.vue'
import FieldContainer from '../../components/fieldContainer.vue'
import FieldsToggleContainer from '../../components/fieldsToggleContainer.vue'
import StyledInput from '../../components/styledInput.vue'
import Autocomp from '../../components/autocomp.vue'
import { location } from '../../data/useAddressLogic'
// Initialize Toast
const toast = useToast()
// Document Resource
const request = createDocumentResource({
doctype: 'Verification Instructions Request',
name: 'VIR-2024-26-09-000007',
})
// Options for Countries
const optionCountry = computed(() => {
return location.data
.filter(loc => loc.location_type === 'Country')
.map(loc => ({
label: loc.location_name,
value: loc.location_name
}))
})
// Functions to get dynamic options based on employment entry
const getOptionCity = (employment) => {
return location.data
.filter(loc => loc.location_type === 'City' && loc.parent_location === employment.country)
.map(loc => ({
label: loc.location_name,
value: loc.location_name
}))
}
const getOptionGovernorate = (employment) => {
return location.data
.filter(loc => loc.location_type === 'Governorate' && loc.parent_location === employment.city)
.map(loc => ({
label: loc.location_name,
value: loc.location_name
}))
}
// Handle Country Change for specific employment
const handleCountryChange = (index, value) => {
const employment = request.doc.employment_history[index]
employment.country = value.value
employment.city = '' // Reset city when country changes
employment.governorate = '' // Reset governorate when country changes
}
// Handle City Change for specific employment
const handleCityChange = (index, value) => {
const employment = request.doc.employment_history[index]
employment.city = value.value
employment.governorate = '' // Reset governorate when city changes
}
// Initialize employment_history
watch(() => request.doc, (newDoc) => {
if (newDoc) {
if (!newDoc.employment_history) {
// Initialize employment_history as an empty array if not present
newDoc.employment_history = []
}
}
}, { immediate: true })
// Fallback Initialization
if (!request.doc || !request.doc.employment_history) {
if (request.doc) {
request.doc.employment_history = []
} else {
// Handle the case where request.doc is initially null
request.doc = {
employment_history: []
}
}
}
// Manage Open Sections
const openSections = reactive({})
// Add a new employment entry
const addEmployment = () => {
const newEmployment = {
id: uuidv4(), // Unique identifier
company: '',
name_of_your_employer: '',
country: '',
city: '',
governorate: '',
}
request.doc.employment_history.push(newEmployment)
nextTick(() => {
openSections[newEmployment.id] = true
})
}
// Save the request
const saveRequest = async () => {
try {
await request.setValue.submit(request.doc)
toast.success('Request has been successfully saved!')
} catch (error) {
console.error('Failed to save the request:', error)
toast.error('Failed to save the request.')
}
}
</script>
Key Changes and Explanations
-
Individual Selection Handling:
-
Dynamic Option Generation:
Replaced selectedCountry and selectedCity with functions getOptionCity and getOptionGovernorate that accept the current employment entry as a parameter. This ensures that the options are dynamically generated based on the specific selections of each employment entry.
-
Event Handlers Update:
Modified the @input-change events to pass both the index and the selected value to the handlers. This allows each employment entry to manage its own state without interference.
-
Reset Dependent Fields:
When a country is changed, the associated city and governorate are reset to ensure data consistency. Similarly, changing the city resets the governorate.
-
Correct Event Binding:
- Ensured that the
@update:modelValue for the city Autocomp component isn't incorrectly bound to handleCountryChange. Instead, it now correctly binds to handleCityChange via the @input-change event.
-
Button Label Correction:
- Changed the "Add" button within each
FieldsToggleContainer to "Save" to better reflect its functionality of saving the current employment entry.
-
Improved Readability and Maintenance:
- By encapsulating the option generation logic within functions that accept the
employment object, the code becomes more modular and easier to maintain.
- Clearer naming conventions and comments help in understanding the flow and purpose of each part of the component.
Final Thoughts
By managing the selection states individually for each employment entry and ensuring that event handlers are correctly bound, your component will handle multiple employment histories more reliably and intuitively. This approach prevents state leakage between different parts of the form and enhances the overall user experience.
If you encounter further issues or have specific requirements, feel free to ask for more detailed assistance!