2

I have a date field, and I want it to be possible for this to be empty. How it works now is that if you don't enter a value, it takes today's date. Any suggestions?

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
Wobee
  • 328
  • 2
  • 9

3 Answers3

8

That happens because the date filter returns the current date for null values / empty strings.

If the value passed to the date filter is null, it will return the current date by default.

To work around this, you would add a conditional.

{% if entry.myDate %}
    Date: {{ entry.myDate|date('Y-m-d') }}
{% endif %}

Another way to do this is to use a ternary operator.

{{ entry.myDate ? entry.myDate|date('Y-m-d') }}
carlcs
  • 36,220
  • 5
  • 62
  • 139
2

You can add a new filter to twig that returns an empty string if the date is null or '0000-00-00', or if not reverts to Twig's built in date filter. Here I've called it 'dateInclEmpty' (trying to think of a better name), you can otherwise use it in the same way as the existing date filter.

$filter = function(Twig_Environment $env){
    return new Twig_SimpleFilter('dateInclEmpty', function ($date,$format,$timezone) use($env){
        if (is_null($date) || $date == '0000-00-00'){
            return "";
        }
        else {
            return twig_date_format_filter($env,$date,$format,$timezone);
        }
    });
};
$twig->addFilter($filter($twig));

(Thanks for the advice Lindsey, let's see if this is any better :-P)

leontrolski
  • 121
  • 2
1

For DateTime:

{{ entry.myDate =="0000-00-00 00:00:00" ? "" : entry.myDate|date('Y-m-d') }}

For Date :

{{ entry.myDate =="0000-00-00" ? "" : entry.myDate|date('Y-m-d') }}
Brad Bell
  • 67,440
  • 6
  • 73
  • 143