Resolving "Warning: date_timezone_set() expects parameter 1 to be DateTime" in a date-based contextual filter view
This morning someone tweeted at me about a problem with the out-of-the-box archive view in Drupal. I have a lengthy post about recreating that view, and the same problem was occurring in my recreated one. If you have a date-based contextual filter -- for example, my /posts-by-date/201301 view where 201301 is the filter value -- and you put a non-date value in that URL, like /posts-by-date/foobar, Drupal throws this error:
Warning: date_timezone_set() expects parameter 1 to be DateTime, boolean given in format_date() (line 2006 of /home/MYSITE/public_html/includes/common.inc).
Warning: date_format() expects parameter 1 to be DateTime, boolean given in format_date() (line 2016 of /home/MYSITE/public_html/includes/common.inc).
This is actually really logical. Your view has been told to look for a date by your contextual filter, and you're giving it a value that isn't a date. The person who tweeted me had it happen with old WordPress URLs, which didn't have the same structure as the ones on the new site.
Fixing this, in the out-of-the-box view or a recreated one, is straightforward:
- Open your contextual filter. Under "When the filter value is in the URL or a default is provided," check Specify validation criteria.
- On the validator dropdown that will appear, select Numeric.
- On the action to take dropdown, select Show "Page not found."
This makes it return a 404 on non-numeric values, which is the behavior we want. Easy enough, but a quick Google search shows that plenty of sites have this problem.
I've also added this information to the original writeup.