How to show date in one format, but store it in another?

158 views Asked by At

In my form I have a fieldset that has a date element:

    $this->add([
        'name' => 'dob',
        'type' => 'date',
        'attributes' => [
            'id' => 'dob',
            'class' => 'form-control',
        ],
        'options' => [
            'label' => 'Date of Birth?',
        ],
    ]);

with the following input filter specification:

        [
            'name' => 'dob',
            'filters' => [
                [
                    'name' => 'date_time_formatter',
                    'options' => [
                        'format' => 'Y-M-d h:i:s.000',
                    ],
                ]
            ],
        ],

When I add an entry (form data is empty), on the front end I get a a date field with drop-down calendar that populates based on my locale (dd/mm/yyyy). This is fine - it goes through my filter when I submit the form the date format is changed and dropped into my db without a problem.

When I edit an entry (form data = ['dob' => '1972-15-07 12:00:00.000']), on the front end the calendar is empty and the console has the message:

> The specified value "1972-15-07 12:00:00.000" does not conform to the required format, "yyyy-MM-dd".

I am using the same view script for multiple forms so am only doing <?php echo $this->form($this->form);?> - meaning I cannot do <?php echo $this->formRow($this->form->get('dob')->dosomething());?>

How can I $form->setData($data); the dob field using the raw db value and have it populate the front-end in a different format? (ideal solution would be limited to manipulation of the element or fieldset only, not the form nor controller).

1

There are 1 answers

0
ARN On

you can convert your date to a format accepted by your calendar plugin:

$date = date('d/m/Y', strtotime($date));