Filter column image based on today's date

Hi there,

I have a website where I want to display a different image of the day each day. I’m currently using boolean logic to filter the homepage column background based on whether it is ‘current’ or not. However, I would like to add images into the database in advance and have it automatically update based on it showing the image that has today’s date in the ‘date’ field in the collection.

I have tried the following code which I found for a similar problem on Corvid but have had no avail as I get a ‘#dailyimage’ does not have the property ‘.src’

import wixData from 'wix-data';

$w.onReady(function () {
 let localDate = new Date();
    wixData.query('datetoimage')
        .lt('minDate', localDate)
        .gt('maxDate', localDate)
        .find().then(results => {
            console.log(results)
            $w('#dailyimage').src = results.items[0].image;
        });
});

Could you advise how I can filter the database accordingly? Many thanks

1 Like

Nayeli (Code Queen) has a great example that you can look at here.
https://www.totallycodable.com/example-timed-content

I was typing this response when GOS posted the link to Nayeli’s wonderful examples. I’ll post this anyway as it deals directly with your code.

Provided that the date entered in a collection field that I’m calling “imageDate” does not have hours, minutes, and seconds, the code below would achieve what you are after:

$w.onReady(function () {
    let localDate = new Date();
    let yearValue = localDate.getFullYear();
    let monthValue = localDate.getMonth();
    let dayValue = localDate.getDate();
    let dateValue = new Date(yearValue,monthValue,dayValue,0,0,0);

    wixData.query('datetoimage')
    .eq('imageDate', dateValue)
    .find().then(results => {
        console.log(results)
        $w('#dailyimage').src = results.items[0].image;
    });
});

If the date entered in the collection does have hours, minutes, and seconds, then you could create a minimum and maximum date value for that calendar date and use the between function with it.

$w.onReady(function () {
    let localDate = new Date();
    let yearValue = localDate.getFullYear();
    let monthValue = localDate.getMonth();
    let dayValue = localDate.getDate();
    let dateValue1 = new Date(yearValue,monthValue,dayValue,0,0,0);
    let dateValue2 = new Date(yearValue,monthValue,dayValue,23,59,59);

    wixData.query('datetoimage')
    .between('imageDate', dateValue1, dateValue2)
    .find().then(results => {
        console.log(results)
        $w('#dailyimage').src = results.items[0].image;
    });
});

Some documentation on the “get” functions used above: JavaScript Date Methods

@tony-brunsman Thank you for this. Before I try it, I also have some information displayed beside the image from the dataset. In this case, should I filter the dataset using this method rather than the image itself?

You can see the section halfway down the homepage here: http://www.lightingnrig.com

To clarify, each entry in my dataset will have a date assigned to it, if today’s date matches a date in the dataset, the homepage should display that image along with the information displayed on the left from my dataset

From your original post comments and code, it wasn’t obvious that you were using a dataset on the page. There are two ways to populate a table and refine its results: 1) use a dataset and the setFilter function or 2) the above approach, querying a collection directly and assigning those values in code.

If you are using a dataset named “dataset1” that is assigned the collection “datetoimage”, this code would achieve the same thing as the second example in my previous post. Since it will be filtered on that record, you will be able to display any other information from that record on the page.

$w.onReady(function () {
    $w("#dataset1").onReady( () => {
        let localDate = new Date();
        let yearValue = localDate.getFullYear();
        let monthValue = localDate.getMonth();
        let dayValue = localDate.getDate();
        let dateValue1 = new Date(yearValue,monthValue,dayValue,0,0,0);
        let dateValue2 = new Date(yearValue,monthValue,dayValue,23,59,59);
        $w("#dataset1").setFilter( wixData.filter()
        .between('image', dateValue1, dateValue2)
        );
    });
});

I got it working! Thanks for your help

@tony-brunsman On a related note, if today’s image is displayed on the homepage, it’s boolean value for a field called ‘current’ should be ‘true’, so it is not shown in a separate gallery of ‘Previous Photos’. How can I amend this code to change the ‘current’ field of the displayed image to ‘not true’ once today’s date has passed, thus allowing it to display in the other gallery?

@tony-brunsman Morning, sorry for jumping in, but… could i do something like this to see if the current user has added to the dataset on the current day? i have button1 connected to dataset1 but i only want to disable the submit button if the current user has already submitted on the current day?
Thanks in advance for any help you can give…

@stedmanmp If you are not already submitting the user ID to this collection tied to dataset1, you should. Then you can run a query to see if they have submitted yet on that particular date.

@gavincoll Conceivably, you could handle this in page code, but it would be much more reliable to schedule a job that would run at midnight every night and change the value of the current field to false for any record where it’s not the current date.

@tony-brunsman Could you advise how I would go about this in code? I’m quite new to coding so help would be appreciated

@gavincoll If the separate gallery is on a separate page, this would be a way to handle the updating of the outdated current field values in page code. Scheduling a job would still be the better way to do it, but alas that may be intimidating at this point since you are new to coding. So,
put this on the separate gallery page.

$w.onReady(function () {
    wixData.query('datetoimage')
    .lt('image', dateValue1)
    .or(
    wixData.query('datetoimage')
    .gt('image',dateValue2)
    )
    .find()
    .then(results => {
        console.log(results);
        let updateArray = [];
        // Loop through results of those that are true
        // and out-of-date, change the value to false
        // and then add the item to the updateArray.
        for (var i = 0; i < results.items.length; i++) {
            let thisItem = results.items[i];
            if (thisItem.current){
                thisItem.current = false;
                updateArray.push(thisItem);
             }
        }
        // Now, update the collection records with this array of  
        wixData.bulkUpdate('datetoimage',updateArray)
        .then( (bulkresults) => {
            // this will return an array showing the IDs of the
            // updated records.
            console.log(bulkresults);
        })
        .catch( (err) => {
           console.log(err);
        });
    });
}

@tony-brunsman Thank you I will try this. My second gallery is on the same page, is the code still applicable?

@gavincoll If you shifted the dataset filtering code to below the “.then( (bulkresults) => {” line, it should be applicable. I say “should” because I’m not able to test it on your page.

Be sure to ask any questions you have about the code if it doesn’t make sense to you. That’s the purpose of the forum.

@tony-brunsman Thank you - I get a parsing error of an ‘unexpected token’ from the last } bracket, would you know why this would be?

@gavincoll Generally, speaking, every left parenthesis and brace has to have a right corollary closing the function. Do a little trial and error to figure out where that may be. The API reference is replete with examples of the syntax expected. Do post the code if you are getting nowhere with it.

@tony-brunsman If I try and close this function, it now throws an error for datevalue1 and datevalue2, saying they are not defined.

import wixData from 'wix-data';
//calculateDate;
$w.onReady(function () {
$w("#dataset1").onReady(() => {
let localDate = new Date();
let yearValue = localDate.getFullYear();
let monthValue = localDate.getMonth();
let dayValue = localDate.getDate();
let dateValue1 = new Date(yearValue, monthValue, dayValue, 0, 0, 0);
let dateValue2 = new Date(yearValue, monthValue, dayValue, 23, 59, 59);
$w("#dataset1").setFilter(wixData.filter()
.between('date', dateValue1, dateValue2)
);
});
});
$w.onReady(function () {
wixData.query('#dataset2')
.lt('date', dateValue1)
.or(
wixData.query('#dataset2')
.gt('date', dateValue2)
)
.find()
.then(results => {
console.log(results);
let updateArray = [];
// Loop through results of those that are true
// and out-of-date, change the value to false
// and then add the item to the updateArray.
for (var i = 0; i < results.items.length; i++) {
let thisItem = results.items[i];
if (thisItem.current) {
thisItem.current = false;
updateArray.push(thisItem);
}
}
// Now, update the collection records with this array of
wixData.bulkUpdate('#dataset2', updateArray)
.then((bulkresults) => {
// this will return an array showing the IDs of the
// updated records.
console.log(bulkresults);
})
.catch((err) => {
console.log(err);
});
});
});

@tony-brunsman Thanks for the reply. The ID. Owner, Created date are added automatically? i didn’t add them but they are showing on there. Its the running the query part i am having the issue with, i am ok with copying and changing values to make them work but i have not yet managed to write something (that works anyway). Do i need to run 2 queries for ID and Date or could i do them together and filter? if i could get this right then i could disable the button if there are any results. Thanks for you help

@gavincoll You have two page onReadys; you can only have one. You know, this is some intermediate coding that I’m doing here. The variables dateValue1 and dateValue2 are out of scope and not accessible.