// Reset ticketworkflowconditions for new event
if (newEvent !== selectedEvent) {
ticketworkflowconditions = { [newEvent]: { combinations: [{ isEnabled: true, fields: {} }] } };
// Clear existing field-related containers
newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());
// Create containers for the fields, choices, and buttons
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
newDropdownSet.appendChild(fieldNameContainer);
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
newDropdownSet.appendChild(choicesContainer);
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
newDropdownSet.appendChild(buttonContainer);
// Populate dropdowns with the newly selected event using the existing logic
await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
}
});
// Append the newDropdownSet to the eventContainer
eventContainer.appendChild(newDropdownSet);
// Finally, append the eventContainer to the main ticketworkflow container
ticketworkflowContainer.appendChild(eventContainer);
}
async function fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
console.error("fieldschoosingvalues called with an undefined selectedEventValue.");
return; // Early exit
}
try {
let statusResp = await makeApiCall(apiKeyInput1.value, domainInput1.value);
code
if (statusResp && statusResp.ticket_fields) {
const fields = statusResp.ticket_fields.filter(field =>
field.field_type.startsWith('default_') &&
field.choices &&
field.choices.length > 0
);
console.log(`Starting fieldschoosingvalues with selectedEventValue: ${selectedEventValue}`);
if (selectedFieldName) {
const fieldContainer = document.createElement('div');
fieldContainer.classList.add('field-container');
fieldNameContainer.appendChild(fieldContainer);
const choicesDiv = document.createElement('div');
choicesDiv.classList.add('choices-container');
choicesContainer.appendChild(choicesDiv);
await getFieldnamesfrom1stapi(fieldContainer, fields, choicesDiv, selectedEventValue, buttonContainer, container, selectedFieldName, selectedChoices);
} 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("Select an event before proceeding.");
return;
}
// Set the initial selected field if provided
if (selectedFieldName && field.name === selectedFieldName) {
option.setAttribute('selected', 'selected');
}
});
fieldNameContainer.appendChild(fieldDropdown);
// Initial mapping of choices in case a field is already selected
if (selectedFieldName) {
const selectedField = fields.find(field => field.name === selectedFieldName);
if (selectedField) {
await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, container, fieldNameContainer, selectedChoices);
code
// Ensure that ticketworkflowconditions structure is initialized for the event.
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] }; // Initialize if not present
}
// Get the latest combination or create a new one if none exists
const combinationsArray = ticketworkflowconditions[selectedEventValue].combinations;
let latestCombination;
if (combinationsArray.length > 0) {
// Get the latest combination
latestCombination = combinationsArray[combinationsArray.length - 1];
} else {
// If no combination exists, create and push a new one
latestCombination = { isEnabled: true, fields: {} };
combinationsArray.push(latestCombination);
}
// Update the selected field in the latest combination's fields
// Ensure previous values are preserved
latestCombination.fields[selectedFieldName] = selectedChoices ? selectedChoices[0] : null;
console.log(`Updated ticketworkflowconditions with mapped fields: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
} else {
console.error('Field not found in Dropdown');
}
}
// Update logic for field change event
fieldDropdown.addEventListener('fwChange', async (event) => {
const newSelectedFieldName = event.target.value;
choicesContainer.innerHTML = '';
code
const newSelectedField = fields.find(field => field.name === newSelectedFieldName);
if (newSelectedField) {
await showingitschoices(choicesContainer, newSelectedField, selectedEventValue, newSelectedFieldName, buttonContainer, container, fieldNameContainer);
// Get the latest combination for the selected event
const latestCombination = ticketworkflowconditions[selectedEventValue].combinations[ticketworkflowconditions[selectedEventValue].combinations.length - 1];
// Update JSON with newly selected field and choice in the latest combination
const choiceValue = choicesContainer.querySelector('.choices-dropdown')?.value || null;
if (latestCombination) {
latestCombination.fields[newSelectedFieldName] = choiceValue; // Add to the latest combination fields
} else {
console.error("No latest combination found for updating fields.");
}
console.log(`Field changed: ${newSelectedFieldName}, Choice: ${choiceValue}`);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
} else {
console.error('Field not found in Dropdown');
}
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
}
});
choicesContainer.appendChild(choicesDropdown);
// Check if the button has already been added
if (!buttonContainer.querySelector('.btn-primary')) {
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Ensure the event is initialized in ticketworkflowconditions
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [{ isEnabled: true, fields: {} }] };
}
// Get the latest combination
const latestCombination = ticketworkflowconditions[selectedEventValue].combinations[
ticketworkflowconditions[selectedEventValue].combinations.length - 1
];
// Update the field's value in the latest combination as a key-value pair
latestCombination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated JSON with field: ${selectedFieldName}, choice: ${selectedChoiceId}`);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
});
}
on choosing choices dropdown, the json should like this
To modify your code so that the JSON structure reflects the desired output format when a choice is selected from the dropdown, you'll need to adjust how you capture each event’s conditions and structure them properly. Specifically, instead of maintaining a nested structure with combinations, we want to set up an array of conditions, where each condition corresponds to an event.
Suggested Changes
Update the ticketworkflowconditions Object: We'll change the structure so that ticketworkflowconditions stores an array of condition objects instead of a nested combination format.
Modify the Event Handlers: When the choices dropdown changes, we will create a consistent object structure that includes eventName, isEnabled, and fields.
Here's how you can achieve this:
Updated Code
javascript
User
async function loadExistingWorkflowConditions() {
let workflowConditions = alldata.ticket_workflow_conditions;
console.log("Mapping Data for Workflows:", workflowConditions);
// Iterate over each condition to add event dropdowns
for (const condition of workflowConditions) {
const { eventName, fields } = condition;
code
Assistant
To ensure that your code saves the ticketworkflowconditions variable in the specified format when a user selects a choice from a dropdown, we’ll need to make sure the data structure is created correctly throughout your application.
Below, I'll give you modifications to your existing code to facilitate that:
Adjustments to the condition structure: We will ensure that ticketworkflowconditions is an array of objects. Each object will represent a workflow condition for an event and have properties: eventName, isEnabled, and fields.
Updating fields: When a field is changed, it will update the existing field in the corresponding condition object.
Here’s how you can ensure that when a condition is saved or modified, it aligns with your specified format.
Updated Code
The following are key changes and the complete function code necessary to save the conditions in the required format:
To ensure that your code behaves as expected—removing the existing event condition when the event is changed and creating a new one—it's important to handle the ticketworkflowconditions array correctly when the event selection changes.
Here's how to achieve this:
When the event is changed from one to another (e.g., from TicketCreate to TicketUpdate), you should first remove the existing condition associated with the previous event.
Then you create a new condition for the selected event with its corresponding fields and choices.
Ensure that the fields and other properties for the new condition are initialized appropriately.
Updated Code
I will modify the addNewRule function and the event change handler to follow this logic:
To ensure that only one condition for each event is present in the ticketworkflowconditions array at any time, we need to make sure that when switching between events, we completely remove the existing condition for that event before adding a new one. If the logic you've implemented still allows duplicates, we need to adjust how the ticketworkflowconditions is manipulated.
Code Adjustments to Prevent Duplicate Conditions:
Clear Existing Conditions: Ensure that when a user selects a new event, we filter out not only the previous event but also check if the new selected event already exists.
Always Ensure No Duplicates: Whenever we add a new condition, we first check if a condition for that event name already exists and remove it before adding the new one.
Here’s the updated code for the addNewRule function:
If the code is still appending new entries without removing the old ones properly, let's make sure we address the logic that modifies the ticketworkflowconditions array.
Debugging Steps
Ensure Correct Filtering: We need to ensure that when you change the event, we are properly filtering the ticketworkflowconditions array.
Consolidate Logic: During the selection change, not only should we remove the existing event, but we need to ensure we're not adding the same event condition back inadvertently.
Clear Output Immediately: We should immediately log the current state of ticketworkflowconditions after each manipulation to catch any issues.
Updated Code Snippet:
Here’s an updated version of the addNewRule function where we will take care to remove existing conditions for the events:
If the code is still appending new entries to ticketworkflowconditions instead of replacing or removing the previous event, let's take a closer look at how we're managing the state of the ticketworkflowconditions array.
Issues to Investigate
Event Listener Logic: Ensure the event listeners are properly clearing previous conditions and preventing duplicates.
State Management: Ensure that conditions are correctly filtered when changing events.
Proper Logging: Use logging effectively to track when conditions are added or removed from the array.
Complete Example with Fixes
Here's a revised version of your function including checks and detailed logging to help ensure proper behavior:
i changed event dropdown from ticketcreate to ticketcreateandupdate it should replace instead of adding on changing the dropdown
Assistant
If the goal is to completely replace the previous entry in the ticketworkflowconditions array with the current selected event when the dropdown changes, we need to make sure that:
Remove the previous entry: We need to filter out the existing condition not just for the previous event but also ensure that when we create a new entry for the newly selected event, we do not append if it already exists.
Updating or creating logic: We should only create a new entry for the selected event if it doesn't already exist.
Revised Implementation
Here’s how you can modify the addNewRule function to handle this properly:
javascript
User
remove based on array index
Assistant
To remove an event based on its index from the ticketworkflowconditions array, you can use the splice() method in JavaScript. This method can be used to remove an item from an array at a specific index.
Implementation Steps:
Find the Index to Remove: Use findIndex() to get the index of the existing condition based on the eventName.
Use splice(): Once the index is found, use splice(index, 1) to remove the item.
Updated Code Example
Here's how you can implement these steps in your code:
To ensure that the previous event condition is replaced instead of simply adding another condition when switching between events, we need to carefully manage the ticketworkflowconditions array. This involves clearly defining when to remove an old condition and also ensuring that it’s done correctly.
Key Points to Check:
Check if the Previous Event Exists: Before adding a new condition, ensure that any existing condition for the previous event is removed.
Prevent Duplicate Entries: After removing the previous event condition, attempt to also remove any existing condition for the newly selected event before you add it.
Let's take an in-depth look at the addNewRule function to ensure that it operates correctly.
Updated Code Implementation
Here’s the revised version of the addNewRule function:
// Initialize an empty array to store ticket workflow conditions
let ticketworkflowconditions = [];
// Load existing workflow conditions
async function loadExistingWorkflowConditions() {
let workflowConditions = alldata.ticket_workflow_conditions;
console.log("Mapping Data for Workflows:", workflowConditions);
await addNewRule(null, workflowConditions);
}
// Adds a new rule for workflow conditions
async function addNewRule(eventName, workflowConditions) {
console.log("Existing Workflow Conditions:", workflowConditions);
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 = 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>
`;
// Append the dropdown to the newDropdownSet
newDropdownSet.querySelector('.event-name-dropdown').value = selectedEvent;
const eventSelect = newDropdownSet.querySelector('.event-name-dropdown');
eventSelect.addEventListener('fwChange', async () => {
const newEvent = eventSelect.value;
if (newEvent !== selectedEvent) {
// Clear and prepare a new condition for the selected event
const newCondition = { eventName: newEvent, isEnabled: true, fields: {} };
ticketworkflowconditions = ticketworkflowconditions.filter(cond => cond.eventName !== newEvent); // Remove previous definitions
// Clear existing field-related containers
newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
newDropdownSet.appendChild(fieldNameContainer);
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
newDropdownSet.appendChild(choicesContainer);
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
newDropdownSet.appendChild(buttonContainer);
await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet, null, null);
ticketworkflowconditions.push(newCondition);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
}
});
// Append the newDropdownSet to the eventContainer
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
}
// Existing methods remain largely unchanged, but you must adapt how you store and access conditions.
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');
}
});
choicesContainer.appendChild(choicesDropdown);
if (!buttonContainer.querySelector('.btn-primary')) {
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
addButton.addEventListener('click', () => {
createAdditionalDropdowns(container);
});
}
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
const eventCondition = ticketworkflowconditions.find(cond => cond.eventName === selectedEventValue);
if (eventCondition) {
// Update the event condition with the selected choice
eventCondition.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated JSON with field: ${selectedFieldName}, choice: ${selectedChoiceId}`);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
}
});
}
// Ensure other functions like getFieldnamesfrom1stapi maintain consistent structures as needed.
Explanation of Changes
Single Condition Objects: Each event now corresponds to a single object in the ticketworkflowconditions array.
Event Selection Logic: The logic resets the existing entry for an event if it changes, allowing the user to create a fresh set of conditions without carrying over anything unintended.
Choices Logic: As the user selects choices in the dropdowns, the fields object within the event condition is updated dynamically to align with the new structure.
Logging for Debugging: Console logs are added to help track changes to the ticketworkflowconditions array for troubleshooting.
Resulting JSON Structure
When culminating the function interactions, the structure achieved will resemble:
json
[
{
"eventName": "TicketCreate",
"isEnabled": true,
"fields": {
"status": "3" // Example choice ID from selected choices
}
}
]
These modifications ensure your application logic captures the expected output format.
async function fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
console.error("fieldschoosingvalues called with an undefined selectedEventValue.");
return; // Early exit
}
try {
let statusResp = await makeApiCall(apiKeyInput1.value, domainInput1.value);
code
if (statusResp && statusResp.ticket_fields) {
const fields = statusResp.ticket_fields.filter(field =>
field.field_type.startsWith('default_') &&
field.choices &&
field.choices.length > 0
);
console.log(`Starting fieldschoosingvalues with selectedEventValue: ${selectedEventValue}`);
if (selectedFieldName) {
const fieldContainer = document.createElement('div');
fieldContainer.classList.add('field-container');
fieldNameContainer.appendChild(fieldContainer);
const choicesDiv = document.createElement('div');
choicesDiv.classList.add('choices-container');
choicesContainer.appendChild(choicesDiv);
await getFieldnamesfrom1stapi(fieldContainer, fields, choicesDiv, selectedEventValue, buttonContainer, container, selectedFieldName, selectedChoices);
} 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("Select an event before proceeding.");
return;
}
// Set the initial selected field if provided
if (selectedFieldName && field.name === selectedFieldName) {
option.setAttribute('selected', 'selected');
}
});
fieldNameContainer.appendChild(fieldDropdown);
// Initial mapping of choices in case a field is already selected
if (selectedFieldName) {
const selectedField = fields.find(field => field.name === selectedFieldName);
if (selectedField) {
await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, container, fieldNameContainer, selectedChoices);
code
// Ensure that ticketworkflowconditions structure is initialized for the event.
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] }; // Initialize if not present
}
// Get the latest combination or create a new one if none exists
const combinationsArray = ticketworkflowconditions[selectedEventValue].combinations;
let latestCombination;
if (combinationsArray.length > 0) {
// Get the latest combination
latestCombination = combinationsArray[combinationsArray.length - 1];
} else {
// If no combination exists, create and push a new one
latestCombination = { isEnabled: true, fields: {} };
combinationsArray.push(latestCombination);
}
// Update the selected field in the latest combination's fields
// Ensure previous values are preserved
latestCombination.fields[selectedFieldName] = selectedChoices ? selectedChoices[0] : null;
console.log(`Updated ticketworkflowconditions with mapped fields: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
} else {
console.error('Field not found in Dropdown');
}
}
// Update logic for field change event
fieldDropdown.addEventListener('fwChange', async (event) => {
const newSelectedFieldName = event.target.value;
choicesContainer.innerHTML = '';
code
const newSelectedField = fields.find(field => field.name === newSelectedFieldName);
if (newSelectedField) {
await showingitschoices(choicesContainer, newSelectedField, selectedEventValue, newSelectedFieldName, buttonContainer, container, fieldNameContainer);
// Get the latest combination for the selected event
const latestCombination = ticketworkflowconditions[selectedEventValue].combinations[ticketworkflowconditions[selectedEventValue].combinations.length - 1];
// Update JSON with newly selected field and choice in the latest combination
const choiceValue = choicesContainer.querySelector('.choices-dropdown')?.value || null;
if (latestCombination) {
latestCombination.fields[newSelectedFieldName] = choiceValue; // Add to the latest combination fields
} else {
console.error("No latest combination found for updating fields.");
}
console.log(`Field changed: ${newSelectedFieldName}, Choice: ${choiceValue}`);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
} else {
console.error('Field not found in Dropdown');
}
async function loadExistingWorkflowConditions() {
let workflowConditions = alldata.ticket_workflow_conditions;
console.log("Mapping Data for Workflows:", workflowConditions);
await addNewRule(workflowConditions);
}
async function addNewRule(workflowConditions) {
console.log("Existing Workflow Conditions:", workflowConditions);
const ticketworkflowContainer = document.getElementById('ticketworkflow-container');
// Iterate over each condition to add event dropdowns
for (const condition of workflowConditions) {
const { eventName, fields } = condition;
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 = document.createElement('div');
newDropdownSet.classList.add('row', 'ticketworkflow-dropdown');
const selectedEvent = 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>
<div class="col-md-2 choices-container"></div>
<div class="col-md-3 button-container" style="margin-top: 25px;"></div>
`;
const eventSelect = newDropdownSet.querySelector('.event-name-dropdown');
eventSelect.value = selectedEvent;
// Ensure previously selected fields and choices are maintained
await fieldschoosingvalues(selectedEvent, newDropdownSet.querySelector('.col-md-2'), newDropdownSet.querySelector('.choices-container'), newDropdownSet.querySelector('.button-container'), selectedFieldName, fields);
eventSelect.addEventListener('fwChange', async () => {
const newEvent = eventSelect.value;
if (newEvent !== selectedEvent) {
// Update ticketworkflowconditions array
let existingCondition = ticketworkflowconditions.find(cond => cond.eventName === selectedEvent);
if (existingCondition) {
// Update existing condition
existingCondition.eventName = newEvent;
} else {
// Add new condition for the newly selected event
ticketworkflowconditions.push({ eventName: newEvent, isEnabled: true, fields: {} });
}
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
}
});
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
}
}
// Update this function as required to ensure all dropdowns update ticketworkflowconditions correctly
async function fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, selectedFieldName = null, selectedFields = null) {
if (!selectedEventValue) {
console.error("Selected event value is undefined.");
return; // Early exit
}
// Assuming you have a makeApiCall to get fields
try {
let statusResp = await makeApiCall(apiKeyInput1.value, domainInput1.value);
if (statusResp && statusResp.ticket_fields) {
const fields = statusResp.ticket_fields.filter(field => field.field_type.startsWith('default_') && field.choices && field.choices.length > 0);
const selectedField = selectedFields ? fields.find(field => field.name === selectedFieldName) : null;
// Populate the fields and choices based on previously selected fields
await getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, selectedField, selectedFields);
} 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, selectedField = null, selectedChoices = null) {
const fieldDropdown = document.createElement('fw-select');
fieldDropdown.setAttribute('label', 'Ticket Fields');
fieldDropdown.setAttribute('required', 'true');
fieldDropdown.setAttribute('placeholder', 'Choose a field');
fieldDropdown.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;
fieldDropdown.appendChild(option);
if (selectedField && field.name === selectedField.name) {
option.setAttribute('selected', 'selected');
}
});
fieldNameContainer.appendChild(fieldDropdown);
// Handle field change and update choices accordingly
fieldDropdown.addEventListener('fwChange', async (event) => {
const newSelectedFieldName = event.target.value;
choicesContainer.innerHTML = ''; // Clear previous choices
const newSelectedField = fields.find(field => field.name === newSelectedFieldName);
if (newSelectedField) {
await showingitschoices(choicesContainer, newSelectedField, selectedEventValue, newSelectedFieldName, buttonContainer, fieldNameContainer);
const eventCondition = ticketworkflowconditions.find(cond => cond.eventName === selectedEventValue);
if (eventCondition) {
eventCondition.fields[newSelectedFieldName] = ''; // Initialize field value
}
} else {
console.error('Field not found in Dropdown');
}
});
}
async function showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, fieldNameContainer, selectedChoices = null) {
choicesContainer.innerHTML = '';
const choicesDropdown = document.createElement('fw-select');
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);
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
const eventCondition = ticketworkflowconditions.find(cond => cond.eventName === selectedEventValue);
if (eventCondition) {
// Update the event condition with the selected choice
eventCondition.fields[selectedFieldName] = selectedChoiceId; // Store the selected choice ID here
console.log(`Updated JSON with field: ${selectedFieldName}, choice: ${selectedChoiceId}`);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
}
});
}
Changes Explained
Updated ticketworkflowconditions structure:
Now maintains a flat structure where each workflow condition is represented as an object, making it easy to push new conditions and update existing ones.
Event Handling:
Each event dropdown updates the corresponding condition in ticketworkflowconditions, ensuring previous choices and fields are preserved and updated properly as the user interacts with the UI.
Choice Handling:
When a user selects a choice from the dropdown, it updates the fields object inside the corresponding condition based on the selected field.
Maintainability:
The structure allows easy extension and modification if you need to add more fields or conditions later, keeping the code clear and concise.
By following these steps, you should be able to achieve the required JSON structure for ticketworkflowconditions and ensure it updates correctly based on user input. The final output JSON structure should look like:
if (newEvent !== selectedEvent) {
// Reset the fields for the previous event
const previousEventCondition = ticketworkflowconditions.find(cond => cond.eventName === selectedEvent);
if (previousEventCondition) {
// Reset the fields array to empty for the previous event
previousEventCondition.fields = {};
console.log(`Reset fields for event "${selectedEvent}"`);
}
// Clear and prepare a new condition for the selected event
const newCondition = { eventName: newEvent, isEnabled: true, fields: {} };
ticketworkflowconditions = ticketworkflowconditions.filter(cond => cond.eventName !== newEvent); // Remove previous definitions
// Clear existing field-related containers
newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
newDropdownSet.appendChild(fieldNameContainer);
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
newDropdownSet.appendChild(choicesContainer);
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
newDropdownSet.appendChild(buttonContainer);
await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet, null, null);
ticketworkflowconditions.push(newCondition);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
}
});
// Append the newDropdownSet to the eventContainer
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
}
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);
// Select the current selected field if available
if (selectedFieldName && field.name === selectedFieldName) {
option.setAttribute('selected', 'selected');
}
});
fieldNameContainer.appendChild(fieldDropdown);
if (selectedFieldName) {
const selectedField = fields.find(field => field.name === selectedFieldName);
if (selectedField) {
await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, container, fieldNameContainer, selectedChoices);
} else {
console.error('Field not found in Dropdown');
}
}
// Find the event condition for the selected event name
const eventCondition = ticketworkflowconditions.find(cond => cond.eventName === selectedEventValue);
if (eventCondition) {
const previousFieldName = selectedFieldName; // Store the previous selected field name
// Log the previous field name for debugging
console.log(`Previous field name: ${previousFieldName}`);
if (previousFieldName && previousFieldName !== newSelectedFieldName) {
// Remove the previous field from the fields object
delete eventCondition.fields[previousFieldName];
console.log(`Removed previous field "${previousFieldName}" from event condition.`);
}
// Add the new selected field to the fields object
eventCondition.fields = {}; // Clear out the fields object to avoid multiple field additions
eventCondition.fields[newSelectedFieldName] = null; // Add the new field with a placeholder value (null)
console.log(`Added new field "${newSelectedFieldName}" to event condition.`);
// Clear the choices container before adding new choices
choicesContainer.innerHTML = '';
const newSelectedField = fields.find(field => field.name === newSelectedFieldName);
if (newSelectedField) {
await showingitschoices(choicesContainer, newSelectedField, selectedEventValue, newSelectedFieldName, buttonContainer, container, fieldNameContainer);
} else {
console.error('Field not found in Dropdown');
}
}
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
}
});
choicesContainer.appendChild(choicesDropdown);
// Listen for changes in choices selection
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
// Find the event condition for the selected event name
let eventCondition = ticketworkflowconditions.find(cond => cond.eventName === selectedEventValue);
if (!eventCondition) {
eventCondition = { eventName: selectedEventValue, isEnabled: true, fields: {} };
ticketworkflowconditions.push(eventCondition);
}
// Update the fields object with the selected choice
eventCondition.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
});
}
in this, if i choosed ticketcreate and choosed fields and choices, now if i change the event from ticketcreate to ticketupdate fore.x why it adds as another array it should remove existing event and create new on
async function addNewRule(eventName, workflowConditions) {
console.log("Existing Workflow Conditions:", workflowConditions);
const ticketworkflowContainer = document.getElementById('ticketworkflow-container');
// Create a new container for the current event
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 = 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>
`;
// Append the dropdown to the newDropdownSet
newDropdownSet.querySelector('.event-name-dropdown').value = selectedEvent;
const eventSelect = newDropdownSet.querySelector('.event-name-dropdown');
eventSelect.addEventListener('fwChange', async () => {
const newEvent = eventSelect.value;
// Remove existing condition for the previous selected event
const previousEventConditionIndex = ticketworkflowconditions.findIndex(cond => cond.eventName === selectedEvent);
if (previousEventConditionIndex !== -1) {
// Remove the existing condition
ticketworkflowconditions.splice(previousEventConditionIndex, 1);
console.log(`Removed existing condition for event: "${selectedEvent}"`);
}
// Clear existing field-related containers
newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());
// Create a new condition for the newly selected event
const newCondition = { eventName: newEvent, isEnabled: true, fields: {} };
ticketworkflowconditions.push(newCondition); // Push new condition
// Prepare new containers for fields and choices
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
newDropdownSet.appendChild(fieldNameContainer);
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
newDropdownSet.appendChild(choicesContainer);
// Create button container
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
newDropdownSet.appendChild(buttonContainer);
// Populate fields based on the new event
await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet, null, null);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
});
// Append the newDropdownSet to the eventContainer
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
}
Code Changes Explained:
Finding and Removing Existing Conditions:
The event change listener (eventSelect.addEventListener('fwChange', ...)) first finds the index of the existing event condition using findIndex based on the previous event's name.
If found, it removes that condition from the ticketworkflowconditions array using splice.
Creating and Adding a New Condition:
A new condition is created immediately after removing the previous one, ensuring only the current event's condition remains in the array.
The structure for fields and choices is then set up for the newly selected event.
Containers for Fields and Choices:
As specified, new containers for fields and choices will be instantiated each time a user changes the event.
Resulting Behavior:
Now, when you change from TicketCreate to TicketUpdate, the existing event condition for TicketCreate will be removed from ticketworkflowconditions, and a fresh condition for TicketUpdate will be created with its fields being set up anew. This ensures your application adheres to the expected data structure without duplicating event conditions.
async function addNewRule(eventName, workflowConditions) {
console.log("Existing Workflow Conditions:", workflowConditions);
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 = 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');
eventSelect.value = selectedEvent;
eventSelect.addEventListener('fwChange', async () => {
const newEvent = eventSelect.value;
// Remove existing condition for the previous event (if it exists)
ticketworkflowconditions = ticketworkflowconditions.filter(cond => cond.eventName !== selectedEvent);
// Now ensure to also remove any existing entry for the new event if it exists
ticketworkflowconditions = ticketworkflowconditions.filter(cond => cond.eventName !== newEvent);
// Create a new condition for the newly selected event
const newCondition = { eventName: newEvent, isEnabled: true, fields: {} };
ticketworkflowconditions.push(newCondition); // Add the new condition
// Clear existing field-related containers
newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
newDropdownSet.appendChild(fieldNameContainer);
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
newDropdownSet.appendChild(choicesContainer);
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
newDropdownSet.appendChild(buttonContainer);
// Populate fields based on the new event's context
await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet, null, null);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
});
// Append the newDropdownSet to the eventContainer
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
}
Key Changes Explained:
Clear Previous Condition:
The previous event condition for selectedEvent is removed using filter.
After that, any existing condition for the newly selected event (newEvent) is also filtered out.
Adding the New Condition:
After ensuring that no duplicate conditions exist for the newly selected event, we create and add a new condition.
Repopulate Fields:
Once a new condition is established, fields and other related configurations can be set up again.
Resulting Behavior:
With these changes in place, when you switch from one event to another, the previous event's condition will be effectively removed from the ticketworkflowconditions array, ensuring that you always have one instance per event. This should result in only one condition existing for each event type at any moment in time.
If you expect a particular behavior (like not allowing duplicate event conditions altogether), these modifications should satisfy that requirement. You can test the logic to confirm no conditions appear more than once in the array as you interact with the event dropdowns.
async function addNewRule(eventName, workflowConditions) {
console.log("Existing Workflow Conditions:", workflowConditions);
const ticketworkflowContainer = document.getElementById('ticketworkflow-container');
// Create event 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 = document.createElement('div');
newDropdownSet.classList.add('row', 'ticketworkflow-dropdown');
const selectedEvent = typeof eventName === 'string' ? eventName : '';
// Dropdown for event selection
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');
eventSelect.addEventListener('fwChange', async () => {
const newEvent = eventSelect.value;
// Check if we are changing to a different event
if (newEvent !== selectedEvent) {
// Remove condition for the previously selected event
ticketworkflowconditions = ticketworkflowconditions.filter(cond => cond.eventName !== selectedEvent);
console.log(`Removed existing condition for event: "${selectedEvent}"`);
// Clear existing field-related containers
newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());
// Ensure no existing entry for the new event if it exists
ticketworkflowconditions = ticketworkflowconditions.filter(cond => cond.eventName !== newEvent);
// Log the current conditions before adding the new one
console.log('Current Conditions after filtering:', JSON.stringify(ticketworkflowconditions, null, 2));
// Now create a new condition for the newly selected event
const newCondition = { eventName: newEvent, isEnabled: true, fields: {} };
ticketworkflowconditions.push(newCondition);
console.log(`Added new condition for: "${newEvent}"`, JSON.stringify(newCondition, null, 2));
// Create new containers for fields and choices
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
newDropdownSet.appendChild(fieldNameContainer);
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
newDropdownSet.appendChild(choicesContainer);
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
newDropdownSet.appendChild(buttonContainer);
// Populate fields based on the new event's context
await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet, null, null);
// Log the updated state of ticketworkflowconditions
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
}
});
// Append the newDropdownSet to the eventContainer
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
}
Key Points in the Updated Code:
Condition Filtering:
We immediately filter out the existing condition for the event being switched away from and log the action.
Then, we also filter out any existing condition for the newly selected event before creating the new condition.
Enhanced Logging:
We log the current state of ticketworkflowconditions right after filtering and before adding the new condition to ensure that you can track exactly what is happening to the array.
Conditional State Management:
The code ensures that the event selection changes only when the selected event actually differs from the previous selection.
Testing
After implementing these changes, please test the functionality again:
Select an event (e.g., TicketCreate).
Configure any fields as needed.
Switch to another event (e.g., TicketUpdate).
Verify that ticketworkflowconditions only contains the newly selected event condition and that the condition for the previously selected event is removed.
This approach should prevent unwanted or duplicated entries in the ticketworkflowconditions array.
async function addNewRule(eventName, workflowConditions) {
console.log("Existing Workflow Conditions:", workflowConditions);
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 = 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');
eventSelect.addEventListener('fwChange', async () => {
const newEvent = eventSelect.value;
// Remove existing condition for the previous event if it exists
if (selectedEvent && selectedEvent !== newEvent) {
ticketworkflowconditions = ticketworkflowconditions.filter(cond => cond.eventName !== selectedEvent);
console.log(`Removed existing condition for event: "${selectedEvent}"`);
}
// Ensure no existing entry for the new event if it exists
ticketworkflowconditions = ticketworkflowconditions.filter(cond => cond.eventName !== newEvent);
// Log the current conditions before adding the new one
console.log('Current Conditions after filtering:', JSON.stringify(ticketworkflowconditions, null, 2));
// Now create a new condition for the newly selected event
const newCondition = { eventName: newEvent, isEnabled: true, fields: {} };
ticketworkflowconditions.push(newCondition);
console.log(`Added new condition for: "${newEvent}"`, JSON.stringify(newCondition, null, 2));
// Clear existing field-related containers
newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());
// Create new containers for fields and choices
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
newDropdownSet.appendChild(fieldNameContainer);
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
newDropdownSet.appendChild(choicesContainer);
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
newDropdownSet.appendChild(buttonContainer);
// Populate fields based on the new event's context
await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet, null, null);
// Log the updated state of ticketworkflowconditions
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
});
// Append the newDropdownSet to the eventContainer
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
}
Key Logic Changes
Filtering Logic:
On the event change (fwChange), the code now filters out not only the previous event (selectedEvent) but also ensures that the new event does not already exist, confirming that no duplicates are created.
Logging:
Enhanced logging statements to show exactly what the conditions look like at each critical step.
Testing the Logic
Initial Setup: Start with the initial condition, like TicketCreate.
Change Events: After adding fields and choices to TicketCreate, change it to TicketCreateandUpdate or TicketUpdate.
Check the Array: After each change, check the contents of ticketworkflowconditions. Only the current event should remain.
Why Condition May Still Append
If you still experience issues where conditions keep appending, please ensure:
Single Instance of the Event Listener: Make sure the eventSelect listener is not being added multiple times. You can do this by verifying the structure where addNewRule is called.
Resetting Container States Before Adding: Make certain to clear any field containers when changing events so that state does not carry over.
Global State Management: If ticketworkflowconditions is being manipulated elsewhere in your code, ensure no other pieces are adding or modifying it unexpectedly.
Please re-test after making these changes and verify the logging outputs to ensure that it behaves as expected.
The code uses findIndex to locate the index of the existing condition for the previously selected event. If it’s found, it’s removed from the ticketworkflowconditions array. This ensures that no duplicate entries are left in the array.
Creating the New Condition:
After ensuring that the previous condition has been removed, it creates and pushes a new condition for the newly selected event.
Clear State:
Existing field containers are cleared before creating new ones, ensuring a fresh state for event interactions.
Immediate Logging:
Detailed logging tracks what happens to the conditions, making it easier to see that the new condition is replacing the old one.
Testing the Functionality
Select an Event: Start with TicketCreate and add a field or choice to it.
Switch Events: Change the dropdown to TicketCreateandUpdate.
Check Conditions: Verify that the console logs show only one condition for TicketCreateandUpdate and that the previous condition for TicketCreate is removed.
Conclusion
With these changes, when you select a new event from the dropdown, the old one should be replaced in the ticketworkflowconditions array, avoiding duplicate entries. This should meet your functionality requirement of having only one event condition present at a time.
async function addNewRule(eventName, workflowConditions) {
console.log("Existing Workflow Conditions:", workflowConditions);
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 = 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');
eventSelect.addEventListener('fwChange', async () => {
const newEvent = eventSelect.value;
// Find the index of the existing condition for the previously selected event
const previousEventIndex = ticketworkflowconditions.findIndex(cond => cond.eventName === selectedEvent);
// If we found the previous event in the array, remove it
if (previousEventIndex !== -1) {
ticketworkflowconditions.splice(previousEventIndex, 1);
console.log(`Removed existing condition for event: "${selectedEvent}"`);
}
// Clear existing field-related containers
newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());
// Create a new condition for the newly selected event
const newCondition = { eventName: newEvent, isEnabled: true, fields: {} };
ticketworkflowconditions.push(newCondition);
console.log(`Added new condition for: "${newEvent}"`);
// Create new containers for fields and choices
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
newDropdownSet.appendChild(fieldNameContainer);
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
newDropdownSet.appendChild(choicesContainer);
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
newDropdownSet.appendChild(buttonContainer);
// Populate fields based on the new event's context
await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet, null, null);
// Log the updated state of ticketworkflowconditions
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
});
// Append the newDropdownSet to the eventContainer
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
}
Key Changes Explained
Finding Index with findIndex():
We use ticketworkflowconditions.findIndex(cond => cond.eventName === selectedEvent) to find the index of the existing condition that matches the currently selected event.
Removing Condition with splice():
If previousEventIndex is not -1 (i.e., the event exists), we remove it using ticketworkflowconditions.splice(previousEventIndex, 1).
Logging:
Detailed logging is provided to confirm when an event is removed and when a new condition is added.
Testing the Solution
Select an event and add fields/choices.
Change the event to another one.
Check the contents of ticketworkflowconditions to ensure the previously selected event has been removed and only the newly selected event remains.
This should prevent unwanted duplicates and ensure that only the currently selected event is represented in the ticketworkflowconditions array.
async function addNewRule(eventName, workflowConditions) {
console.log("Existing Workflow Conditions:", workflowConditions);
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 = 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');
eventSelect.addEventListener('fwChange', async () => {
const newEvent = eventSelect.value;
// Find the index of the condition for the previously selected event
const previousEventIndex = ticketworkflowconditions.findIndex(cond => cond.eventName === selectedEvent);
// If an existing condition is found for the previously selected event, remove it
if (previousEventIndex !== -1) {
ticketworkflowconditions.splice(previousEventIndex, 1);
console.log(`Removed existing condition for event: "${selectedEvent}"`);
}
// Also ensure to remove any existing entry for the newly selected event
const newEventIndex = ticketworkflowconditions.findIndex(cond => cond.eventName === newEvent);
if (newEventIndex !== -1) {
ticketworkflowconditions.splice(newEventIndex, 1);
console.log(`Removed existing condition for event: "${newEvent}" before adding the new one.`);
}
// Clear existing field-related containers
newDropdownSet.querySelectorAll('.field-name-container, .choices-container, .button-container').forEach(container => container.remove());
// Create a new condition for the newly selected event
const newCondition = { eventName: newEvent, isEnabled: true, fields: {} };
ticketworkflowconditions.push(newCondition);
console.log(`Added new condition for: "${newEvent}"`);
// Create new containers for fields and choices
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
newDropdownSet.appendChild(fieldNameContainer);
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
newDropdownSet.appendChild(choicesContainer);
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
newDropdownSet.appendChild(buttonContainer);
// Populate fields based on the new event's context
await fieldschoosingvalues(newEvent, fieldNameContainer, choicesContainer, buttonContainer, newDropdownSet, null, null);
// Log the updated state of ticketworkflowconditions
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
});
// Append the newDropdownSet to the eventContainer
eventContainer.appendChild(newDropdownSet);
ticketworkflowContainer.appendChild(eventContainer);
}
Important Changes and Clarifications
Finding and Removing Conditions:
The previous event is located using findIndex(). If it exists, it's removed from the array using splice().
Before adding a new condition, we also check if a condition already exists for the newly selected event and remove it as well using the same find-and-remove logic.
Clearing Existing Containers:
Whenever an event is changed, all related fields and containers are cleared, ensuring there are no remnants from previous event configurations.
Logging:
Detailed logging statements help clarify when events are being removed and new conditions are being created.
Testing After Changes
Select an Event: Start with TicketCreate, configure its fields, and log the state.
Switch Events: Change the dropdown to TicketCreateandUpdate or TicketUpdate.
Check ticketworkflowconditions: Verify that only the current condition exists in the array and that the previous conditions are removed completely.
By implementing these changes, the application should now replace the old event condition with the new one, adhering to the required functionality.