diff --git a/app/src/composables/use-item/use-item.ts b/app/src/composables/use-item/use-item.ts index b7ce8542a9..b9e854e6a4 100644 --- a/app/src/composables/use-item/use-item.ts +++ b/app/src/composables/use-item/use-item.ts @@ -1,5 +1,6 @@ import api from '@/api'; import { useCollection } from '@directus/shared/composables'; +import { useFieldsStore, useRelationsStore } from '@/stores/'; import { VALIDATION_TYPES } from '@/constants'; import { i18n } from '@/lang'; import { APIError } from '@/types'; @@ -166,6 +167,54 @@ export function useItem(collection: Ref, primaryKey: Ref r.collection === relation.collection && r.meta?.many_field === relation.meta?.junction_field + ); + + if (relation.meta?.one_field && relation.meta.one_field in newItem) { + const fieldsToFetch = fields + .filter((field) => field.startsWith(relation.meta!.one_field!)) + .map((field) => field.split('.').slice(1).join('.')); + + const existingIds = newItem[relation.meta.one_field].filter((item: any) => typeof item !== 'object'); + + let existingItems: any[] = []; + + if (existingIds.length > 0) { + const response = await api.get(getEndpoint(relation.collection), { + params: { + fields: [relatedPrimaryKeyField!.field, ...fieldsToFetch], + [`filter[${relatedPrimaryKeyField!.field}][_in]`]: existingIds.join(','), + }, + }); + + existingItems = response.data.data; + } + + newItem[relation.meta.one_field] = newItem[relation.meta.one_field].map((relatedItem: any) => { + if (typeof relatedItem !== 'object' && existingItems.length > 0) { + relatedItem = existingItems.find((existingItem: any) => existingItem.id === relatedItem); + } + + delete relatedItem[relatedPrimaryKeyField!.field]; + + if (relation.meta?.junction_field && existsJunctionRelated?.related_collection) { + const junctionRelatedPrimaryKeyField = fieldsStore.getPrimaryKeyFieldForCollection( + existsJunctionRelated.related_collection + ); + delete relatedItem[relation.meta.junction_field][junctionRelatedPrimaryKeyField!.field]; + } + return relatedItem; + }); + } + } + const errors = validate(newItem); if (errors.length > 0) { diff --git a/app/src/modules/content/routes/item.vue b/app/src/modules/content/routes/item.vue index 49f5357205..0f897c6997 100644 --- a/app/src/modules/content/routes/item.vue +++ b/app/src/modules/content/routes/item.vue @@ -474,7 +474,7 @@ export default defineComponent({ async function saveAsCopyAndNavigate() { try { const newPrimaryKey = await saveAsCopy(); - if (newPrimaryKey) router.push(`/content/${props.collection}/${encodeURIComponent(newPrimaryKey)}`); + if (newPrimaryKey) router.replace(`/content/${props.collection}/${encodeURIComponent(newPrimaryKey)}`); } catch { // Save shows unexpected error dialog }