Skip to content

DateTime objects in Neos.Fusion.Form causing string conversion error on validation #105

@ComvationAG

Description

@ComvationAG

Problem

When using Form.Schema.date() fields in Neos.Fusion.Form, the following error occurs only when form validation fails (i.e., not all required fields are filled):

Object of class DateTime could not be converted to string Exception Type: Error

The form works fine when all required fields are properly filled. The error only appears when the form is re-rendered with validation errors.

We are using version 3.0.3.

Root Cause

When form validation fails and the form is re-rendered, the form data containing DateTime objects is passed back to the form fields via Neos.Fusion.Form:Input with type="date".

The AbstractFormObject::stringifyValue() method tries to convert these DateTime objects to strings for rendering in HTML input fields, but it doesn’t have a specific handler for DateTimeInterface objects, causing the fatal error.

The function currently looks like this:

protected function stringifyValue($value): string
{
    if (is_object($value)) {
        $identifier = $this->persistenceManager->getIdentifierByObject($value);
        if ($identifier !== null) {
            return $identifier;
        }
    }
    if (is_array($value)) {
        $value = json_encode($value);
    }
    return (string)$value;
}

Solution

Modify Neos.Fusion.Form Package
Edit AbstractFormObject.php:

<?php
protected function stringifyValue($value): string
{
    // Convert DateTime objects to a safe HTML value string (e.g. for <input type="date">)
    if ($value instanceof \DateTimeInterface) {
        return $value->format('Y-m-d');
    }
    if (is_object($value)) {
        $identifier = $this->persistenceManager->getIdentifierByObject($value);
        if ($identifier !== null) {
            return $identifier;
        }
    }
    if (is_array($value)) {
        $value = json_encode($value);
    }
    return (string)$value;
}

This ensures DateTime objects are properly formatted before being rendered as HTML form values. I believe this is a bug in Neos.Fusion.Form that should be fixed in the core package, as it's a common use case to pre-fill date fields with DateTime values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions