Dropdown and database

Hi, I created a dropdown box, a table, a database and connected them.
I have looked at multiple codes but none seems to work for me. I would like the dropdown sort or display the table by product.
I found some code that helped me not to duplicate the products but the table does not respond. If I would connect the dropdown to the product value, it stops working.
Can someone help me out?

@hortiray Hi There. Please take a look at this post

This user tried to use the same mapping function but the code was flawed. The correct (or one that works) way to implement your getUniqueItems() function is shown in the post.

Cheers
Steve

Hi Steve, thanks for the quick response. Just as Dilly I have tried many things and I am a fairly new beginner. I looked at the code and tried to adjust it so it is for one dropdown but of course that didn’t work. The dropdown does only display its default settings at this moment. I am using this method for multiple pages. Would be so good if it did work!

Thank you in advance…

@hortiray The red dots signify an error. The main error you have is that you don’t have a reset button with the id “resetDropdownsButton”. If you add this the error will go away. You can also comment out line 6 by adding // at the beginning of the line this makes the line a comment.

Then what you should do is replace the getUniqueTitles() function (lines 24-27) with this code:

function getUniqueTitles(items, columnKey) {
 const titlesOnly = items.map(item => item[columnKey]);
 // We need to return an array
 let result = [];
 // Make our list unique by adding it to a Set object
 let uniqueSet = new Set(titlesOnly);
 // Get the iterator to cycle through each record
 let setIterator = uniqueSet.entries();
 for (let entry of setIterator) {
 // Add the primary value of each record to our array
 let entryValue = entry[0];
 if (entryValue) {
 // Only use valid values
            result.push(entryValue);
        }   
    }
 return result;
}

I think that should fix your problem. If it still doesn’t then post the URL to your site to help debug it.

Steve

@stevendc Many Thanks Steve!
As you can see in the code below, the reset button, which I made with the correct id, still gives an error.
The url to my site is: https://hortiray.wixsite.com/database/orchard , there should be no password request atm.


Also the dropdownbox does not display the right names…
While you are there, can I ask you another thing?
When you would go to the edit/new page through the button on the page we are talking about.
This edit page was working fine but I decided to use a second database because that would be easier in the future with other pages. The second dataset is for products. I have a few products and the image is related to them. How would I receive the data from the product database for field: product and field: image and store it in the first database under the same fieldnames?

I want to use this method also for the calendar page but let’s keep to the first thing…

Thanks again!

@hortiray Hi There:

On your page you seem to have deleted most of the onReady code. To make the code in the image above work you need to understand how the functions are declared and use blocks - the { } that enclose code.

To fix the red dot error in the image you simply need to do two things.
Delete line 22 and replace line 7 with });

The onReady function call is a function which requires its arguments to be between ( AND )
So we start with :

$w.onReady();

Now we want onReady to do something. It expects a function from us to do that. So we give it what is called an anonymous function which looks like this:

function () {
    // Do some things here
}

Now we have to give this as an argument to the onReady function so it now looks like this

$w.onReady(
    function () {
        // Do some things here
    }
);

Most developers will try to reduce the amount of white space by combining things on the same line. This is not a requirement it is a coding style. So you will often see the onReady like this:

$w.onReady( function () {
    // Do some things here
} );

This should help - remember the parethesis () and the braces {} are matched pairs - think of one as Open, (, and the other as Close, ). If you see red dots show up, this is normally the first place to look. This is also why you will see code indented after an Open and outdented after a Close.

Setting your filter

OK your drop down seems to be set up correctly. You seem to have correctly extracted the information for the Product name and the dropdown shows the correct options:


What you need to do (and you are not doing in your code at the moment) is filter the dataset that is being used to show the selected products from the drop down.

The two things you need to do are:

  1. Catch the event that occurs when you change the dropdown value following a selection

  2. Use the selected value to filter AND refresh the dataset.

  3. Catch the new drop down value
    This requires that you understand the Wix Code event handler mechanism which is covered in these two reference documents:

For drop downs my preferred mechanism is to take some action on the onChange() event


NOTE: There are two ways to create an event handler. You should pick one way and NOT both. In the first article above you are shown how to attach an event function to an Element using the Properties Panel. This does the same thing as defining the onChange() handler described to the right. The important thing is to understand that when a dropdown value is selected Wix Code generates an event and calls the function that has been set as the event handler to handle the event.

OK for this mini tutorial we will NOT use the properties panel we will define the handler in code.
We need to do this AFTER the page has loaded in the $w.onReady() handler. We will add this to your existing onReady handler…

$w.onReady(function () {
    // Initialise our page data.
    // Register event handlers
    // Dropdown Change Event
    $w('#dropdown1').onChange(dropdownChanged);
    
    // Initialise our dropdown
    uniqueDropDown1();
});

There are two ways to register an event handler. One is to use an anonymous function (its anonymous because it doesn’t have a name!). The second is to define a function that will be the handler, this is essentially what the Wix Editor Properties Panel does for you.

As you can see we have called our handler dropdownChanged. This is meaningful and tells us what the code is trying to do.

  1. Use the selected value to filter AND refresh the dataset.

Now let’s create our handler. What it need to do is get the value from the dropdown and use it to filter the dataset attached to our products table. Once we have changed the dataset we simply tell the table that it needs to refresh.

We will use these API functions that you should be familiar with:

function dropdownChanged(event) {
    // Assume we will build a dataset filter
    let datasetFilter = wixData.filter();
    // Get the value of the dropdown if one is selected
    // If the selectedIndex of the dropdown is >= 0 then a value exists
    if ($w('#dropdown1').selectedIndex >= 0) {
        // We have a value - get it and build the filter
        let dropDownValue = $w('#dropdown1').value;
        // Filter finds all products matching the dropdown
        datasetFilter = datasetFilter.eq("product", dropdownValue);
    }
    // If we get here either we found a value, in which case the filter will work.
    // or we didn't, which means the dropdown has been reset, in which case the filter is
    // Removed by using an empty query.
    $w('#dataset1').setFilter(datasetFilter)
    .then(() => {
        // The dataset has been filtered so we now refresh the table
        $w('#table1').refresh();
    })
    .catch((error) => {
        // If we get here we have encountered an error so console.log() it for now
        console.log(error.message);
    });
}

I am not quite sure about your multiple data collections. So can you do this? Let’s end this question here and then create a new one with more specific request? This helps focus answers and makes it easier for people to fine them. Also if this answers your original question please mark it as top comment. In any new question try to make the subject clear about the specific problem and perhaps identify the wix API you are having problems with:

e.g. wix-data/wix-dataset: How do I … with multiple data collections?

Hope this helps
Cheers
Steve

1 Like

@stevendc Hi Steve, Once again thank you! I understand the codes more and more…
Am I correct to say that you want me to replace the old dropdownchange event with the one above? I did but it shows me that the dropdownvalue is undefined. Did we miss something?


I understand what you said about how to transform my question and will do that next time.
Cheers!

@hortiray OK a couple of errors which are easy to fix:
Line 48 defines dropdownChanged as the dropdown event handler. The onReady() handler (lines 5 and 10) uses dropdownHasChanged. Pick the name you like and use is in all places :slight_smile:

Line 57 uses dropdownValue (with a lowercase down )which doesn’t exist (my bad sorry). Line 55 defines the variable as dropDownValue (with a capital Down ). The capitalization is important. Again make sure these are the same (which ever you like).

These fixes should do the trick!

@stevendc Thanks Steve, I looked and looked if all text was correct and names the same but missed that. I need to pay more attention to details! I changed the text and received the error shown in the image. https://hortiray.wixsite.com/database/orchard
There is a admin login at the bottom.


UPDATE: I just discovered that the table is attached to the dataset, which is also sorting by row. So the rows are nicely displayed in order but as you mentioned it cannot be done with both coding and in editor. That means we probably have to add the second sorting in the codes as well… I have left this as it is for now…

@hortiray There is a bug on line 57 (which is why the line has a red dot :-). My bad. I have updated my earlier answer.

Basically when you us .eq() you need to compare the value against a field in the data collection. We need to compare against the product field.

Line 57 needs to look like this -

datasetFilter = datasetFilter.eq("product", dropdownValue);

Steve

@stevendc Its amazing! Working like a charm! I understand what you mean with this bug and that it needs to be compared. Changed it and now works perfect! Thank you for your step by step explanation! I will make your previous tutorial answer the top comment!

Also I am continuing with the next step re-using your code to create another dropdown from multiple collections.

Cheers Raymond!

1 Like