Search code examples
datetimefieldvariable-assignmentpimcore

Pimcore: Setting DateTime Class Fields on Objects


I'm writing an importer and am getting stuck with actually creating the objects. Specifically, I'm having troubles with DateTime fields. I have a class called blogArticle and I'm using them just as the Pimcore demo data uses them for blog articles.

$newPost = new Object\BlogArticle();
$newPost->setCreationDate( time() );
$newPost->setPublished( true );

$newPost->setText( $text );      // text input field
$newPost->setTitle( $title );    // text input field
$newPost->setDate( $date );      // datetime input field

$newPost->setKey( \Pimcore\File::getValidFilename( $key ) );
$newPost->setParentId( $id );
$newPost->save();

The exact error I am getting is:

Whoops\Exception\ErrorException thrown with message "Call to a member function getTimestamp() on a non-object"

Stacktrace:
#0 Whoops\Exception\ErrorException in /.../pimcore/models/Object/ClassDefinition/Data/Datetime.php:73

I cannot find anything in the documentation apart from how the value is stored in the database for this field type. Literally zero documentation on how to appropriately assign values to class fields per field type.


SOLUTION

Thanks to Igor Benko on solving this one!

$newPost_date = new DateTime( "2016-07-01 12:10:37" );
$newPost->setDate( $newPost_date );

Solution

  • It seems that your system is still set to use the Zend_Date. DateTime is used only if you have a clean install of Pimcore 4, otherwise the compatibility layer is turned on by default after the update. The compatibility layer uses Zend_Date instead.

    In your system.php you have to turn the flag useZendDate to false in order to use DateTime class.

    You need to pass an instance of DateTime class to the setter. Something like this:

    $date=new DateTime("2016-07-01 12:10:37");
    $newPost->setDate($date);
    

    See this: https://www.pimcore.org/wiki/display/PIMCORE4/Update+from+Version+3.x+to+Version+4#UpdatefromVersion3.xtoVersion4-PHP%27sDateTimereplacesZend_Date

    EDIT: Updated the answer after @GrafikMatthew updated his question.