Skip Navigation

[Résolu] limit datepicker in view

Ce fil est résolu. Voici une description du problème et la solution proposée.

Problem:
The user would like to filter a view by date against two datetime custom fields.

Solution:
That's tricky, because dates are considered to have the time 00:00:00. So if an event begins and ends on the same day, the view will not find it.

This will require custom code and custom logic. Check the example here https://toolset.com/forums/topic/limit-datepicker-in-view/#post-2227857

Relevant Documentation:

This support ticket is created Il y a 2 années et 5 mois. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 - - 9:00 – 13:00
14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 - - 14:00 – 18:00

Supporter timezone: Africa/Casablanca (GMT+00:00)

Marqué : ,

This topic contains 9 réponses, has 2 voix.

Last updated by Stefan van Perlo Il y a 2 années et 4 mois.

Assisted by: Jamal.

Auteur
Publications
#2224735

I'm trying to limit the date picker on a page to a date within a range.

Example can be seen here:
hidden link

I've tried to appley the code i used in a post form:

jQuery(document).ready(function($) {
setTimeout(function() {
if(jQuery( "input.js-wpt-date" )) {

let today = new Date();
let weekstart = new Date("2022-03-05"); // HIER AANPASSEN NAAR NIEUWE WEEK VAN DE HOOGBEGAAFDHEID

const diffTime = Math.abs(weekstart - today);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
const diffEndDate = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 8;

let mindate = "+" + diffDays + "D";
let maxdate = "+" + diffEndDate + "D";

jQuery("input.js-wpt-date").each(function() {
val = $(this).val();
$(this).datepicker("option", "minDate", mindate);
$(this).datepicker("option", "maxDate", maxdate);
$(this).val(val);
});
}
}, 500 );
});

But i cant get it to work on the datepicker.

View code for the datepicker:

<label for="wpv-wpcf-datum-en-starttijd">[wpml-string context="wpv-views"]Startdatum[/wpml-string]</label>
[wpv-control-postmeta field="wpcf-datum-en-starttijd" date_format="d F" boundary_label_min="wpcf-datum-en-starttijd" boundary_label_max="wpcf-datum-en-eindtijd" url_param="wpv-wpcf-datum-en-starttijd"]

Can you help me?

#2226103

Jamal
Supporter

Languages: Anglais (English ) Français (Français )

Timezone: Africa/Casablanca (GMT+00:00)

Hello and thank you for contacting the Toolset support.

For a view filter you will need to use a different jQuery selector. Use "js-wpv-frontend-datepicker" instead of "js-wpt-date". I tried the following code on the browser console and it seems to work:

jQuery(document).ready(function($) {
    setTimeout(function() {
        if(jQuery( "input.js-wpv-frontend-datepicker" )) {

            let today = new Date();
            let weekstart = new Date("2022-03-05"); // HIER AANPASSEN NAAR NIEUWE WEEK VAN DE HOOGBEGAAFDHEID

            const diffTime = Math.abs(weekstart - today);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            const diffEndDate = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 8;

            let mindate = "+" + diffDays + "D";
            let maxdate = "+" + diffEndDate + "D";

            jQuery("input.js-wpv-frontend-datepicker").each(function() {
                val = $(this).val();
                $(this).datepicker("option", "minDate", mindate);
                $(this).datepicker("option", "maxDate", maxdate);
                $(this).val(val);
            });
        }
    }, 500 );
});

I hope this helps. Let me know if you have any questions.

#2227197

Thanks very much for your help! Unfortunately, this code makes the date picker work only once. The datepicker returns to default after the list gets updated.

Weirdly enough it even makes the datepicker work incorrectly (if you select march 7 for example, it only gives one result, from 13th of march). Strange :S

#2227613

Jamal
Supporter

Languages: Anglais (English ) Français (Français )

Timezone: Africa/Casablanca (GMT+00:00)

Would you allow me temporary access to your website to check this further? Your next reply will be private to let you share credentials safely. ** Make a database backup before sharing credentials. **

I am not sure to understand your last message, can you please provide test steps to reproduce it:
1. I go to xxx
2. I do xxx
3. I expect to have xxx
4. Instead i get xxx

#2227711

Jamal
Supporter

Languages: Anglais (English ) Français (Français )

Timezone: Africa/Casablanca (GMT+00:00)

It seems that the date filter is broken, it needs to be recreated. Before I tried so, I have two questions:
- What would you like to achieve with this date filter? I mean what the formula that you want to use?
- Where did you add the Javascript code? If it is added to the theme, would you allow me FTP access to access the theme files?

#2227713

Ideally, the datefilter should return all the events that take place on that date.
If you select a date (example march 9th)
-it should return all events that start on march 9th
-If an event starts on March 8th, and ends on march 12th those results should be below that.

i added the jquery in the view "home 3"
hidden link

#2227857

Jamal
Supporter

Languages: Anglais (English ) Français (Français )

Timezone: Africa/Casablanca (GMT+00:00)

The view uses AJAX. Each time a search is performed the search form will be updated, and we need to apply the code to it again. Let's extract the code that restricts the datepicker to a function:

function restrictDatePicker($) {
    setTimeout(function() {
        if(jQuery( "input.js-wpv-frontend-datepicker" )) {
 
            let today = new Date();
            let weekstart = new Date("2022-03-05"); // HIER AANPASSEN NAAR NIEUWE WEEK VAN DE HOOGBEGAAFDHEID
 
            const diffTime = Math.abs(weekstart - today);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            const diffEndDate = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 8;
 
            let mindate = "+" + diffDays + "D";
            let maxdate = "+" + diffEndDate + "D";
 
            jQuery("input.js-wpv-frontend-datepicker").each(function() {
                val = $(this).val();
                $(this).datepicker("option", "minDate", mindate);
                $(this).datepicker("option", "maxDate", maxdate);
                $(this).val(val);
            });
        }
    }, 500 );
}

Then, we need to call this function on page load, and after each AJAX call. Check this article https://toolset.com/documentation/programmer-reference/adding-custom-javascript-code-to-views-that-use-ajax/

jQuery(document).ready(restrictDatePicker);
jQuery( document ).on( 'js_event_wpv_pagination_completed', function( event, data ) {
	/**
	* data.view_unique_id (string) The View unique ID hash
	* data.effect (string) The View AJAX pagination effect
	* data.speed (integer) The View AJAX pagination speed in miliseconds
	* data.layout (object) The jQuery object for the View layout wrapper
	*/
	restrictDatePicker(jQuery)
});
jQuery( document ).on( 'js_event_wpv_parametric_search_form_updated', function( event, data ) {
	/**
	* data.view_unique_id (string) The View unique ID hash
	* data.view_changed_form (object) The jQuery object for the View form after being updated
	* data.view_changed_form_additional_forms_only (object) The jQuery object containing additional forms from other instances of the same View inserted using the [wpv-form-view] shortcode
	* data.view_changed_form_additional_forms_full (object) The jQuery object containing additional forms from other instances of the same View inserted using the [wpv-view] shortcode
	*/
	restrictDatePicker(jQuery)
});

This will fix the issues with the datepicker field. For the results filtering, it seems that the current query filter only looks for posts that have a start date greater than the search value. If we choose March 9th, it correctly returns March 13th post as it is greater than the search value.
The query filter needs to be updated to search for posts that have a start date lower than the search value, and an end date greater than the search value. In other words, the posts that are active for the search value. Two query filters like this hidden link

However, this query filters will not work on the events that have a begin and end date on the same day, because the posts' fields are datetimes, where as the search control is a date. This will not also for posts that have a begin date of the same day, because their begin date has a time and it is greater than 00:00:00 time which we are searching with.
To workaround this, I think that we can see if the start date is lower than the last second on the day of the search value. For that reason, we'll need custom code to hook into the view's query filter and change it. Something like this:

add_filter( 'wpv_filter_query', 'search_date_between_datetimes', 10, 3 );
function search_date_between_datetimes ( $query, $view_settings, $view_id ) {
	if( $view_id == 13044 ) {
		foreach( $query['meta_query'] as $key => $meta ){
			if( isset( $meta['key'] ) && $meta['key'] == 'wpcf-datum-en-starttijd' ) {
				// Add the last second of the day  = (24 * 60 * 60) -1 = 86399
				$query['meta_query'][$key]['value'] = 86399 + $query['meta_query'][$key]['value'];
			}
		}
	}
	return $query;
}

Read more about the  filter here https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
It uses an underlying WP_Query instance, which you can check its arguments here https://developer.wordpress.org/reference/classes/wp_query/

I wanted to test this code on your website using a Toolset custom code snippet, but edit is deactivated on your website. Check this screenshot hidden link
I'll need FTP access if you want me check it for you. You can update your previous private reply with FTP credentials.

#2228485

Hi,
Thank you,

I have updated the ftp acces credentials!
Tomorrow i will try to figutre out how to include the datepicker code in the site.

(PS: It looks like there is no file for the customisations present on the path in the screenshot.)

#2228691

Jamal
Supporter

Languages: Anglais (English ) Français (Français )

Timezone: Africa/Casablanca (GMT+00:00)

Using FTP access I was able to add the code to the code snippet. And it seems to work as expected. In fact, I edited the test post again to make the event for March 13th 2022 from 08am to 09pm, and if I search with the same day it gives the expected results. Check this screenshot hidden link

I am sure this code is the correct one, but if you find some unexpected results please let me know if this way:
1. I go to xxx
2. I do xxx
3. I expect to have xxx
4. Instead i get xxx
So, I can understand it better without needing to guess from the existing posts on your website.

#2231513

Thank you sup much for your help! You went above and beyond for this. It works as expected!

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.