[5.x] Element relations not saved when creating an element with Craft::createObject()
#16942
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
Noticed a quirk/bug when creating an element using
Craft::createObject()
and setting data on a element relation custom field.The test code for creating an entry is as follows:
With this code the element saves and if you view the element in the CP or look at its content in the DB everything looks correct. The related element shows up in the field etc.
However, no rows are added to the
relations
DB table. This means that if you were to do an element query e.g.Entry::find()->relatedTo([123])->one()
the entry would not be returned.Tracked this issue down to two parts.
Because the element is being created with
createObject()
and mass assignment the$_initialized
property on the element is still false when it hits the following bit of code, so the field is not marked as dirty.cms/src/base/Element.php
Lines 5056 to 5058 in f48af60
This however doesn't stop the content from saving, but in the case of a relationship field it prevents the relation from saving in the
updateRelations()
method when figuring out if the field should be included.cms/src/base/Element.php
Lines 6199 to 6205 in f48af60
To get the ball rolling on a solution for this I took the idea that if this element is a brand new element we can pass
$isNew
from theafterSave()
toupdateRelations()
. As, in theory, if it is new we probably want to be trying to save all the data we can.Related issues
craftcms/commerce#3931