Avoid Reselecting Dropdown Choices in PowerApps Model-Driven Apps

Currently, I am working on a PowerApps project that involves multiple dropdown lists (option sets) where users should only be able to select each team once. I am striving to prevent users from reselecting teams that have already been chosen but facing some challenges in the process. Below is an excerpt of the code I'm working with:

let selectedTeams = [];

// Team Codes


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");

return;

}

if (selectedTeams.includes(selectedValue)) {

formContext.ui.setFormNotification("This team has already been chosen.", "ERROR", "duplicateTeam");

formContext.getAttribute(fieldName).setValue(null);

} 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(); 

options.forEach(option => {

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

});


});

}

I have implemented a JavaScript function that triggers on the onchange event for each dropdown, aiming to prevent re-selection of already chosen teams.

While I store selected values in an array, I encounter difficulty in clearing options post selection.

Current Issue: The items do not vanish from the dropdown list after selection. Questions: How can I enhance my code to ensure successful removal of selected options from the dropdown list?

I would greatly appreciate any insights, examples of code, or guidance provided. Thank you in advance for your assistance!

Although I store selected values in an array, clearing options after selection poses a challenge.

Answer №1

To implement a dynamic dropdown list that disables previously selected teams and prevents re-selection, we must adjust the JavaScript logic to update dropdowns effectively. Given that PowerApps does not offer a direct way to remove or disable options in dropdown lists, we'll need to filter the options in each dropdown based on the selectedTeams array and set only the filtered list as available.

Here is an updated approach with detailed explanations for each step:

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

Modified Code

Below is a revised version of your code that incorporates these principles:

let selectedTeams = [];

// Function to manage team selection changes
function onTeamChange(executionContext, fieldName) {
    const formContext = executionContext.getFormContext();
    const selectedValue = formContext.getAttribute(fieldName).getValue();

    // Remove deselected value from selectedTeams
    if (selectedValue === null) {
        selectedTeams = selectedTeams.filter(team => team !== formContext.getAttribute(fieldName).getInitialValue());
        formContext.ui.clearFormNotification("duplicateTeam");
    } else {
        // Check for duplicate selections in other dropdowns
        if (selectedTeams.includes(selectedValue)) {
            formContext.ui.setFormNotification("This team has already been chosen.", "ERROR", "duplicateTeam");
            formContext.getAttribute(fieldName).setValue(null); // Prevent duplication by resetting selection
        } else {
            formContext.ui.clearFormNotification("duplicateTeam");
            selectedTeams.push(selectedValue); // Add new selection to selectedTeams
        }
    }

    // Update options for all dropdowns
    updateDropdownOptions(formContext);
}

// Function to update options in each dropdown based on selections
function updateDropdownOptions(formContext) {
    const allDropdowns = ["teamOptionSet1", "teamOptionSet2", "teamOptionSet3", "teamOptionSet4"]; // Dropdown field names

    allDropdowns.forEach(fieldName => {
        const dropdown = formContext.getAttribute(fieldName);
        const selectedValue = dropdown.getValue();
        const options = dropdown.getOptions();

        // Filter options based on selected teams, ensuring current selection remains available
        const availableOptions = options.filter(option => 
            !selectedTeams.includes(option.value) || option.value === selectedValue
        );

        // Replace existing options with available ones
        dropdown.clearOptions();
        availableOptions.forEach(option => dropdown.addOption(option));
    });
}

Key Changes Explanation

  1. Track Selections: The array selectedTeams keeps track of 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, the selection is reset and a notification is shown.
  • If not a duplicate, the new selection is added to selectedTeams.
  • If a team is deselected (null value), it is removed from selectedTeams.
  1. Filter Available Options: The updateDropdownOptions method iterates through each dropdown, filters options based on selectedTeams, excluding the currently selected option for that dropdown. The clearOptions() and addOption() functions are used to manage options efficiently.

Additional Notes The use of clearOptions() and addOption() is essential due to PowerApps limitations on modifying dropdown options directly. It ensures that a dropdown's current selection can remain accessible even if part of selectedTeams, preventing unintentional disabling.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying MySQL data on an HTML page with Node.js

Hello there, I recently started delving into Node.js for the first time. My current project involves fetching data from MySQL and displaying it on my HTML page. However, when I try to access my website at http://localhost:3000/index.html, I encounter an er ...

Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success. <ul class="nav nav-pills mb-3" id=&q ...

By pressing the "showMore" button, the page dynamically pulls in a json list from a file

Currently, my focus is on a dropwizard-Java project. My task involves retrieving and showcasing the first 10 items from a json list in a mustache view. If the user clicks on the "show more" link, I should retrieve the next 10 elements from the list and d ...

leveraging the localStorage feature in a for-in iteration

I am new to stackOverflow, although I have browsed the forums for help in the past. However, this time I couldn't find a solution to my current issue, so I decided to create an account and seek assistance. The problem at hand is related to a workout ...

Tips for updating the selected date format in a Material Table component using React

In the context of using a material table in React, the columns set up are as follows: columns={[ { title: 'Name', field: 'name', type: 'string', }, ...

The base64 conversion for the image is overflowing from the upload image field in react-draft-wysiwyg

I have a functional react-draft-wysiwyg editor application that allows me to add images. However, I am currently encountering an issue which is detailed below: https://i.stack.imgur.com/HTjAc.png This is the code snippet of what I have attempted so far. ...

Encountering the error message "ReferenceError: parsePayload cannot be accessed before initialization"

Check out this code snippet: Experiencing an issue with 'ReferenceError: Cannot access 'parsePayload' before initialization' Any assistance would be appreciated const express = require("express"); const { createToDo, updateToD ...

Error: Attempting to access 'map' property from undefined object while making API call

Can someone please help me with a coding problem? When I run the code below, I encounter the error message "TypeError: Cannot read properties of undefined (reading 'map')." Upon logging the "items" variable, I observe 2 results, the first of whi ...

Is there a way to adjust the timepicker value directly using the keyboard input?

Is there a way to control the material-ui-time-picker input using the keyboard instead of clicking on the clock? This is my current code: import React, { Component } from "react"; import { TimePicker } from "material-ui-time-picker"; import { Input as Ti ...

Tips for transferring a function between stateful and stateless components

Looking to transfer a function from a stateful component to a stateless component, here's a snippet of the code. Below is the stateless code. const ProductsGridItem = props => { const { result } = props; const source = result._source; return ( ...

Jest remains verdant even in cases where Expected does not match Received

it('User is already present as a supplier', (done) => { const store = mockStore({}, [{ type: 'get_user', data: { } }]); return store.dispatch(userGetAction({ role: 'supplier' }, () => {})).then(() => { t ...

Issue with texture visibility in ThreeJS: Texture appears in debug mode but not in regular display mode

Currently delving into ThreeJS and JavaScript, I am in the process of constructing a scene with 2 meshes: A cube positioned at the origin. A "floor" situated on the XY plane, utilizing a checkered texture loaded from an image. When running it in debug mo ...

A table featuring an HTML select element that allows users to choose from preset options or manually enter

My goal is to incorporate a select box where users can either choose from a set list of options or input their own custom value. The select element is nested within a table. Unfortunately, using datalist is not a viable solution for me in this case. I have ...

"The process of updating a div with MySQL data using Socket.io on Node.js abruptly halts without any error message

Embarking on a new project using socket.io has been quite the learning experience for me as a beginner. Despite extensive research, I managed to reach the desired stage where I have divs dynamically populated with data fetched from MySQL. In my server.js f ...

What is the best way to eliminate the time component from an object in JavaScript?

I have a task to strip the time information from a specific property in my object. To achieve this, I am checking if any timestamps are present in the property value by using an index. Here is the initial input: input [ { "S": "Charge Interest Agai ...

JSONP request resulted in a syntax error

I'm having trouble retrieving data from a JSONP source, as it keeps throwing a Syntax error when the function is called. I am quite new to this subject and find it hard to understand why this error occurs. It seems like my understanding of JSONP reque ...

What is the method for inserting JSON data into a select element's options?

Below is the HTML code snippet provided: <html> <head> <link rel="stylesheet" type="text/css" href="CarInfoStyle.css"> </head> <script src="CarInfoJavascript.js"></script> <body> <div class="search ...

display different vue component based on screen size

I am in search of a method to implement responsive components in Vue.js (Nuxt). I have developed this mix-in but encountering an error: export const mediaQuery = { data() { return { breakpoints: { sm: 576, md: 768, lg: ...

Ways to make a function inside a Node.js script get called by JavaScript in HTML?

At the moment, I am integrating Node.JS with various systems as the backend. My goal is to trigger a function in the Node.JS script from my webpage and retrieve specific values. This illustration outlines my objective: JS --> triggers function --> ...

Maintaining consistent height using JavaScript

Dealing with equal height using just CSS can be a hassle, especially when you want to support older browsers like IE9. That's why I've decided to use JavaScript instead. If a user disables JavaScript, having unequal heights is the least of my con ...