Dropdown 2 codependent on dropdown1

Hello guys,

I hit a wall. I use wix studio and I can´t seen to get my dropdown 2 dependent on my fisrt. Ex; I have a Segment of Personal Care, and I want my dropdown 2 to show me only the materials for this segment instead of all materials from my collection (other segments).

I’ve tried to create a second collection and get a reference connection, but there is no option of putting a value reference as I see in most videos and comments.

I would like to use the dataset2 I’m using to conect my two dropdowns ‘dropdownsegments’ and ‘dropdownmaterials’. I conected then but, I want to only display the option of searching fo materials inside the segment selected! Can someone help me please? I’ve tried many things and codes (chatgpt build for me and I chenge de values properly, but nothing seens to work).

There are a few ways to achieve this with code. What have you tried so far ? maybe post your code and it may just need tweaking. I have built a few conditional formatting dropdown filters and each are very different in the approach.

Hello Dan,

I´m using this code;

import wixData from ‘wix-data’;

$w.onReady(function () {

wixData.query("dataset2")
    .distinct("segmentName") // 
    .then((results) => {
        const options = results.items.map((segment) => {
            return {
                label: segment, // 
                value: segment  // 
            };
        });
        $w("#dropdownsegments").options = options;
    });


$w("#dropdownsegments").onChange((event) => {
    const selectedSegment = event.target.value; // 


    wixData.query("dataset2")
        .eq("segmentName", selectedSegment) // 
        .find()
        .then((results) => {
            const materialOptions = results.items.map((item) => {
                return {
                    label: item.materialName, // Nome do material na sua coleção
                    value: item._id // O valor será o ID do material
                };
            });
            $w("#dropdownmaterials").options = materialOptions; // Popula o dropdownmaterials com os materiais filtrados
        });
});

at a quick glace the code seems logical. Check that your datasets and collection names/id are all correct

Hello,

I checked the ID one by one! And still not working. I don’t know what I am doing wrong. It still shows all materials when I select the refered segment.

Hello Amanda,

Is the above your CMS database name? This reads that this is the dataset page element ID. Make sure dataset2 is your collection name.

Also add some console.log() lines to make sure you are getting the data. If you can’t get it, feel free to export a sample of your database and I’ll put it in the IDE on my end to write a solution for you.

I went ahead and did a quick playground on my end. Please follow the steps below and adjust the code to suit your needs.

Database setup

  1. Create a database for your first dropdown => in my case I created a “Foods” database
  2. In this database create a primary text field => in my case the text field was named “Food Title” and its field key is “foodTitle”
  3. Create a separate database for your dropdown 2 => in my case I created a “Ingredients” database
  4. In this new database create a primary text field => in my case I named it “Ingredient Name” and its field key is “ingredientName”
  5. Add a new column in this database with the field type of multi-reference and connect this field to your first database. Then use the reference tags to assign values across the 2 databases.

Activate Dev Mode if not already

In the dev panel find your collections to reference
Here is what my collections and field key names look like at this point:

Add a page dataset and connect it your first dropdown

  • Set its method to “Filter Content” and select the variable you need to assign it to.

Add a new dropdown

  • Set its default behavior to disabled and take note of its element name. (make sure enabled is not checked)

Page code:

import wixData from 'wix-data';

// set as global data
let allData

$w.onReady(function () {

    $w('#dataset1').onReady(() => {
        getAllData()
    })

});

/*
Get all the data and save globally
• 2 collections
	• Food Database
	• Ingredient Database

Both collections share a multireference so we will use the include option to in the query

Believe there is a limit of 50 instead of 1000 when including references
*/
const getAllData = async () => {
    const getData = await wixData.query('Foods').include('Ingredients_foodReference').limit(50).find()
    const { items } = getData
    console.log(items, 'all items') // return main collection with referenced fields attached into array
    allData = items
    // set rest of code when data is global
    eventHandlers()
}

function eventHandlers() {
    $w('#dropdown1').onChange((e) => buildIngredientDropdown(e.target.value))
}

const buildIngredientDropdown = (value) => {
	console.log(value, 'check value')
    if (value) {
        let dropdownOptions
        if (value === 'RESET_ALL') {
            const allIngredients = allData.flatMap((all) => all.Ingredients_foodReference)
            const uniqueIngredients = [...new Set(allIngredients.map((ingredients) => ingredients.ingredientName))] // use spread to only get unique values
            // console.log(uniqueIngredients, 'unique ingredients for all', allIngredients) // works here
			dropdownOptions = uniqueIngredients.map((item) => ({
                label: item,
                value: item,
            }))
        } else {
            const filteredData = allData.find((items) => items.foodTitle === value)
            const ingredients = filteredData.Ingredients_foodReference // Ingredients_foodReference is the referenced key name
			// console.log(ingredients, 'ingredients specific', filteredData)
            dropdownOptions = ingredients.map((item) => ({
                label: item.ingredientName,
                value: item.ingredientName,
            }))
        }
        $w('#dropdown2').options = dropdownOptions ?? []
        $w('#dropdown2').enable()
    } else {
        // reset dropdown 2 if no value
        $w('#dropdown2').value = ''
        $w('#dropdown2').options = []
        $w('#dropdown2').disable()
    }
}

That’s it! When you change the code variables and database names to match yours, you will have something similar to this.

ScreenRecording2024-10-03at3.53.54PM-ezgif.com-video-to-gif-converter

1 Like