DASPRiD / Formidable

PHP 7 form library for handling user input
BSD 2-Clause "Simplified" License
27 stars 7 forks source link

How to work with dates and times #21

Closed chateaux closed 5 years ago

chateaux commented 5 years ago

I have created a form factory as such:

class SomeFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $mapping = (new ObjectMapping([
            'start' => FieldMappingFactory::dateTime(new \DateTimeZone('UTC')),
            'end' => FieldMappingFactory::dateTime(new \DateTimeZone('UTC')),
        ], GameFormData::class))->verifying(new ChecStuff());
        return new Form($mapping);
    }
}

In my form I have added it like so:

<?=$this->bootstrapForm()->inputDate('Start date', $this->form->getField('start'))?>
<?=$this->bootstrapForm()->inputDate('End date', $this->form->getField('end'))?>

Created my own inputDate helper as such:

final class InputDate
{
    use AttributeTrait;

    public function __invoke(Field $field, array $htmlAttributes = []) : string
    {
        if (!array_key_exists('type', $htmlAttributes)) {
            $htmlAttributes['type'] = 'text';
        }

        $htmlAttributes['id'] = 'input.' . $field->getKey();
        $htmlAttributes['name'] = $field->getKey();
        $htmlAttributes['value'] = $field->getValue();
        $htmlAttributes['type'] = 'date';

        $document = new DOMDocument('1.0', 'utf-8');
        $input = $document->createElement('input');
        $document->appendChild($input);
        $this->addAttributes($input, $htmlAttributes);

        return $document->saveHTML($input);
    }
}

In my controller I make sure the correct datetime format is present as such which I copied from the DateTimeFormatter class

    $start = new \DateTime($prg['start']);
    $prg['start'] = $start->format("Y-m-d\TH:i:s.u");
    $end = new \DateTime($prg['end']);
    $prg['end'] = $end->format("Y-m-d\TH:i:s.u");

When code runs, I get this error message:

File: /var/www/local.scratch.com/public_html/application/vendor/dasprid/formidable/src/Mapping/Exception/NestedMappingExceptionTrait.php:24 Message: j Failed to bind start: Call to a member function setTimezone() on boolean

Not 100% sure how to fix this?

DASPRiD commented 5 years ago

You are not supplying a time zone in your date string, thus you have to set the $localTime parameter to true.