New field is not written on onBeforeWrite

Silverstripe Version: 4.13

Question: I added a new field to schema and set a value in onBeforeWrite and it does not save

I have a DataObject with a form, I added a field 'LatestRelease' => 'Datetime'.
I set the value in onBeforeWrite, $this->LatestRelease = $this->Releases()->last()->Created; LatestRelease is not edited by user in CRM form.

For a sanity check I did $this->Title = 'fixed title'; with an existing field, which the user edited in the CRM form. That one updates properly.

Let the hook finish with parent::onBeforeWrite

PS. I am also using Versioning

private static $db = [
        'Title' => 'Varchar(200)',
        'LatestRelease' => 'Datetime',
    ];
...
public function getCMSFields()
    {
        $title_field = TextField::create(
            'Title',
            _t("LibreOffice\Extensions\Extension.CMSFormTitle", 'The Title for the extension')
        );
...
// LatestRelease is not added here since it's an internal use only field, not sure if it matters
return $fields;
}
...
public function onBeforeWrite()
    {
        $isPublishing = $this->getSourceQueryParam('Versioned.stage') == 'Live';

        if ($isPublishing) {
            $mostRecentRelease = $this->Releases()->last();
            if ($mostRecentRelease) {
                // I have a log here and I am sure this code is executed
                $this->LatestRelease = $mostRecentRelease->Created;
                $this->Title = 'fixed title';
            }
        }
        parent::onBeforeWrite();
    }

Did you do a dev/build to make sure the column exists in the database?

Yes, indeed to confirm if the field is saved I query the db and I see a null value before and after the hook is executed.

I recommend stepping through with a debugger and seeing what the code is actually doing. Could be your condition is never true for some reason.

I debugged step by step and indeed it was not entering the condition, my problem was that onBeforeWrite the object was not Version.LIVE so i could not query for it, I had to query for Staged objects and now it works

1 Like