tkuchikiの日記

新ブログ https://blog.tkuchiki.net

Symfony2で、「The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class DateTime. ...」というエラーが出る場合について

Entityのカラムをdatetimeで設定した状態で、FormTypeに、

$form->add('created_at', 'text');


のように、'datetime'以外を設定すると、

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class DateTime. You can avoid this error by setting the "data_class" option to "DateTime" or by adding a view transformer that transforms an instance of class DateTime to scalar, array or an instance of \ArrayAccess. 

というエラーが発生する。

この場合、素直に $form->add() に 'datetime' を指定するか、
'text' などを指定する場合は、Datetime オブジェクトを string に置き換えれば対処できる。