i choosed a event-ticketcreate, choosed field and its choices. keep this as a combination under same event . if i choose another set of fields and choices with same event name it should add as another combination
alter my code for this changes
async function loadExistingWorkflowConditions() {
console.log("Mapping Data for Workflows:", alldata.ticket_workflow_conditions);
for (const [eventName, fieldMappings] of Object.entries(alldata.ticket_workflow_conditions)) {
console.log('Loading rule for event:', eventName);
await addNewRule(eventName, fieldMappings);
}
}
async function addNewRule(eventName, fieldMappings) {
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
if (!fieldNameContainer) {
fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
container.appendChild(fieldNameContainer);
}
if (!choicesContainer) {
choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
container.appendChild(choicesContainer);
}
// Add "Delete Event" button if it doesn't already exist
if (!buttonContainer.querySelector('.delete-event-button')) {
const deleteEventButton = document.createElement('fw-button');
deleteEventButton.classList.add('delete-event-button');
deleteEventButton.setAttribute('color', 'danger');
deleteEventButton.textContent = 'Delete Event';
buttonContainer.appendChild(deleteEventButton);
code
deleteEventButton.addEventListener('click', () => {
const eventContainer = container.closest('.event-container');
if (eventContainer) {
eventContainer.remove();
delete ticketworkflowconditions[eventSelect.value];
console.log("Delete Event button clicked. Event removed from DOM and ticketworkflowconditions.");
}
});
}
// Handle existing mappings
if (fieldMappings) {
for (const [selectedFieldName, selectedChoices] of Object.entries(fieldMappings)) {
console.log(Mapping existing value: Event - ${eventSelect.value}, Field - ${selectedFieldName}, Choices - ${selectedChoices});
for (const choice of selectedChoices) {
await fieldschoosingvalues(
eventSelect.value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container,
selectedFieldName,
[choice]
);
}
}
}
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(Event changed to: ${selectedEventValue});
code
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = {};
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
}
async function fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
console.error("fieldschoosingvalues called with an undefined selectedEventValue.");
return;
}
try {
let statusResp = await makeApiCall(apiKeyInput1.value, domainInput1.value);
code
if (statusResp && statusResp.ticket_fields) {
let fields = statusResp.ticket_fields.filter(field =>
field.field_type.startsWith('default_') &&
field.choices &&
field.choices.length > 0 &&
field.required_for_agents
);
console.log(`Starting fieldschoosingvalues with selectedEventValue: ${selectedEventValue}`);
console.log(`Starting field name to map: ${selectedFieldName}`);
console.log(`Starting choice name to map: ${selectedChoices}`);
if (selectedFieldName) {
const individualFieldContainer = document.createElement('div');
individualFieldContainer.classList.add('field-container');
fieldNameContainer.appendChild(individualFieldContainer);
const individualChoicesContainer = document.createElement('div');
individualChoicesContainer.classList.add('choices-container');
choicesContainer.appendChild(individualChoicesContainer);
for (const choice of selectedChoices) {
console.log(`Mapping existing choice ${choice} to dropdown for field ${selectedFieldName} in event ${selectedEventValue}`);
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = {};
}
if (!ticketworkflowconditions[selectedEventValue][selectedFieldName]) {
ticketworkflowconditions[selectedEventValue][selectedFieldName] = [];
}
if (!ticketworkflowconditions[selectedEventValue][selectedFieldName].includes(choice)) {
ticketworkflowconditions[selectedEventValue][selectedFieldName].push(choice);
console.log(`Added choice ${choice} to ticketworkflowconditions for field ${selectedFieldName} under event ${selectedEventValue}`);
} else {
console.log(`Choice ${choice} already exists for field ${selectedFieldName} under event ${selectedEventValue}`);
}
await getFieldnamesfrom1stapi(
individualFieldContainer,
fields,
individualChoicesContainer,
selectedEventValue,
buttonContainer,
container,
selectedFieldName,
[choice]
);
}
} else {
await getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, container);
}
} else {
console.error('No fields found or data not available');
}
} catch (error) {
console.error("Error fetching data for Dropdown:", error);
}
}
async function getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
console.error("getFieldnamesfrom1stapi called with an undefined selectedEventValue.");
return;
}
console.log(Initializing field dropdown for event ${selectedEventValue}, field: ${selectedFieldName});
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = {};
}
if (!ticketworkflowconditions[selectedEventValue][selectedFieldName]) {
ticketworkflowconditions[selectedEventValue][selectedFieldName] = [];
}
if (!ticketworkflowconditions[selectedEventValue][selectedFieldName].includes(selectedChoiceId)) {
ticketworkflowconditions[selectedEventValue][selectedFieldName].push(selectedChoiceId);
console.log(`Added choice ID ${selectedChoiceId} to field ${selectedFieldName} for event ${selectedEventValue}`);
} else {
console.warn(`Choice ID ${selectedChoiceId} already exists in ${selectedFieldName}`);
}
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
// Call fieldschoosingvalues for this additional dropdown
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
}
To modify your code such that it allows for multiple field and choices combinations under the same event name, you will need to properly organize and maintain the state information for each combination. I'll update specific parts of your existing code to implement these changes:
Update the state management for the ticketworkflowconditions to allow multiple combinations per event.
Adjust event listeners to correctly manage the addition of new combinations.
Ensure the UI reflects the multiple combinations correctly.
Here are the adjustments made to your code:
javascript
// Adjust the organization of `ticketworkflowconditions`
const ticketworkflowconditions = {};
async function loadExistingWorkflowConditions() {
console.log("Mapping Data for Workflows:", alldata.ticket_workflow_conditions);
for (const [eventName, fieldMappings] of Object.entries(alldata.ticket_workflow_conditions)) {
console.log('Loading rule for event:', eventName);
await addNewRule(eventName, fieldMappings);
}
}
async function addNewRule(eventName, fieldMappings) {
const ticketworkflowContainer = document.getElementById('ticketworkflow-container');
const eventContainer = document.createElement('div');
// Same styling as before
// ...
const newDropdownSet = await createEventDropdownSet(eventName);
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
await initializeEventDropdown(newDropdownSet, fieldMappings);
}
async function initializeEventDropdown(container, fieldMappings = null) {
const eventSelect = container.querySelector('.event-name-dropdown');
console.log(`initializeEventDropdown - Initial selected event: ${eventSelect.value}`);
let fieldSetsContainer = container.querySelector('.field-sets-container');
if (!fieldSetsContainer) {
fieldSetsContainer = document.createElement('div');
fieldSetsContainer.classList.add('field-sets-container');
container.appendChild(fieldSetsContainer);
}
// Handle existing mappings
if (fieldMappings) {
for (const [selectedFieldName, selectedChoices] of Object.entries(fieldMappings)) {
await createFieldSet(fieldSetsContainer, eventSelect.value, selectedFieldName, selectedChoices);
}
}
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
fieldSetsContainer.innerHTML = ''; // Clear existing field sets
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await createFieldSet(fieldSetsContainer, selectedEventValue);
});
}
async function createFieldSet(container, eventValue, selectedFieldName = null, selectedChoices = null) {
const fieldNameContainer = document.createElement('div');
const choicesContainer = document.createElement('div');
const buttonContainer = document.createElement('div');
fieldNameContainer.classList.add('field-name-container');
choicesContainer.classList.add('choices-container');
buttonContainer.classList.add('button-container');
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Create all dropdowns and buttons here as previously done
// Call `fieldschoosingvalues` for each new field set
await fieldschoosingvalues(eventValue, fieldNameContainer, choicesContainer, buttonContainer, selectedFieldName, selectedChoices);
// Add button to allow creating additional field sets
const addButton = document.createElement('fw-button');
addButton.setAttribute('color', 'primary');
addButton.textContent = 'Add Field Set';
buttonContainer.appendChild(addButton);
addButton.addEventListener('click', () => {
createFieldSet(container, eventValue);
});
// Create delete option for this specific field set
const deleteFieldSetButton = document.createElement('fw-button');
deleteFieldSetButton.setAttribute('color', 'danger');
deleteFieldSetButton.textContent = 'Delete Field Set';
buttonContainer.appendChild(deleteFieldSetButton);
deleteFieldSetButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
// Implement additional logic to clean state if necessary
console.log(`Deleted field set for event: ${eventValue}`);
});
}
// The rest of your code stays largely unchanged
// Make sure to call `fieldschoosingvalues`, `getFieldnamesfrom1stapi`, and `showingitschoices` accordingly
Key Changes:
Multiple Field Sets: Added logic to manage multiple field sets under the same event by creating dedicated containers for field names and choices.
Dynamic Addition: Added buttons to allow users to dynamically add new field sets as needed.
Delete Field Set: Each field set can be independently deleted, which cleans up the UI and potentially the state.
These changes should better support your requirement to have multiple combinations of fields and choices under a single event name. You should further customize and ensure any state management reflects this structure adequately.
Below is the modified full code based on your original code and the requested functionality to allow for multiple field and choice combinations under the same event name:
javascript
const ticketworkflowconditions = {};
// Load existing workflow conditions from alldata
async function loadExistingWorkflowConditions() {
console.log("Mapping Data for Workflows:", alldata.ticket_workflow_conditions);
for (const [eventName, fieldMappings] of Object.entries(alldata.ticket_workflow_conditions)) {
console.log('Loading rule for event:', eventName);
await addNewRule(eventName, fieldMappings);
}
}
async function addNewRule(eventName, fieldMappings) {
const ticketworkflowContainer = document.getElementById('ticketworkflow-container');
const eventContainer = document.createElement('div');
eventContainer.classList.add('event-container');
eventContainer.style.boxShadow = '0 5px 10px 0 rgba(0, 0, 0, 0.2)';
eventContainer.style.padding = '30px';
eventContainer.style.marginBottom = '15px';
eventContainer.style.borderRadius = '5px';
eventContainer.style.backgroundColor = '#fff';
const newDropdownSet = await createEventDropdownSet(eventName);
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
await initializeEventDropdown(newDropdownSet, fieldMappings);
}
async function createEventDropdownSet(eventName) {
console.log("Creating Event Dropdown");
const newDropdownSet = document.createElement('div');
newDropdownSet.classList.add('row', 'ticketworkflow-dropdown');
const selectedEvent = typeof eventName === 'string' ? eventName : '';
newDropdownSet.innerHTML = `
<div class="col-md-2 event-name-container">
<fw-select
class="event-name-dropdown"
label="Select Event Name"
required="true"
placeholder="Your choice"
hint-text="Select singular option">
<fw-select-option value="TicketCreate" ${selectedEvent === "TicketCreate" ? "selected" : ""}>Ticket Create</fw-select-option>
<fw-select-option value="TicketUpdate" ${selectedEvent === "TicketUpdate" ? "selected" : ""}>Ticket Update</fw-select-option>
<fw-select-option value="TicketCreateandUpdate" ${selectedEvent === "TicketCreateandUpdate" ? "selected" : ""}>Ticket Create and Update</fw-select-option>
</fw-select>
</div>
`;
const eventSelect = newDropdownSet.querySelector('.event-name-dropdown');
if (selectedEvent) {
eventSelect.value = selectedEvent;
}
return newDropdownSet;
}
async function initializeEventDropdown(container, fieldMappings = null) {
const eventSelect = container.querySelector('.event-name-dropdown');
console.log(`initializeEventDropdown - Initial selected event: ${eventSelect.value}`);
let fieldSetsContainer = container.querySelector('.field-sets-container');
if (!fieldSetsContainer) {
fieldSetsContainer = document.createElement('div');
fieldSetsContainer.classList.add('field-sets-container');
container.appendChild(fieldSetsContainer);
}
// Handle existing mappings
if (fieldMappings) {
for (const [selectedFieldName, selectedChoices] of Object.entries(fieldMappings)) {
await createFieldSet(fieldSetsContainer, eventSelect.value, selectedFieldName, selectedChoices);
}
}
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
fieldSetsContainer.innerHTML = ''; // Clear existing field sets
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await createFieldSet(fieldSetsContainer, selectedEventValue);
});
}
async function createFieldSet(container, eventValue, selectedFieldName = null, selectedChoices = null) {
const fieldNameContainer = document.createElement('div');
const choicesContainer = document.createElement('div');
const buttonContainer = document.createElement('div');
fieldNameContainer.classList.add('field-name-container');
choicesContainer.classList.add('choices-container');
buttonContainer.classList.add('button-container');
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Initialize fieldschoosingvalues for the new field set
await fieldschoosingvalues(eventValue, fieldNameContainer, choicesContainer, buttonContainer, selectedFieldName, selectedChoices);
// Button to create additional field sets
const addButton = document.createElement('fw-button');
addButton.setAttribute('color', 'primary');
addButton.textContent = 'Add Field Set';
buttonContainer.appendChild(addButton);
addButton.addEventListener('click', () => {
createFieldSet(container, eventValue);
});
// Delete button for this specific field set
const deleteFieldSetButton = document.createElement('fw-button');
deleteFieldSetButton.setAttribute('color', 'danger');
deleteFieldSetButton.textContent = 'Delete Field Set';
buttonContainer.appendChild(deleteFieldSetButton);
deleteFieldSetButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
console.log(`Deleted field set for event: ${eventValue}`);
});
}
async function fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
console.error("fieldschoosingvalues called with an undefined selectedEventValue.");
return;
}
try {
let statusResp = await makeApiCall(apiKeyInput1.value, domainInput1.value);
if (statusResp && statusResp.ticket_fields) {
let fields = statusResp.ticket_fields.filter(field =>
field.field_type.startsWith('default_') &&
field.choices &&
field.choices.length > 0 &&
field.required_for_agents
);
if (selectedFieldName) {
const individualFieldContainer = document.createElement('div');
individualFieldContainer.classList.add('field-container');
fieldNameContainer.appendChild(individualFieldContainer);
const individualChoicesContainer = document.createElement('div');
individualChoicesContainer.classList.add('choices-container');
choicesContainer.appendChild(individualChoicesContainer);
for (const choice of selectedChoices) {
await getFieldnamesfrom1stapi(
individualFieldContainer,
fields,
individualChoicesContainer,
selectedEventValue,
buttonContainer,
selectedFieldName,
[choice]
);
}
} else {
await getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer);
}
} else {
console.error('No fields found or data not available');
}
} catch (error) {
console.error("Error fetching data for Dropdown:", error);
}
}
async function getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, selectedFieldName = null, selectedChoices = null) {
const firstDropdown = document.createElement('fw-select');
firstDropdown.classList.add('field-name-dropdown');
firstDropdown.setAttribute('label', 'Ticket Fields');
firstDropdown.setAttribute('required', 'true');
firstDropdown.setAttribute('placeholder', 'Choose a field');
firstDropdown.setAttribute('hint-text', 'Select singular option');
fields.forEach(field => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', field.name);
option.textContent = field.label;
firstDropdown.appendChild(option);
if (selectedFieldName && field.name === selectedFieldName) {
option.setAttribute('selected', 'selected');
}
});
fieldNameContainer.appendChild(firstDropdown);
if (selectedFieldName) {
const selectedField = fields.find(field => field.name === selectedFieldName);
if (selectedField) {
await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, selectedChoices);
}
}
firstDropdown.addEventListener('fwChange', async (event) => {
const selectedFieldName = event.target.value;
choicesContainer.innerHTML = '';
const selectedField = fields.find(field => field.name === selectedFieldName);
if (selectedField) {
await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer);
} else {
console.error('Selected Field not found in fields.');
}
});
}
async function showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, selectedChoices = null) {
choicesContainer.innerHTML = '';
const choicesDropdown = document.createElement('fw-select');
choicesDropdown.classList.add('choices-dropdown');
choicesDropdown.setAttribute('label', `${selectedFieldName}`);
choicesDropdown.setAttribute('required', 'true');
choicesDropdown.setAttribute('placeholder', `Choose ${selectedFieldName}`);
choicesDropdown.setAttribute('hint-text', 'Select singular option');
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
}
});
choicesContainer.appendChild(choicesDropdown);
if (buttonContainer.childNodes.length === 0) {
const addButton = document.createElement('fw-button');
addButton.setAttribute('color', 'primary');
addButton.textContent = 'Add';
buttonContainer.appendChild(addButton);
addButton.addEventListener('click', () => {
// Add logic to handle adding this choice to ticketworkflowconditions if necessary
const selectedChoiceId = choicesDropdown.value;
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = {};
}
if (!ticketworkflowconditions[selectedEventValue][selectedFieldName]) {
ticketworkflowconditions[selectedEventValue][selectedFieldName] = [];
}
if (!ticketworkflowconditions[selectedEventValue][selectedFieldName].includes(selectedChoiceId)) {
ticketworkflowconditions[selectedEventValue][selectedFieldName].push(selectedChoiceId);
}
});
}
}
Full Code Explanation:
Container Structure: The code maintains a structure where multiple field sets can be created under a single event dropdown.
Dynamic UI Elements: Added buttons for both adding and deleting field sets.
Ticketworkflow Conditions: The conditions are organized into a nested structure that allows multiple fields and their associated choices to be stored efficiently per event.
Event Handling: Proper event listeners are set up to handle the selection of fields and choices dynamically.
This complete code should now fulfill your requirement of supporting multiple field and choice combinations under the same event while ensuring that the UI is intuitive and functional. Adjust any additional API interaction details or UI specifics according to your application's needs.
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = {};
}
if (!ticketworkflowconditions[selectedEventValue][selectedFieldName]) {
ticketworkflowconditions[selectedEventValue][selectedFieldName] = [];
}
if (!ticketworkflowconditions[selectedEventValue][selectedFieldName].includes(selectedChoiceId)) {
ticketworkflowconditions[selectedEventValue][selectedFieldName].push(selectedChoiceId);
console.log(`Added choice ID ${selectedChoiceId} to field ${selectedFieldName} for event ${selectedEventValue}`);
} else {
console.warn(`Choice ID ${selectedChoiceId} already exists in ${selectedFieldName}`);
}
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
To modify your showingitschoices function to save the state in the new JSON structure you've provided, you'll need to implement several changes to how ticketworkflowconditions is structured and how data is saved when users interact with the dropdown elements.
Below is the updated code for the showingitschoices function, along with adjustments to the relevant parts of your overall workflow. I'll ensure to include the necessary changes that capture the event name, create combinations, and save fields and their selections in the specified JSON format.
Data Structure: Changed ticketworkflowconditions to an array structure compatible with the required JSON format.
Combination Handling:
Added an addCombination function, which creates a new combination for the selected event. This function collects the selected fields and their values whenever the user clicks "Add Combination".
The function checks if the event already exists in ticketworkflowconditions. If not, it creates a new entry.
Dropdown Event Handling:
When a choice is selected, the corresponding field's value is updated in the combinations.
Added checks to ensure that the appropriate event and combination are being interacted with.
How to Use
When users select choices from the dropdown, they are stored in ticketworkflowconditions.
Each time they click "Add Combination", a new combination is added to the appropriate event.
The structure now matches your specified JSON format, making it easier to serialize and work with.
Final Considerations
Make sure to check that the new structure functions correctly with your existing workflow and adjust any additional interactions that might depend on how data is stored or retrieved. Additionally, you may want to implement additional features or checks based on your application's requirements (such as enabling/disabling combinations).
To address the issue where the error "Event not found in ticketworkflowconditions" is thrown, we need to ensure that the event is properly being added to ticketworkflowconditions when a new combination is created, and that when updating the selection, the code correctly identifies existing events.
Here’s an updated version of the showingitschoices and related functions to make sure the event is correctly tracked and updated:
Updated Code
javascript
const ticketworkflowconditions = []; // Initialize the new data structure
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
choicesContainer.innerHTML = '';
const choicesDropdown = document.createElement('fw-select');
choicesDropdown.classList.add('choices-dropdown');
choicesDropdown.setAttribute('label', `${selectedFieldName}`);
choicesDropdown.setAttribute('required', 'true');
choicesDropdown.setAttribute('placeholder', `Choose ${selectedFieldName}`);
choicesDropdown.setAttribute('hint-text', 'Select singular option');
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
choicesContainer.appendChild(choicesDropdown);
// Create Add and Delete buttons
if (buttonContainer.childNodes.length === 0) {
const addButton = document.createElement('fw-button');
addButton.setAttribute('color', 'primary');
addButton.textContent = 'Add Combination';
buttonContainer.appendChild(addButton);
const deleteFieldButton = document.createElement('fw-button');
deleteFieldButton.setAttribute('color', 'danger');
deleteFieldButton.textContent = 'Delete Field Set';
buttonContainer.appendChild(deleteFieldButton);
addButton.addEventListener('click', () => {
addCombination(selectedEventValue, fieldNameContainer, choicesDropdown);
});
deleteFieldButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Updating the combination for the selected event
let eventEntry = ticketworkflowconditions.find(eventObj => eventObj.eventName === selectedEventValue);
if (!eventEntry) {
// If not found, create a new event entry since it should always exist when adding combinations
console.warn(`Event "${selectedEventValue}" not found. This is likely an issue with how combinations are being added.`);
return; // Early return to avoid further errors
}
// Check if there's already an active combination
const activeCombination = eventEntry.combinations.find(comb => comb.isEnabled === true);
if (!activeCombination) {
console.warn('No active combination found for this event');
return;
}
// Find the field and update or add it
const fieldEntry = activeCombination.fields.find(field => field.name === selectedFieldName);
if (fieldEntry) {
fieldEntry.value = selectedChoiceId; // Update the value directly
} else {
activeCombination.fields.push({ name: selectedFieldName, value: selectedChoiceId });
}
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function addCombination(selectedEventValue, fieldNameContainer, choicesDropdown) {
let eventEntry = ticketworkflowconditions.find(event => event.eventName === selectedEventValue);
if (!eventEntry) {
eventEntry = { eventName: selectedEventValue, combinations: [] };
ticketworkflowconditions.push(eventEntry);
}
const newCombination = {
isEnabled: true,
fields: []
};
// Find selected fields and their corresponding choices
const fieldEntries = fieldNameContainer.querySelectorAll('.field-name-dropdown');
fieldEntries.forEach(field => {
const fieldName = field.value;
const fieldChoice = choicesDropdown.value; // Get the latest selected choice
newCombination.fields.push({ name: fieldName, value: fieldChoice });
});
// Adding the new combination to the event entry
eventEntry.combinations.push(newCombination);
console.log('Added new combination:', newCombination);
}
Key Changes and Explanations
Error Handling: In the showingitschoices function, added a check to see if the event entry exists. If it doesn't, it logs a warning but doesn’t attempt to proceed, preventing further errors.
Event Structure: The structure ensures that the event is correctly added when the "Add Combination" button is clicked, and when fields are selected, it properly attempts to retrieve the existing combinations.
Active Combination Check: A check is in place to ensure at least one active combination exists when trying to add fields to it.
Use of Console Warnings: Added console warnings to highlight when certain conditions (like event not found or no active combination) occur, which can assist in debugging.
Testing the Code
Make sure to thoroughly test this modified code in your application to ensure that the creation of events and their combinations works as expected.
Pay close attention to the sequence of user inputs, especially when adding combinations and updating selections to confirm that the data reflects accurately in ticketworkflowconditions.
Feel free to reach out if you need any more modifications or additional features!