To simplify the structure of the provided JSON data for better implementation, you can follow a more streamlined approach. Here’s a simplified version:
Instead of using an array of objects for fields, a single object is used. This reduces redundancy and improves readability. Field names are keys, and their values are directly assigned.
This simplification maintains clarity and conciseness while preserving the original data structure and intent.
User
any better
Assistant
To further improve and simplify the structure while maintaining clarity, consider abstracting common elements and focusing on minimalism. Here's an optimized version:
Encapsulate events in a single array, eliminating the need for repeated nesting.
Flatten the Structure:
Directly associate each event with its properties, such as priority and status, for simplicity.
Remove Redundant Layers:
Omitting unnecessary hierarchy levels like "combinations" and "fields" when they aren't needed for contextual separation.
This structure is straightforward, reducing verbosity while clearly conveying the essential data. If the isEnabled property is always true, you can omit it entirely to streamline further.
User
if it contains multiple
Assistant
If the JSON structure needs to support multiple combinations per event and possibly other configurations, you can maintain flexibility while still keeping it organized. Here’s a potential approach:
Maintain an array of events so that multiple events can be easily added and handled.
Combinations:
Keep the combinations array within each event to support multiple configurations.
Each combination contains the properties such as isEnabled, priority, and status for different setups.
Streamlined Data Structure:
Flatten the fields inside each combination for clarity, ensuring each combination is self-contained and easy to understand.
This structure maintains flexibility to include multiple settings for each event and ensures that each configuration is clearly defined and easily manageable.
User
simplify this with the same structure
Assistant
To simplify the given structure while maintaining the capacity to handle multiple combinations per event, we can streamline the JSON by keeping only the necessary elements without unnecessary nesting. Here's a simplified version:
Each combination now contains all properties as flat key-value pairs, reducing nesting and improving readability.
Minimal Key Usage:
The use of minimal and meaningful keys ensures that each part of the data is clear and concise.
This structure keeps it simple by eliminating unnecessary nesting, while still allowing for multiple combinations per event. Each combination is now a simple object within the combinations array, ensuring ease of access and manipulation.
User
any better
Assistant
To further simplify the structure while retaining clarity and functionality, you might ensure that each data element serves a clear purpose, minimizing any redundancy or nesting that doesn't add value. Here's an even more straightforward version:
The entire structure is now a top-level array, which directly contains event objects, eliminating the need for an additional wrapper ("events" object).
Descriptive Key Names:
Simplified key names like "event" instead of "name" for clarity.
Consistency in Keys:
One-word keys like "enabled" enhance readability and maintain consistency with JSON naming conventions.
Minimized Complexity:
Each event's details are directly accessible within a simple structure, minimizing the layers one must parse through.
This setup is designed to keep things as straightforward as possible while maintaining the flexibility required for multiple combinations per event.
User
keep enable outer
Assistant
To keep the isEnabled attribute outside of individual combinations while still enabling multiple combinations per event, you can position it at the event level. This way, it's clear that the setting applies to the entire event. Here's how you can structure it:
The enabled status now applies to the entire event, indicating whether the event is active or not.
Combinations as Simple Objects:
Each combination within an event is a simple object with priority and status attributes.
Clear and Structured Hierarchy:
The structure is organized so you can quickly understand which configurations belong to each event, and whether the event is enabled as a whole.
This design is straightforward and aligns with the need to manage multiple configurations under each event while keeping the enabling logic at a higher, event-level context.
User
async function createEventDropdownSet(eventName) {
console.log("Creating Event Dropdown");
Based on the function createEventDropdownSet that generates a dropdown set with event options, you can create a corresponding JSON structure that captures the events and their potential combinations. The JSON will reflect the events as mentioned in the dropdown options. Here's how you can structure it:
Events: The JSON structure includes three events corresponding to the dropdown options: "Ticket Create," "Ticket Update," and "Ticket Create and Update."
Enabled: Assume all events are enabled (true) by default for illustration, but you can set this based on your specific application logic.
Combinations: Each event has placeholder combinations, which you can modify to fit the actual business logic or rules you have in place.
This JSON represents a configurable setup where each event can control different combinations of priorities and statuses, allowing for a flexible and dynamic configuration system that aligns with what the dropdown options provide.
this is the correct i needed. now if i choose another set of priority and status how it will add to json
Assistant
If you need to dynamically add combinations of "Priority" and "Status" to the JSON structure based on user selections from a dropdown or a form, you'll want to create a function that captures these selections and updates the JSON accordingly. Here's a basic approach to achieving that:
Assuming you have a function or mechanism to add new combinations:
javascript
// Example JSON structure.
let events = [
{
"eventName": "Ticket Create",
"combinations": [
{
"isEnabled": true,
"fields": {
"Priority": 2,
"Status": 3
}
}
]
},
{
"eventName": "Ticket Update",
"combinations": [
{
"isEnabled": true,
"fields": {
"Priority": 4,
"Status": 4
}
}
]
}
];
// Function to add a new combination to a specific event.
function addCombinationToEvent(eventName, priority, status, isEnabled = true) {
// Find the event by name.
const event = events.find(e => e.eventName === eventName);
if (event) {
// Add the new combination to the event's combinations.
event.combinations.push({
"isEnabled": isEnabled,
"fields": {
"Priority": priority,
"Status": status
}
});
} else {
// If the event doesn't exist, you could create it.
events.push({
"eventName": eventName,
"combinations": [
{
"isEnabled": isEnabled,
"fields": {
"Priority": priority,
"Status": status
}
}
]
});
}
}
// Example usage:
addCombinationToEvent("Ticket Create", 5, 6);
addCombinationToEvent("Ticket Update", 1, 2);
addCombinationToEvent("New Event", 3, 4);
// Logging the updated JSON structure.
console.log(JSON.stringify(events, null, 2));
The JSON provided has a structural issue: each event has a repeated "combinations" key, which is not valid JSON. You need a single "combinations" array for each event that includes all the combinations as separate objects within that array. Here's the corrected version:
Instead of having multiple "combinations" keys, this corrected JSON structure has a single "combinations" array where each combination is clearly defined as an object within the array.
Logical Nesting:
Each event (Ticket Create and Ticket Update) contains its respective combinations, ensuring clarity and proper JSON syntax.
This fix ensures your JSON is both syntactically correct and logically organized according to JSON standards.
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
code
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
Assistant
To achieve the desired behavior of updating the ticketworkflowconditions object such that changing a field does not result in multiple fields within the same combination (i.e., each combination should only have one field name active at a time), you need to adjust the logic responsible for updating or replacing the combinations.
The logic should:
Ensure Uniqueness per Field Name: When a field is chosen, ensure that the previous field is removed or replaced.
Manage Combinations Properly: Address how combinations are managed to ensure they reflect only the relevant fields.
Here's how you might adjust the relevant part of your showingitschoices function:
To achieve the behavior where a single event can only have one active field in its combinations at any given time, you need to modify the logic such that each change replaces the entirety of a previous combination instead of merely updating parts of it. This approach ensures that if a new field is selected, all previous fields are cleared or overridden.
You need to ensure that the logic effectively resets the structure for the event. Here's a refined approach:
To achieve the desired outcome where modifying a field effectively replaces the entire combination for a given event, the logic should ensure that each new field selection completely resets the combinations. Here's an approach to do this in your code:
Adjusted Code
javascript
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize the ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Clear all existing combinations for this event to only keep the latest choice
ticketworkflowconditions[selectedEventValue].combinations = [
{
isEnabled: true, // Default to enabled
fields: {
[selectedFieldName]: selectedChoiceId
}
}
];
console.log(`Set new combination for event ${selectedEventValue}, field ${selectedFieldName} with choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-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);
}
// Ensure the togglecontainer exists or create it
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container', 'ml-auto'); // Apply margin-left auto to align it right
container.appendChild(togglecontainer);
}
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;
}
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
Assistant
To implement a functionality where clicking an "Add" button within the showingitschoices function creates another set of ticket fields and choices, and each additional set contains a "Delete" button, you can use the following approach:
Create an "Add" Button: Include a button in the UI to add a new set of dropdowns.
Handle the "Add" Button Click: On clicking the "Add" button, instantiate another set of dropdowns for selection.
Include a "Delete" Button: Each new set contains a "Delete" button to allow removal of that particular set.
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
Assistant
To achieve the desired behavior where new selections are merged into existing combinations instead of replacing them, you'll need to modify the logic that handles the storage and management of ticketworkflowconditions.
When the "Add" button is clicked and another field and choice are selected, the new selection should be added to the existing combination rather than starting a new one. Here is how you can implement this:
// Create the dropdown for choices
const choicesDropdown = document.createElement('fw-select');
choicesDropdown.classList.add('choices-dropdown');
choicesDropdown.setAttribute('label', {selectedFieldName});
choicesDropdown.setAttribute('hint-text', 'Select singular option');
Assistant
To achieve the desired functionality where selecting an additional field and choice should be merged into the existing combination for the same event, you need to update the logic in showingitschoices. Specifically, instead of clearing and reinitializing the combinations array for the event, you should update the existing combination's fields object with the newly selected field and choice.
Here's a reworked version of your function to accomplish this:
javascript
User
async function createEventDropdownSet(eventName) {
console.log("Creating Event Dropdown");
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-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);
}
// Ensure the togglecontainer exists or create it
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container', 'ml-auto'); // Apply margin-left auto to align it right
container.appendChild(togglecontainer);
}
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(Event changed to: ${selectedEventValue});
code
Assistant
To add validation ensuring that a field, choice, or event must be selected before proceeding, you can implement simple checks before executing the critical parts of your functions. When trying to perform an action, such as adding a new choice or field, ensure that the selections required for those actions are actually made. You can display alerts or messages in the console to notify users if they need to select something before proceeding.
Here's how you can integrate these validations into your existing code:
Updated Code with Validation
javascript
User
// showErrorToast('Status field not found in Dropdown 1');
add this too
Assistant
To incorporate a function like showErrorToast that displays an error message, you'll need to create or use a UI library that handles toasts, notifications, or alerts. I'll show you a basic way to add this functionality into the code. If you're using a UI framework, you can replace the showErrorToast function logic with your framework's method for displaying messages.
Here is how you might integrate the showErrorToast function into your existing code:
Define showErrorToast Function: Create a simple implementation to display error messages, typically as overlays or pop-up messages on the screen.
Integrate the Error Toast with Validation Logic: Include calls to showErrorToast where validations fail.
Here's how it could be done:
html
<!-- Include this in your HTML, CSS, or as part of a consistent styling setup -->
<style>
.toast {
visibility: hidden;
max-width: 50%;
margin: auto;
background-color: #f44336; /* Red */
color: white;
text-align: center;
border-radius: 2px;
position: fixed;
z-index: 1;
left: 0; right:0;
bottom: 30px;
font-size: 17px;
}
.toast.show {
visibility: visible;
-webkit-animation: fadein 0.5s, fadeout 0.5s 4.5s;
animation: fadein 0.5s, fadeout 0.5s 4.5s;
}
@-webkit-keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@-webkit-keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
@keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
</style>
<div id="toast" class="toast"></div>
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
Assistant
To incorporate a toggle switch into your existing layout and ensure it's appropriately positioned, you can create an <fw-toggle> element and append it to the togglecontainer. The implementation will include checking if the togglecontainer exists and adding the toggle inside it. I'll also ensure it has a margin to offset it from the right as requested.
Here is how you can integrate this into your initializeEventDropdown function:
Updated Function with Toggle Integration
javascript
async function initializeEventDropdown(container, fieldMappings = null) {
const eventSelect = container.querySelector('.event-name-dropdown');
console.log(`initializeEventDropdown - Initial selected event: ${eventSelect.value}`);
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
// Ensure containers exist
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);
}
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
container.appendChild(buttonContainer);
}
// Ensure the togglecontainer exists or create it
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto'; // Align it to the right with auto margin
togglecontainer.style.marginRight = '5px'; // Offset of 5 from the right
container.appendChild(togglecontainer);
}
// Create and append the toggle to the toggle container
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.setAttribute('checked', ''); // Initial checked state
togglecontainer.appendChild(toggleSwitch);
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(`Event changed to: ${selectedEventValue}`);
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
}
User
async function createEventDropdownSet(eventName) {
console.log("Creating Event Dropdown");
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
// Ensure the togglecontainer exists or create it
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto'; // Align it to the right with auto margin
togglecontainer.style.marginRight = '5px'; // Offset of 5 from the right
container.appendChild(togglecontainer);
}
// Create and append the toggle to the toggle container
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.setAttribute('checked', ''); // Initial checked state
togglecontainer.appendChild(toggleSwitch);
Assistant
To handle the toggle for setting the isEnabled property, you can update the existing logic to incorporate toggle state changes. This requires listening for changes on the toggle switch and updating the isEnabled value accordingly.
Here's how you can implement this logic:
Updated Code with Toggle Handling
javascript
User
async function createEventDropdownSet(eventName) {
console.log("Creating Event Dropdown");
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
// Ensure the togglecontainer exists or create it
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto'; // Align it to the right with auto margin
togglecontainer.style.marginRight = '5px'; // Offset of 5 from the right
container.appendChild(togglecontainer);
}
// Create and append the toggle to the toggle container
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.setAttribute('checked', ''); // Initial checked state
togglecontainer.appendChild(toggleSwitch);
Assistant
To make every dropdown unaccessible when the toggle is off, you can dynamically set the disabled attribute on each dropdown based on the toggle's state. This involves updating the event listener for the toggle switch to enable or disable the dropdowns.
Here's how you can achieve that:
Updated Code
javascript
User
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto'; // Align it to the right with auto margin
togglecontainer.style.marginRight = '5px'; // Offset of 5 from the right
container.appendChild(togglecontainer);
}
make toggle little bit downl
Assistant
To slightly lower the position of the toggle in your container, you can add a marginTop style to the togglecontainer. Adjusting the marginTop value will move the toggle downwards within its parent container. Here's how you can modify the code:
Adjusted Code to Lower the Toggle
javascript
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto'; // Align it to the right with auto margin
togglecontainer.style.marginRight = '5px'; // Offset of 5 from the right
togglecontainer.style.marginTop = '15px'; // Adjust the position downwards
container.appendChild(togglecontainer);
}
Explanation:
marginTop: The addition of togglecontainer.style.marginTop = '15px'; shifts the toggle container slightly downward within its parent. You can tweak the 15px value to fit your design needs.
Consistent Positioning: Other margin properties (marginLeft and marginRight) remain unchanged to maintain alignment with previous positioning logic.
This change allows you to control the vertical spacing of the toggle, creating a more aesthetically pleasing layout and potentially improving the usability of the user interface. Adjust the margin value further if you need more or less spacing.
User
program is working correctly. now add this feature.
if i have choosed already values for 1st set of combo
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
To implement the feature where users can create additional combinations for the same event and append them to ticketworkflowconditions, you need to modify the logic when adding new combinations. The updated process will allow creating and storing multiple combinations for a single event without overwriting existing ones.
Here's the updated code with the feature integrated:
Updated Code
javascript
User
program is working correctly. now add this feature.
if i have choosed already values for 1st set of combo
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
To implement the feature where a new combination for the same event is added to the existing list, you need to ensure that your code allows for multiple combinations under a single event. This involves appending a new combination with the selected fields and values, rather than modifying an existing one.
Here's how you can modify your existing methods to add this functionality:
Changes in showingitschoices
javascript
User
not working
program is working correctly. now add this feature.
if i have choosed already values for 1st set of combo
make changes (dont remove existing working methods) add this method
Assistant
To effectively add a new combination for the same event without disrupting existing entries, we need to ensure that each new set of field choices results in a new combination being added to the combinations array. This involves making sure that a new combination is correctly initialized and added whenever a set of fields is chosen.
Key Steps to Implement the Feature:
Initialize New Combination: Every time a set of selections is made, initialize a new object containing fields and isEnabled.
Push the New Combination: Add this new combination to the existing list of combinations for the event.
Here's how you can integrate these changes into the showingitschoices function:
javascript
User
understand this i choosed ticketcreate and its choices. Now the json will look like this .
if i want another combo with same event, i will click addnewrule and choose ticketcreate, then choosing field and choices. it should add as new combination . now the json should view like this.
To achieve the desired behavior where clicking "Add New Rule" allows you to create a new combination for the same event, we need to ensure that this action initializes a new combination set without interfering with existing ones. Here's a step-by-step approach to handle this user interaction and update your JSON structure accordingly:
Implementation Steps:
Initialize New Combination Set: When you click "Add New Rule," a new combination set for the selected event is prepared. If you select "TicketCreate," a new combination array is invoked for subsequent field selections.
Field Selections: Allow selections of multiple fields and their respective choices for the newly created set only.
Appending to Combinations: Upon validating the selections, the new combination is appended to the existing combinations array of the relevant event within your JSON data model.
Here's how you can update functions to support this:
Updated Code
javascript
User
understand this i choosed ticketcreate and its choices. Now the json will look like this .
if i want another combo with same event, i will click addnewrule and choose ticketcreate, then choosing field and choices. it should add as new combination . now the json should view like this.
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
To achieve the desired feature, where clicking "Add New Rule" will add a new combination for the same event without replacing existing ones, you'll need to adjust the logic to ensure each set of field and choice selections results in a new combination being added to the combinations array.
Here's how you can modify your project to incorporate this functionality:
Key Steps:
Allow Selection of Event with "Add New Rule": Enable users to create a new combination with the same event choice.
Store Each Combination Separately: Ensure that each set of selected fields creates and appends a new combination object to the existing combinations array.
Here's an updated implementation:
Updated Code:
javascript
User
understand this i choosed ticketcreate and its choices. Now the json will look like this .
if i want another combo with same event, i will click addnewrule and choose ticketcreate, then choosing field and choices. it should add as new combination . now the json should view like this.
Note : using addNewrule on that if i choose same event then it should work as like this
To achieve the desired functionality where clicking "Add New Rule" and selecting the same event allows you to add a new combination, we need to ensure that each new combination is appended correctly. This involves ensuring selections are managed separately for each rule, and the logic supports appending rather than overwriting.
Here's a clean implementation that incorporates this functionality:
Implementation:
Add a New Combination Button: Use the "Add New Rule" to initialize the process for selecting a new combination for the same event.
Separate Combination Logic: Manage each combination independently to ensure selections are not mixed up.
Here's how you can integrate these changes:
Modified Code:
javascript
User
why add new combination button that should not be there
understand this i choosed ticketcreate and its choices. Now the json will look like this .
if i want another combo with same event, i will click addnewrule and choose ticketcreate, then choosing field and choices. it should add as new combination . now the json should view like this.
I understand now. You don't want an "Add New Combination" button within the same configuration. Instead, you want to have separate mechanisms for initially setting a rule and later adding more rules for the same event via a different setup (like clicking "Add New Rule"). Let's focus on ensuring that when you reselect "TicketCreate" and choose different fields and values, it creates an additional combination.
Here's how you can ensure this happens:
Updated Process:
Primary Event Dropdown: Allow initial selection where the user sets up one combination for an event.
Add New Rule (External Trigger): Use an external mechanism (like a global "Add New Rule" button or link outside of the function) to append more combinations.
Here's how the code can support this functionality:
Code Implementation:
javascript
Not yet included in a published release.
Explanation:
Search and Insert:
The function addCombinationToEvent searches for the event using the event name.
If the event is found, it adds a new combination to the event's combinations array.
If the event is not found, it creates a new event entry with the provided combination.
Flexible Parameters:
The function takes in parameters for eventName, priority, status, and optionally isEnabled, making it easy to handle different user inputs.
Maintain Original Structure:
The function preserves the original JSON structure while allowing for dynamic updates to its contents.
With this approach, you can update your JSON structure based on user selections from a dropdown or other inputs, ensuring your data model remains current with user interactions.
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Flag to check if the field exists
let fieldUpdated = false;
// Check if the field already exists in combinations, and update it
for (let combination of ticketworkflowconditions[selectedEventValue].combinations) {
if (combination.fields.hasOwnProperty(selectedFieldName)) {
// If field exists, replace the value
combination.fields[selectedFieldName] = selectedChoiceId;
fieldUpdated = true;
console.log(`Updated ${selectedFieldName} with choice ID ${selectedChoiceId} for event ${selectedEventValue}`);
break;
}
}
// If the field was not found, create a new combination
if (!fieldUpdated) {
// First, check if the field is already in another combination
let combinationExistsForAnotherField = false;
for (let combination of ticketworkflowconditions[selectedEventValue].combinations) {
// Remove the old field if found (before adding the new one)
if (combination.fields.hasOwnProperty(selectedFieldName)) {
delete combination.fields[selectedFieldName];
combinationExistsForAnotherField = true;
}
}
// Add new combination with the selected field and value
let newCombination = {
isEnabled: true, // Default to enabled
fields: {
[selectedFieldName]: selectedChoiceId
}
};
if (combinationExistsForAnotherField) {
console.log(`Field replaced in combination for event ${selectedEventValue}`);
} else {
ticketworkflowconditions[selectedEventValue].combinations.push(newCombination);
console.log(`Created new combination for event ${selectedEventValue}, field ${selectedFieldName} with choice ID ${selectedChoiceId}`);
}
}
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Remove any existing combination for the selected field
for (let combination of ticketworkflowconditions[selectedEventValue].combinations) {
if (combination.fields.hasOwnProperty(selectedFieldName)) {
// Remove previous field entry before updating
delete combination.fields[selectedFieldName];
}
}
// Determine if there is an existing combination that should be updated
let combinationUpdated = false;
for (let combination of ticketworkflowconditions[selectedEventValue].combinations) {
if (Object.keys(combination.fields).length === 0) {
combination.fields[selectedFieldName] = selectedChoiceId;
combinationUpdated = true;
console.log(`Updated ${selectedFieldName} with choice ID ${selectedChoiceId} for event ${selectedEventValue}`);
break;
}
}
// If no existing combination was updated, create a new combination
if (!combinationUpdated) {
ticketworkflowconditions[selectedEventValue].combinations.push({
isEnabled: true, // Default to enabled
fields: {
[selectedFieldName]: selectedChoiceId
}
});
console.log(`Created new combination for event ${selectedEventValue}, field ${selectedFieldName} with choice ID ${selectedChoiceId}`);
}
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
Key Adjustments:
Field Removal Before Update: Before adding a new field to a combination, the function removes any existing field entries related to the current selection. This ensures that each combination holds only a single field at any time.
Check for Empty Combinations: The logic identifies combinations with no fields left after removal, allowing these to be updated with the new selections.
This implementation ensures that each change made in the dropdown will result in only one active field per combination in ticketworkflowconditions, aligning with your requirements.
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Clear existing combinations for this event to ensure only one active field at a time
ticketworkflowconditions[selectedEventValue].combinations = [];
// Add the new combination for the selected field
ticketworkflowconditions[selectedEventValue].combinations.push({
isEnabled: true, // Default to enabled
fields: {
[selectedFieldName]: selectedChoiceId
}
});
console.log(`Set new combination for event ${selectedEventValue}, field ${selectedFieldName} with choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
Key Adjustments:
Clear Combinations Array: Before adding a new combination, clear the combinations array for the selected event to ensure that only the current field is active. This replaces any previous combinations with a new one.
Single Active Field Logic: This guarantees that selecting a new field completely replaces any existing field within the combinations for that event, maintaining a one-field-per-combination state.
This approach will ensure that each selected field will replace the entire previous setup, leading to a JSON structure like the one you requested. Each time you select a new field or value, it will reset the combinations for that particular event.
Key Adjustments:
Reset Combinations: The line ticketworkflowconditions[selectedEventValue].combinations = [...] effectively clears previous combinations when a new choice is made, ensuring the JSON maintains only the current field and value.
Simple Array Assignment: Assigning the combinations array to a new array with a single object ensures that all previous data is removed and replaced with the latest user selection.
Exclusive Handling: This setup guarantees that only the field currently selected is reflected in the JSON, aligning with your goal to reset the combination whenever the field changes.
This approach ensures that your JSON only contains the latest selected field and its associated value, achieving the desired behavior of having a single active setting for each event.
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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("getFieldnamesfrom1stapi called with an undefined selectedEventValue.");
return;
}
console.log(Initializing field dropdown for event ${selectedEventValue}, field: ${selectedFieldName});
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
code
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Clear existing combinations for this event to ensure only one active field at a time
ticketworkflowconditions[selectedEventValue].combinations = [];
// Add the new combination for the selected field
ticketworkflowconditions[selectedEventValue].combinations.push({
isEnabled: true, // Default to enabled
fields: {
[selectedFieldName]: selectedChoiceId
}
});
console.log(`Set new combination for event ${selectedEventValue}, field ${selectedFieldName} with choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
in this, on showing showingits choices, add a button Add Button to the container , when clicking add it should create another set of ticket fields and choices
additionaldropdown should only have Delete button only
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Add an "Add" button to the button container
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Handle the "Add" button click
addButton.addEventListener('click', () => {
createAdditionalDropdowns(container);
});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Clear existing combinations for this event to ensure only one active field at a time
ticketworkflowconditions[selectedEventValue].combinations = [];
// Add the new combination for the selected field
ticketworkflowconditions[selectedEventValue].combinations.push({
isEnabled: true, // Default to enabled
fields: {
[selectedFieldName]: selectedChoiceId
}
});
console.log(`Set new combination for event ${selectedEventValue}, field ${selectedFieldName} with choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container', 'mt-3');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
Key Elements:
Add Button: The Add button allows users to add additional field-choice sets.
Dynamic Dropdowns:createAdditionalDropdowns dynamically creates and appends new dropdowns and a delete button to the container for further fields and choices.
Delete Button: Each new set includes a Delete button that removes the complete set of containers, ensuring that users can manage their input configurations fluently.
Event Integrity: By handling each specific dropdown field set separately and ensuring the event and associated data are preserved, consistency in user selections is maintained across multiple sets.
This solution enhances flexibility and provides functionality for managing multiple setups of ticket fields and choices.
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Clear existing combinations for this event to ensure only one active field at a time
ticketworkflowconditions[selectedEventValue].combinations = [];
// Add the new combination for the selected field
ticketworkflowconditions[selectedEventValue].combinations.push({
isEnabled: true, // Default to enabled
fields: {
[selectedFieldName]: selectedChoiceId
}
});
console.log(`Set new combination for event ${selectedEventValue}, field ${selectedFieldName} with choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
this is the initial at first filed and choice are selected. now if i want to add another field using add and choosing field and choices in the same event or same conbo /set . now it should be like this
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Add an "Add" button to the button container
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Handle the "Add" button click
addButton.addEventListener('click', () => {
createAdditionalDropdowns(container);
});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Determine if a combination already exists
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// Create a new combination if none exist
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Add or update the field in the existing combination
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container', 'mt-3');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
Key Changes:
Maintain Existing Combinations: The logic now checks if an existing combination already exists for the selectedEventValue. It either uses the existing combination or initializes a new one as required.
Merge Choices: New field and choice selections are merged into an existing combination, ensuring multiple fields can coexist within a single combination per event.
Simplified Updates: Each field update modifies the fields object of the existing combination directly, merging new fields with existing ones instead of starting afresh.
This code should now allow additional fields and choices to be added to an existing event's combination, effectively merging into the current setup as you specified.
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Clear existing combinations for this event to ensure only one active field at a time
ticketworkflowconditions[selectedEventValue].combinations = [];
// Add the new combination for the selected field
ticketworkflowconditions[selectedEventValue].combinations.push({
isEnabled: true, // Default to enabled
fields: {
[selectedFieldName]: selectedChoiceId
}
});
console.log(Set new combination for event ${selectedEventValue}, field ${selectedFieldName} with choice ID ${selectedChoiceId});
this is the initial at first filed and choice are selected. now if i want to add another field using add and choosing field and choices in the same event or same conbo /set . now it should be like this
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Add an "Add" button to the button container
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Handle the "Add" button click
addButton.addEventListener('click', () => {
createAdditionalDropdowns(container);
});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Get the existing combination or create a new one
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// If no existing combination, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the existing combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
Explanation:
Preservation of Combinations:
The code checks if there is already a combination for the selected event. If not, it initializes one. This way, it does not override the existing fields.
Field and Choice Merging:
The function directly modifies the fields of the existing combination by adding or updating the selected field and choice.
Logical Flow for Additional Fields:
Clicking "Add" and selecting a new field and choice will now merge these selections into the single existing combination, rather than replacing it.
Adjust this script in your environment, ensuring the createAdditionalDropdowns function is similarly adapted to support multiple fields and choices as appropriate. This setup maintains a single active combination per event while allowing multiple fields within that combination.
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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("getFieldnamesfrom1stapi called with an undefined selectedEventValue.");
return;
}
console.log(Initializing field dropdown for event ${selectedEventValue}, field: ${selectedFieldName});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Get the existing combination or create a new one
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// If no existing combination, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the existing combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
add validation for each (event, field , choices ) havent choosed
Validation Messages: Console error messages are added to inform the user when required selections are missing.
Field and Choice Validation: Ensure that both fields and choices are selected before updates.
Event Select Validation: The event selection is confirmed at various stages to ensure that operations depend on a valid event being chosen.
This setup helps ensure that users make necessary selections before advancing any actions that depend on user input, reducing errors and improving the flow of interaction.
// Function to display error toast
function showErrorToast(message) {
const toastElement = document.getElementById('toast');
toastElement.textContent = message;
toastElement.className = 'toast show';
setTimeout(() => {
toastElement.className = toastElement.className.replace('show', '');
}, 5000); // Remove the show class after 5 seconds
}
async function initializeEventDropdown(container, fieldMappings = null) {
const eventSelect = container.querySelector('.event-name-dropdown');
console.log(`initializeEventDropdown - Initial selected event: ${eventSelect.value}`);
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-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);
}
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
container.appendChild(buttonContainer);
}
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container', 'ml-auto');
container.appendChild(togglecontainer);
}
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(`Event changed to: ${selectedEventValue}`);
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
showErrorToast("Please select an event.");
return;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
}
async function fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
showErrorToast("Select an event before proceeding.");
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, selectedEventValue, buttonContainer, container, selectedFieldName, selectedChoices);
} else {
await getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, container);
}
} else {
showErrorToast('No fields found or data not available');
}
} catch (error) {
showErrorToast("Error fetching data for Dropdown");
console.error(error);
}
}
async function getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
showErrorToast("Select an event before proceeding.");
return;
}
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, container, fieldNameContainer, selectedChoices);
} else {
showErrorToast('Field not found in Dropdown');
}
}
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, container, fieldNameContainer);
} else {
showErrorToast('Field not found in Dropdown');
}
});
}
// Other existing functions remain unchanged.
Key Changes:
showErrorToast Function: Displays a toast message on the screen when an error occurs. The toast appears at the bottom of the screen and automatically disappears after a few seconds.
Integration of Error Toasts: Calls to showErrorToast have been added throughout the code at points where validations fail or errors are detected, providing immediate feedback to the user.
This will help users quickly identify and resolve issues, improving the overall user experience. If you're using a library for UI components, you can replace the toast implementation with the library's native functionality.
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Get the existing combination or create a new one
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// If no existing combination, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the existing combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
on this, add
async function initializeEventDropdown(container, fieldMappings = null) {
const eventSelect = container.querySelector('.event-name-dropdown');
console.log(initializeEventDropdown - Initial selected event: ${eventSelect.value});
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-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);
}
// Ensure the togglecontainer exists or create it
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container', 'ml-auto'); // Apply margin-left auto to align it right
container.appendChild(togglecontainer);
}
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;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
}
toggle container and add
as and append with offset of 5 (from right)
Explanation:
Toggle Initialization:
A new <fw-toggle> element is created, set to medium size, and initially checked. This toggle is then appended to the togglecontainer.
Layout Adjustments:
The togglecontainer is given a margin-left set to auto to ensure it is right-aligned within its parent. Additionally, a margin-right of 5px offsets it slightly from the right edge.
Container Verification:
Ensures all necessary containers exist or are created if needed, maintaining a robust and error-free setup.
This integration ensures that the toggle is correctly included and positioned as required, along with the existing dropdown and button elements. Adjust styles as needed, particularly if integrating into a CSS framework with specific grid or column classes.
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;
}
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Get the existing combination or create a new one
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// If no existing combination, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the existing combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
tbat toggle should handle isenable if toggle on isenabled should be true if it is not keep as false
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 fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
// Ensure containers exist
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);
}
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
container.appendChild(buttonContainer);
}
// Ensure the togglecontainer exists or create it
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto'; // Align it to the right with auto margin
togglecontainer.style.marginRight = '5px'; // Offset of 5 from the right
container.appendChild(togglecontainer);
}
// Create and append the toggle to the toggle container
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.setAttribute('checked', ''); // Initial checked state
togglecontainer.appendChild(toggleSwitch);
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(`Event changed to: ${selectedEventValue}`);
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
toggleSwitch.addEventListener('fwChange', (event) => {
const isChecked = event.target.checked;
updateIsEnabledState(toggleSwitch, isChecked);
});
function updateIsEnabledState(toggleSwitch, isChecked) {
const selectedEventValue = eventSelect.value;
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
combination = { isEnabled: isChecked, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
} else {
combination.isEnabled = isChecked;
}
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
// Other existing functions (fieldschoosingvalues, getFieldnamesfrom1stapi, showingitschoices, createAdditionalDropdowns) remain unchanged.
Key Changes:
Toggle Event Listener:
The toggleSwitch listens for fwChange events to detect when its state changes.
Update isEnabled:
The updateIsEnabledState function updates the isEnabled property of the active combination for the selected event based on the toggle state.
Conditional Initialization:
Ensures that if no combination exists, one is initialized upon toggle usage.
This implementation adjusts the isEnabled attribute based on the toggle's state, ensuring that your logic is reflected in the data each time the toggle changes state.
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;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
function updateIsEnabledState(toggleSwitch, isChecked) {
const selectedEventValue = eventSelect.value;
code
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
combination = { isEnabled: isChecked, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
} else {
combination.isEnabled = isChecked;
}
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Get the existing combination or create a new one
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// If no existing combination, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the existing combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
if toggle is off make every dropdown unaccessible
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 fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
// Ensure containers exist
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);
}
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
container.appendChild(buttonContainer);
}
// Ensure the togglecontainer exists or create it
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto'; // Align it to the right with auto margin
togglecontainer.style.marginRight = '5px'; // Offset of 5 from the right
container.appendChild(togglecontainer);
}
// Create and append the toggle to the toggle container
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.setAttribute('checked', ''); // Initial checked state
togglecontainer.appendChild(toggleSwitch);
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(`Event changed to: ${selectedEventValue}`);
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
toggleSwitch.addEventListener('fwChange', (event) => {
const isChecked = event.target.checked;
updateDropdownAccessibility(isChecked);
updateIsEnabledState(eventSelect.value, isChecked);
});
function updateDropdownAccessibility(isEnabled) {
const dropdowns = container.querySelectorAll('.choices-dropdown, .field-name-dropdown, .event-name-dropdown');
dropdowns.forEach(dropdown => {
dropdown.disabled = !isEnabled;
});
}
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
combination = { isEnabled: isChecked, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
} else {
combination.isEnabled = isChecked;
}
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
// Other existing functions (fieldschoosingvalues, getFieldnamesfrom1stapi, showingitschoices, createAdditionalDropdowns) remain unchanged.
Key Changes:
Update Dropdown Accessibility:
updateDropdownAccessibility function disables all relevant dropdowns when the toggle is unchecked (false) and enables them when it's checked.
Toggle Event Listener:
Listens for fwChange on the toggle and updates both the accessibility of dropdowns and the isEnabled state of the current combination.
Dynamic Enable/Disable:
Uses the disabled attribute on the dropdown elements to toggle their accessibility.
This approach provides a user interface experience where toggling the switch directly influences both the data structure (ticketworkflowconditions) and the interactivity of the form fields.
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
code
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
combination = { isEnabled: isChecked, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
} else {
combination.isEnabled = isChecked;
}
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Get the existing combination or create a new one
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// If no existing combination, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the existing combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
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 fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
// Ensure containers exist
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);
}
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
container.appendChild(buttonContainer);
}
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto';
togglecontainer.style.marginRight = '5px';
togglecontainer.style.marginTop = '30px';
container.appendChild(togglecontainer);
}
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.setAttribute('checked', ''); // Initial checked state
togglecontainer.appendChild(toggleSwitch);
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(`Event changed to: ${selectedEventValue}`);
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
toggleSwitch.addEventListener('fwChange', (event) => {
const isChecked = event.target.checked;
updateDropdownAccessibility(isChecked);
updateIsEnabledState(eventSelect.value, isChecked);
});
function updateDropdownAccessibility(isEnabled) {
const dropdowns = container.querySelectorAll('.choices-dropdown, .field-name-dropdown, .event-name-dropdown');
dropdowns.forEach(dropdown => {
dropdown.disabled = !isEnabled;
});
}
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Just update the 'isEnabled' state for existing combinations
ticketworkflowconditions[selectedEventValue].combinations.forEach(combination => {
combination.isEnabled = isChecked;
});
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
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);
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
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, container, fieldNameContainer, selectedChoices);
} else {
showErrorToast('Field not found in Dropdown');
}
}
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, container, fieldNameContainer);
} else {
showErrorToast('Field not found in Dropdown');
}
});
}
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Add an "Add" button to the button container
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Handle the "Add" button click
addButton.addEventListener('click', () => {
createAdditionalDropdowns(container);
});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Create new combination for the selected field and choice
const newCombination = { isEnabled: true, fields: { [selectedFieldName]: selectedChoiceId } };
ticketworkflowconditions[selectedEventValue].combinations.push(newCombination);
console.log(`Updated event ${selectedEventValue} with a new combination for field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container', 'mt-3');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
Explanation:
Adding New Combinations:
When a new choice is made for a field, a new combination is created and appended to the combinations array for the selected event.
Maintaining Existing Combinations:
The new logic appends combinations rather than replacing existing ones, allowing multiple combinations under the same event.
Toggle and Conditions:
The existing toggle logic is preserved, ensuring that combinations' isEnabled states reflect the toggle switch's position.
This solution ensures that multiple valid configurations for a single event can coexist and all configurations are recorded without overwriting.
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
code
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
combination = { isEnabled: isChecked, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
} else {
combination.isEnabled = isChecked;
}
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Get the existing combination or create a new one
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// If no existing combination, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the existing combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Add an "Add" button to the button container
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Handle the "Add" button click
addButton.addEventListener('click', () => {
createAdditionalDropdowns(container);
});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Find an existing combination that doesn't have the field set yet
let combination = ticketworkflowconditions[selectedEventValue].combinations.find(comb => !(selectedFieldName in comb.fields));
if (!combination) {
// If no existing combination is found, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with a combination for field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
Explanation of Key Changes:
Combination Selection Logic:
The logic checks for an existing combination that does not have the current selectedFieldName. If found, it updates that combination; otherwise, it creates a new one.
Appending New Combinations:
By adding new combinations into the existing list, the code supports multiple configurations for the same event.
Dynamic Updating:
Updates occur in the existing array without overwriting previous combinations, ensuring that all valid combinations persist.
This approach supports the addition of new field-choice combinations for a specific event without interfering with existing configurations.
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
// Prepare a temporary object to store field selections, this will be the new combination
let tempFields = {};
// Add an "Add New Combination" button to the button container
const addButton = document.createElement('button');
addButton.textContent = 'Add New Combination';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Handle the "Add New Combination" button click
addButton.addEventListener('click', () => {
if (!selectedEventValue) {
console.error('Event value is not defined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Create a new combination from selected fields
const newCombination = {
isEnabled: true,
fields: { ...tempFields }
};
// Push the new combination to the combinations array
ticketworkflowconditions[selectedEventValue].combinations.push(newCombination);
console.log(`Added a new combination to event ${selectedEventValue}`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
// Reset temporary fields for next combination
tempFields = {};
});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Store the selected field value in temporary fields
tempFields[selectedFieldName] = selectedChoiceId;
console.log(`Temporary fields updated:`, tempFields);
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container', 'mt-3');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
Explanation:
Temporary Fields Storage: We use a tempFields object to accumulate field selections before the combination is added.
Adding Combinations: The "Add New Combination" button appends a new combination to the selected event’s combinations array.
Dynamic Updates: Each selection in the dropdown updates the tempFields, ensuring all selected fields are captured before adding the combination.
This allows for multiple sets of selections to be added to the same event, enabling a flexible configuration system.
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 fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
// Ensure containers exist
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);
}
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
container.appendChild(buttonContainer);
}
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto';
togglecontainer.style.marginRight = '5px';
togglecontainer.style.marginTop = '30px';
container.appendChild(togglecontainer);
}
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.setAttribute('checked', ''); // Initial checked state
togglecontainer.appendChild(toggleSwitch);
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(`Event changed to: ${selectedEventValue}`);
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
toggleSwitch.addEventListener('fwChange', (event) => {
const isChecked = event.target.checked;
updateDropdownAccessibility(isChecked);
updateIsEnabledState(eventSelect.value, isChecked);
});
function updateDropdownAccessibility(isEnabled) {
const dropdowns = container.querySelectorAll('.choices-dropdown, .field-name-dropdown, .event-name-dropdown');
dropdowns.forEach(dropdown => {
dropdown.disabled = !isEnabled;
});
}
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Just update the 'isEnabled' state for existing combinations
ticketworkflowconditions[selectedEventValue].combinations.forEach(combination => {
combination.isEnabled = isChecked;
});
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
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);
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
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, container, fieldNameContainer, selectedChoices);
} else {
showErrorToast('Field not found in Dropdown');
}
}
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, container, fieldNameContainer);
} else {
showErrorToast('Field not found in Dropdown');
}
});
}
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
let tempFields = {};
// Add an "Add New Combination" button to the button container
const addButton = document.createElement('button');
addButton.textContent = 'Add New Combination';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Handle the "Add New Combination" button click
addButton.addEventListener('click', () => {
if (!selectedEventValue) {
console.error('Event value is not defined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Create new combination and add to the combinations array
const newCombination = {
isEnabled: true,
fields: { ...tempFields }
};
ticketworkflowconditions[selectedEventValue].combinations.push(newCombination);
console.log(`Added a new combination to event ${selectedEventValue}`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
// Reset temporary fields for next combination
tempFields = {};
});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Store the selected field choice in temporary fields
tempFields[selectedFieldName] = selectedChoiceId;
console.log(`Temporary fields updated:`, tempFields);
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container', 'mt-3');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
Key Changes:
tempFields Storage: Temporary storage is created to gather fields and choices for each new combination.
Separate Combinations: Each "Add New Combination" button click creates a new entry in the event's combinations array.
Modular Handling: Updated structure involves creating and setting up a new combination during each rule addition without affecting the existing rules, promoting flexible, multi-combo configurations.
This allows users to establish new field-choice sets under the same event, dynamically updating the conditions as described.
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
code
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Just update the 'isEnabled' state for existing combinations
ticketworkflowconditions[selectedEventValue].combinations.forEach(combination => {
combination.isEnabled = isChecked;
});
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Get the existing combination or create a new one
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// If no existing combination, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the existing combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
now make changes in this
async function createEventDropdownSet(eventName) {
console.log("Creating Event Dropdown");
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
code
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Just update the 'isEnabled' state for existing combinations
ticketworkflowconditions[selectedEventValue].combinations.forEach(combination => {
combination.isEnabled = isChecked;
});
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
code
// Check for necessary data
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Get the existing combination or create a new one
let combination = ticketworkflowconditions[selectedEventValue].combinations[0];
if (!combination) {
// If no existing combination, create a new one
combination = { isEnabled: true, fields: {} };
ticketworkflowconditions[selectedEventValue].combinations.push(combination);
}
// Update the existing combination's fields with the new field and choice
combination.fields[selectedFieldName] = selectedChoiceId;
console.log(`Updated event ${selectedEventValue} with field ${selectedFieldName} and choice ID ${selectedChoiceId}`);
// Log the updated ticketworkflowconditions object
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
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 fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
// Ensure containers exist
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);
}
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
container.appendChild(buttonContainer);
}
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto';
togglecontainer.style.marginRight = '5px';
togglecontainer.style.marginTop = '30px';
container.appendChild(togglecontainer);
}
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.setAttribute('checked', ''); // Initial checked state
togglecontainer.appendChild(toggleSwitch);
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(`Event changed to: ${selectedEventValue}`);
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
toggleSwitch.addEventListener('fwChange', (event) => {
const isChecked = event.target.checked;
updateDropdownAccessibility(isChecked);
updateIsEnabledState(eventSelect.value, isChecked);
});
function updateDropdownAccessibility(isEnabled) {
const dropdowns = container.querySelectorAll('.choices-dropdown, .field-name-dropdown, .event-name-dropdown');
dropdowns.forEach(dropdown => {
dropdown.disabled = !isEnabled;
});
}
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Update the 'isEnabled' state for all combinations of the selected event
ticketworkflowconditions[selectedEventValue].combinations.forEach(combination => {
combination.isEnabled = isChecked;
});
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
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);
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
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, container, fieldNameContainer, selectedChoices);
} else {
showErrorToast('Field not found in Dropdown');
}
}
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, container, fieldNameContainer);
} else {
showErrorToast('Field not found in Dropdown');
}
});
}
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
let tempFields = {};
// Add an "Add New Combination" button to the button container
const addButton = document.createElement('button');
addButton.textContent = 'Add New Combination';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Handle the "Add New Combination" button click
addButton.addEventListener('click', () => {
if (!selectedEventValue) {
console.error('Event value is not defined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Create new combination and add to the combinations array
const newCombination = {
isEnabled: true,
fields: { ...tempFields }
};
ticketworkflowconditions[selectedEventValue].combinations.push(newCombination);
console.log(`Added a new combination to event ${selectedEventValue}`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
// Reset temporary fields for next combination
tempFields = {};
});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Store the selected field choice in temporary fields
tempFields[selectedFieldName] = selectedChoiceId;
console.log(`Temporary fields updated:`, tempFields);
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container', 'mt-3');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
Key Changes:
Temporary Fields Collection:
A temporary object, tempFields, is used to collect field and choice selections.
Add New Combination Logic:
The "Add New Combination" button creates a new combination from tempFields and appends this to the combinations array of the selected event.
Dynamic Data Structure:
Each new set of choices results in a new combination being appended, effectively managing multiple configurations under a single event.
This setup supports the specified feature and maintains the flexibility needed for dynamic condition combinations.
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 fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let togglecontainer = container.querySelector('.toggle-container');
// Ensure containers exist
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);
}
if (!buttonContainer) {
buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container');
buttonContainer.style.marginTop = '25px';
container.appendChild(buttonContainer);
}
if (!togglecontainer) {
togglecontainer = document.createElement('div');
togglecontainer.classList.add('col-md-2', 'toggle-container');
togglecontainer.style.marginLeft = 'auto';
togglecontainer.style.marginRight = '5px';
togglecontainer.style.marginTop = '30px';
container.appendChild(togglecontainer);
}
const toggleSwitch = document.createElement('fw-toggle');
toggleSwitch.setAttribute('size', 'medium');
toggleSwitch.setAttribute('checked', ''); // Initial checked state
togglecontainer.appendChild(toggleSwitch);
eventSelect.addEventListener('fwChange', async function () {
const selectedEventValue = eventSelect.value;
console.log(`Event changed to: ${selectedEventValue}`);
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
buttonContainer.innerHTML = '';
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
toggleSwitch.addEventListener('fwChange', (event) => {
const isChecked = event.target.checked;
updateDropdownAccessibility(isChecked);
updateIsEnabledState(selectedEventValue, isChecked);
});
function updateDropdownAccessibility(isEnabled) {
const dropdowns = container.querySelectorAll('.choices-dropdown, .field-name-dropdown, .event-name-dropdown');
dropdowns.forEach(dropdown => {
dropdown.disabled = !isEnabled;
});
}
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Just update the 'isEnabled' state for existing combinations
ticketworkflowconditions[selectedEventValue].combinations.forEach(combination => {
combination.isEnabled = isChecked;
});
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
}
}
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);
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);
await getFieldnamesfrom1stapi(individualFieldContainer, fields, individualChoicesContainer, 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) {
showErrorToast("Select an event before proceeding.");
return;
}
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, container, fieldNameContainer, selectedChoices);
} else {
showErrorToast('Field not found in Dropdown');
}
}
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, container, fieldNameContainer);
} else {
showErrorToast('Field not found in Dropdown');
}
});
}
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
// Clear previous choices
choicesContainer.innerHTML = '';
// Create the dropdown for choices
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');
// Add options to the dropdown from selectedField.choices
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
// Pre-select choices if selectedChoices array is provided
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
console.log(`Pre-selected choice: ${choice.id} for field: ${selectedFieldName}`);
}
});
// Append the dropdown to the container
choicesContainer.appendChild(choicesDropdown);
let tempFields = {};
// Add an "Add New Combination" button to the button container
const addButton = document.createElement('button');
addButton.textContent = 'Add New Combination';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
// Handle the "Add New Combination" button click
addButton.addEventListener('click', () => {
if (!selectedEventValue) {
console.error('Event value is not defined');
return;
}
// Initialize ticketworkflowconditions for the selected event if not already present
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
// Create new combination and add to the combinations array
const newCombination = {
isEnabled: true,
fields: { ...tempFields }
};
ticketworkflowconditions[selectedEventValue].combinations.push(newCombination);
console.log(`Added a new combination to event ${selectedEventValue}`);
console.log('Updated ticketworkflowconditions:', JSON.stringify(ticketworkflowconditions, null, 2));
// Reset temporary fields for next combination
tempFields = {};
});
// Event listener for when a choice is selected
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Store the selected field choice in temporary fields
tempFields[selectedFieldName] = selectedChoiceId;
console.log(`Temporary fields updated:`, tempFields);
});
}
function createAdditionalDropdowns(container) {
// Create new containers for the additional sets
const fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
fieldNameContainer.classList.add('offset-md-2');
const choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
const buttonContainer = document.createElement('div');
buttonContainer.classList.add('col-md-3', 'button-container', 'mt-3');
// Add a "Delete" button to the button container
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.classList.add('btn', 'btn-danger', 'mt-2');
buttonContainer.appendChild(deleteButton);
// Append the new containers to the main container
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
// Call fieldschoosingvalues to populate the new set of dropdowns
fieldschoosingvalues(
container.querySelector('.event-name-dropdown').value,
fieldNameContainer,
choicesContainer,
buttonContainer,
container
);
// Event listener to handle the "Delete" button click
deleteButton.addEventListener('click', () => {
fieldNameContainer.remove();
choicesContainer.remove();
buttonContainer.remove();
});
}
Explanation:
Temporary Fields Handling:
tempFields is used to store the selections made for each combination before they are added to ticketworkflowconditions.
Addition of New Combinations:
Each click of "Add New Combination" results in a new object stored in the combinations array, ensuring previous combinations remain unaffected.
Multiple Configurations:
This design allows for the creation of multiple configurations for a single event, based on the field and choice inputs made by the user.
With these adjustments, the code now supports dynamically adding new combinations for the same event without overwriting existing configurations.
// Example global object to store conditions
let ticketworkflowconditions = {
"TicketCreate": {
"combinations": [
{
"isEnabled": true,
"fields": {
"status": "2",
"priority": "2"
}
}
]
}
};
async function initializeDropdownAndListeners(container) {
// Example event setup
const newDropdownSet = await createEventDropdownSet('TicketCreate');
container.appendChild(newDropdownSet);
const eventSelect = container.querySelector('.event-name-dropdown');
const fieldNameContainer = document.createElement('div');
const choicesContainer = document.createElement('div');
const buttonContainer = document.createElement('div');
container.appendChild(fieldNameContainer);
container.appendChild(choicesContainer);
container.appendChild(buttonContainer);
eventSelect.addEventListener('fwChange', async () => {
const selectedEventValue = eventSelect.value;
if (!selectedEventValue) {
console.error("Selected event value is undefined or empty.");
return;
}
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container);
});
}
async function fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
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
);
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) {
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);
});
fieldNameContainer.appendChild(firstDropdown);
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, container, fieldNameContainer);
} else {
console.error('Field not found in Dropdown');
}
});
}
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer
) {
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);
});
choicesContainer.appendChild(choicesDropdown);
// Store temporary selections until final addition to combinations
const tempFields = {};
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
if (!selectedEventValue || !selectedFieldName) {
console.error('Event or field name is undefined');
return;
}
// Save the field to temp to avoid overwrite
tempFields[selectedFieldName] = selectedChoiceId;
});
// If this was a form, clicking save being outside could complete the combination, here's an abstract example:
container.querySelector('button#saveCombination').addEventListener('click', () => {
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
ticketworkflowconditions[selectedEventValue].combinations.push({
isEnabled: true,
fields: { ...tempFields }
});
console.log('JSON updated with new combo:', JSON.stringify(ticketworkflowconditions, null, 2));
});
}
// Here would be the setup or an event somewhere to trigger adding a new rule
// E.g.,
async function addNewRule(container) {
console.log("Adding new rule for another set...");
initializeDropdownAndListeners(container); // Calls the initialization to set up another rule
}
Explanation:
AddNewRule Functionality: I added a high-level function addNewRule that simulates how you might add a new rule when a user clicks to do so. This function initializes dropdowns for a new set.
Combination Storage: By clicking a button like "Save" (assuming that its placeholder ID is #saveCombination within your HTML), you append the current selection to your JSON structure.
Temporary Data Handling: Each set of selections is stored separately until the user finalizes it, e.g., with a 'save' mechanism outside.
This setup ensures when you choose "TicketCreate" again after clicking "Add New Rule" (or similar named button), the new combination is stored within your data structure as intended. Adjust the framework or logic if unique saving flows are required.