2

I'm trying to use Craft's native datepicker with a plugin I've made for the admin section.

I've got some code that works;

{% from "_includes/forms" import date %}

<h3>Start Date</h3>

{{ date({
    id: 'startDate',
    name: 'startDate',
    value: now
}) }}

but I can't seem to get it to work with any other date, no matter what I do.

In my URL I have;

startDate=09/02/2017

and in my twig template I have;

{% set startDate = craft.request.getParam('startDate') %}

What do I need to do to startDate in order to get the date picker to read that date?

2

Unfortunately, what you're trying to do, is not possible without writing a simple plugin to return a Craft\DateTime object that the day picker can work with.

The global variable now, is a Craft\DateTime object, which the date picker is happy to work with because it can call localeDate() on it.

However, anything returned by date or date_modify twig filters, will be a \DateTime object, which lacks functionality that the date picker relies on.

Your only option would be, to create a simple plugin that can take your date parameter, and return a Craft\DateTime object, which you can pass as a value to the date picker/date macro.

This is one of those things that you think, "this should be easy or at least possible", but I haven't found a twig-only solution yet.

  • This is one of the main reasons (along with about 100 others), that we've ditched the Craft\DateTime class in Craft 2 and are just using PHP's native DateTime everywhere in Craft 3. – Brad Bell Feb 21 '17 at 18:54
  • @BradBell Craft 3 FTW:) – Selvin Ortiz Feb 21 '17 at 19:16
2

I achieved this by putting this into my variables file;

public function craftDate($date) {

     $dateObject = DateTime::createFromString($date,craft()->timezone);

     return $dateObject;

 }

and then calling this in my template by using;

{{ date({
    id: 'startDate',
    name: 'startDate',
    value: craft.formExport.craftDate(reconfiguredStartDate)
}) }}

(The date had been reconfigured from 01/02/2017 to 2017-02-01)

0

The Twig Perversion plugin has a date_from_string filter that turns a string into a Craft\DateTime object.

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.