skip to Main Content

I’m currently working on a PowerApps project where I have several dropdown lists (option sets) that should only allow users to select each team once. I want to prevent users from reselecting teams after they’ve been chosen. However, I’m running into a few issues.
Here’s a Snippet of My Code:

let selectedTeams = [];

// Codes pour les équipes


function onTeamChange(executionContext, fieldName) {

const formContext = executionContext.getFormContext();

const selectedValue = formContext.getAttribute(fieldName).getValue();

// Si une valeur a été désélectionnée

if (selectedValue === null) {

// Retirer l'élément désélectionné de selectedTeams``

selectedTeams = selectedTeams.filter(team => team !== fieldName);

formContext.ui.clearFormNotification("duplicateTeam");

return;

}

// Vérifie si l'équipe est déjà dans la liste des équipes sélectionnées.

if (selectedTeams.includes(selectedValue)) {

formContext.ui.setFormNotification("Cette équipe a déjà été choisie.", "ERROR", "duplicateTeam");

formContext.getAttribute(fieldName).setValue(null); // Réinitialise la sélection pour éviter le doublon.

} else {

formContext.ui.clearFormNotification("duplicateTeam");

selectedTeams.push(selectedValue); // Ajoute la nouvelle sélection dans selectedTeams`.`

}

// Met à jour les options des dropdowns

updateDropdownOptions(formContext);

}

function updateDropdownOptions(formContext) {

const allDropdowns = ["teamOptionSet1", "teamOptionSet2", "teamOptionSet3", "teamOptionSet4"]; // Noms des champs

allDropdowns.forEach(fieldName => {

const dropdown = formContext.getAttribute(fieldName);

const options = dropdown.getOptions(); // Récupère toutes les options de l'option set

// Réinitialise les options de l'option set

options.forEach(option => {

// Si l'option est dans la liste selectedTeams`, désactivez-la`

option.disabled = selectedTeams.includes(option.value);

});

// Met à jour le dropdown avec les options modifiées

// Note: Dans PowerApps, vous ne pouvez pas appeler setOptions. Vous devez le gérer par logique utilisateur.

});

}

I have a JavaScript function that runs on the onchange event for each dropdown. The goal is to check if a selected team has already been chosen and, if so, prevent re-selection.

I’m storing the selected values in an array, but I’m having trouble clearing options after a selection is made.

Issue I’m Facing: The items do not disappear from the dropdown list after selection.
Questions:
How can I modify my code to ensure that selected options are properly removed from the dropdown list?

Any insights, code examples, or pointers would be greatly appreciated! Thanks in advance for your help!

I’m storing the selected values in an array, but I’m having trouble clearing options after a selection is made.

2

Answers


  1. To create a dynamic dropdown list where previously selected teams are disabled and prevent re-selection, we need to adjust your JavaScript logic to update dropdowns effectively. Since PowerApps does not allow us to remove or disable options directly in dropdown lists, we’ll need to filter the options in each dropdown based on the selectedTeams array and then set only the filtered list as available.

    Here’s a revised approach with explanations for each part:

    1. Store Selections: Track selected teams in an array.
    2. Filter Options: Each time a team is selected or deselected, filter the options for each dropdown.
    3. Reset Options: If a team is deselected, re-enable it in other dropdowns.

    Updated Code

    Below is a modified version of your code that implements these principles:

    let selectedTeams = [];
    
    // Function to handle team selection changes
    function onTeamChange(executionContext, fieldName) {
        const formContext = executionContext.getFormContext();
        const selectedValue = formContext.getAttribute(fieldName).getValue();
    
        // If a value was deselected, remove it from selectedTeams
        if (selectedValue === null) {
            selectedTeams = selectedTeams.filter(team => team !== formContext.getAttribute(fieldName).getInitialValue());
            formContext.ui.clearFormNotification("duplicateTeam");
        } else {
            // Check if the team is already selected in another dropdown
            if (selectedTeams.includes(selectedValue)) {
                formContext.ui.setFormNotification("Cette équipe a déjà été choisie.", "ERROR", "duplicateTeam");
                formContext.getAttribute(fieldName).setValue(null); // Reset selection to prevent duplicate
            } else {
                formContext.ui.clearFormNotification("duplicateTeam");
                selectedTeams.push(selectedValue); // Add the new selection to selectedTeams
            }
        }
    
        // Update the options for all dropdowns
        updateDropdownOptions(formContext);
    }
    
    // Function to update options for each dropdown based on selections
    function updateDropdownOptions(formContext) {
        const allDropdowns = ["teamOptionSet1", "teamOptionSet2", "teamOptionSet3", "teamOptionSet4"]; // Names of the dropdown fields
    
        allDropdowns.forEach(fieldName => {
            const dropdown = formContext.getAttribute(fieldName);
            const selectedValue = dropdown.getValue();
            const options = dropdown.getOptions();
    
            // Filter options based on the selected teams, allowing the current selection to stay available
            const availableOptions = options.filter(option => 
                !selectedTeams.includes(option.value) || option.value === selectedValue
            );
    
            // Remove existing options and add only the available ones back
            dropdown.clearOptions();
            availableOptions.forEach(option => dropdown.addOption(option));
        });
    }
    

    Explanation of Key Changes

    1. Track Selections: selectedTeams is an array that tracks all selected team values across dropdowns.
    2. onTeamChange Logic: When a team is selected, the function checks if it’s already in selectedTeams.
    • If it’s a duplicate, it resets the selection and shows a notification.
    • If not a duplicate, it adds the new selection to selectedTeams.
    • If a team is deselected (i.e., the value is null), it removes that team from selectedTeams.
    1. Filter Available Options:updateDropdownOptions loops through each dropdown and filters the options to exclude any value in selectedTeams, except the currently selected option for that dropdown.
      The clearOptions() and addOption() methods are used to reset options.

    Notes
    clearOptions() and addOption() are necessary because PowerApps doesn’t support direct modification of existing options in the dropdown.
    If a dropdown’s current selection is allowed to stay, even if it’s part of selectedTeams, so it doesn’t get unintentionally disabled.

    Login or Signup to reply.
  2. You cannot directly set options as "disabled" in option sets that you can set with HTML shutters.

    Here’s an updated version of your code with some adjustments:

    let selectedTeams = [];
    
    function onTeamChange(executionContext, fieldName) {
        const formContext = executionContext.getFormContext();
        const selectedValue = formContext.getAttribute(fieldName).getValue();
    
        if (selectedValue === null) {
            selectedTeams = selectedTeams.filter(team => team !== fieldName);
            formContext.ui.clearFormNotification("duplicateTeam");
            updateDropdownOptions(formContext);
            return;
        }
    
        if (selectedTeams.includes(selectedValue)) {
            formContext.ui.setFormNotification("Cette équipe a déjà été choisie.", "ERROR", "duplicateTeam");
            formContext.getAttribute(fieldName).setValue(null); // Reset selection
        } else {
            formContext.ui.clearFormNotification("duplicateTeam");
            selectedTeams.push(selectedValue);
        }
    
        updateDropdownOptions(formContext);
    }
    
    function updateDropdownOptions(formContext) {
        const allDropdowns = ["teamOptionSet1", "teamOptionSet2", "teamOptionSet3", "teamOptionSet4"];
    
        allDropdowns.forEach(fieldName => {
            const dropdown = formContext.getAttribute(fieldName);
            const options = dropdown.getOptions();
    
            const filteredOptions = options.filter(option => !selectedTeams.includes(option.value));
    
            dropdown.setOptions(filteredOptions);
        });
    }
    

    Explanation:

    1.The updateDropdownOptions function now filters out options that are in the selectedTeams array.

    2.Instead of trying to disable the options, it updates each dropdown to only display options that haven’t been selected yet.

    3.setOptions may not work in all PowerApps environments, so if this doesn’t apply to your setup, another approach would be to handle it through conditional logic and user feedback, resetting selections if duplicates are detected.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search