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?

| improve this question | | | | |
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') }}
| improve this answer | | | | |
  • for completeness {{ entry.myDate ? entry.myDate|date('Y-m-d') : 'XYZ' }} – caramba Mar 19 at 12:02
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)

| improve this answer | | | | |
  • -1 Hacking the core is never a good idea :( – Lindsey D Jan 20 '16 at 15:50
  • I've made it as a new filter instead, hopefully less hacky – leontrolski Jan 22 '16 at 10:49
  • Much better! :) – Lindsey D Jan 22 '16 at 16:15
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') }}
| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.