Skip to content

[5.x]: Cannot add uploaded assets with \craft\fields\Asset anymore due to BaseRelationField::normalizeValue change #15707

@Anubarak

Description

@Anubarak

Sorry if this should have been a discussion / suggestion. I'm not sure if it's a breaking change/bug or not since my usage was never intended in the first place but worked

Description

I used to upload additional assets to asset fields by setting it's field value to the original ids after calling setFieldValuesFromRequest. This worked great until one of the last updates... My process was the following.

$entry->setFieldValuesFromRequest('fields');
$entry->setFieldValue('images', $oldImageIds);

This will let \craft\fields\Asset to search for uploads plus the field will contain a query to all the existing Uploads so it will add them.

cms/src/fields/Assets.php

Lines 568 to 572 in 5e56c6d

if (is_array($query->id)) {
$query = $this->normalizeValue(array_merge($query->id, $assetIds), $element);
} else {
$query = $this->normalizeValue($assetIds, $element);
}

In the lines above, $query->id will contain the previous ids since I set them.
However, due to your change in BaseRelationField

2ce4b5b#diff-dd150284a0df94daa2918aaacda81e6ad9b20bac8d429414043f37120a5769ddL677-L680

$query->id does not include the asset ids anymore and there is no real way to add assets to the existing one instead of overwriting them all.
I know I used an "unsupported" hack to achieve my goal but since adding/uploading additional assets to an entry is a common task for me, I really hope you could add an event or some other way to achieve this. As of now, I "fixed" it with the following code.

$entry->setFieldValuesFromRequest('fields');
$entry->setFieldValue('images', $oldImageIds);
$entry->getFieldValue('images')->id = $oldImageIds;

Which is of cause bad and I do not want to do this.

I considered it as a "kind of bug" since you are using $query->id at one place and $query->andWhere at the other place at least that should be consistent.

Craft CMS version

5.4.x

PHP version

8.3

Operating system and version

No response

Database type and version

No response

Image driver and version

No response

Installed plugins and versions

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions