Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make setting field values via Entry::EVENT_BEFORE_SAVE work when $firstSave is true #15372

Merged
merged 7 commits into from
Jul 18, 2024

Conversation

i-just
Copy link
Contributor

@i-just i-just commented Jul 17, 2024

Description

Setting field values via Entry::EVENT_BEFORE_SAVE doesn’t work when $firstSave is true.

This happens (in v5 only) because in _saveElementInternal(), we no longer always save the element’s content.

Example code:

Event::on(
    Entry::class,
    Entry::EVENT_BEFORE_SAVE,
    function (ModelEvent $event) {
        $entry = $event->sender;

        if ($entry->sectionId == 14 && $entry->firstSave) {
            $entry->setFieldValues([
                'number' => 6,
            ]);
        }
    }
);

The order of operations is: ElementsController->actionApplyDraft() is called, then Elements->_saveElementInternal(). At that point, $element->firstSave is false, so when EVENT_BEFORE_SAVE is called, the condition is not met, and the field values are not set. The $saveContent is true at this point, so content is saved, but since field values weren’t set, this doesn’t result in the desired change.

Then Drafts->applyDraft() gets called, then Drafts->removeDraftData(), and that’s what sets $element->firstSave to true. However, when it later calls Elements->_saveElementInternal(), it calls it with $saveContent set to false, so EVENT_BEFORE_SAVE is called, the condition is met, and the field values are set, but the content is not actually saved.

Related issues

#15369

@i-just i-just requested a review from brandonkelly July 17, 2024 14:06
@brandonkelly
Copy link
Member

The only point of that saveElement() call from removeDraftData() is to get draftId removed from the element. We’re explicitly saying we don’t want content to be saved, so I think saveElement() should respect that, even if a plugin changes a field value in the process.

Maybe we should just start communicating the intention by adding a saveContent property on the element?

@brandonkelly brandonkelly merged commit ac4a1db into 5.x Jul 18, 2024
@brandonkelly brandonkelly deleted the bugfix/15369-event-before-save-and-first-save branch July 18, 2024 16:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants