Skip to content

Duplicate Selected Locales: content is empty when the admin active locale is not among the selected locales (remaining case after #15849) #17562

Open

Description

@p11yadrian

Describe the Bug

Follow-up to #15847 / #15849 (fixed in v3.83.0) and #15655. Those fixed the filtering so localized block content is no longer dropped. A related case remains on v3.86.0:

"Duplicate Selected Locales" produces a document with empty localized content whenever the admin's active locale is NOT one of the selected locales.

Root cause

In packages/payload/src/duplicateDocument/index.ts (getDuplicateDocumentData), the source doc is first correctly narrowed to the selected locales:

duplicatedFromDocWithLocales = filterDataToSelectedLocales({
  configBlockReferences: payload.config.blocks,
  docWithLocales: duplicatedFromDocWithLocales,
  fields: collectionConfig.fields,
  selectedLocales,
})

I verified this step is correct now — for selectedLocales: ['en'] it preserves content: { en: [...] } with all inner block values intact.

The problem is the next step, which resolves that already-filtered doc back to a single locale:

const duplicatedFromDoc = await afterRead({
  ...
  doc: deepCopyObjectSimple(duplicatedFromDocWithLocales),
  locale: req.locale,       // the admin's ACTIVE locale
  fallbackLocale: null,     // hardcoded — ignores the configured fallback
  ...
})

When req.locale (the admin's active locale) is not in selectedLocales, the with-locales doc no longer contains req.locale (it was just filtered out), and with fallbackLocale: null there is no fallback — so every localized field resolves to empty. The new document is created with empty content.

This is independent of field type; it affects any localized field and is fully determined by whether req.locale ∈ selectedLocales.

Link to the code that reproduces this issue

Same setup as #15847 — https://github.com/jakobpevec/payload-issue-repro — with one added step: change the admin's active locale to a locale you do not select.

Reproduction Steps

Collection with a localized blocks (or richText) field and ≥2 locales (e.g. en, de), and a document with content in both.

  1. Open the document.
  2. In the admin, switch the active locale (top-right locale selector) to de.
  3. Open Duplicate → Duplicate Selected Locales and select only en.
  4. Duplicate.

Actual: the duplicated document's localized content is empty.
Expected: the duplicated document contains the en content.

Control (proves the rule): with the active locale set to en (active locale ∈ selected), the same steps copy the content correctly. Verified across a full matrix — content is preserved iff the active locale is one of the selected locales:

active locale selected content copied
en [en] ✅
de [en] ❌ empty
de [de] ✅
en [de] ❌ empty
en [en, de] ✅
de [en, de] ✅
fr [en, de] ❌ empty

Suggested fix

Resolve afterRead with a locale guaranteed to survive the filter — e.g. use req.locale when it is in selectedLocales, otherwise the first selected locale — and/or honor the configured fallback instead of hardcoding fallbackLocale: null.

Which area(s) are affected? (Select all that apply)

area: localization, area: admin

Environment Info

  • Payload version: 3.86.0
  • Database adapter: @payloadcms/db-postgres
  • Node.js: 22

Activity

  1. added
    area: localization
    and removed on Jul 30, 2026
  2. luantaraschi commented on Aug 6, 2026

    @luantaraschi

    I tried to implement the suggested fix and found that it breaks an existing test. Posting what I verified so nobody else spends the same evening on it.

    The bug is worse than "empty content" — it can throw

    Reproduced on main (MongoDB) with withRequiredLocalizedFields from test/localization, which has a required localized blocks field and a required localized title:

    const doc = await payload.create({ collection: withRequiredLocalizedFields, data: {...}, locale: 'en' })
    await payload.update({ id: doc.id, collection: withRequiredLocalizedFields, data: {...}, locale: 'es' })
    
    await payload.duplicate({
      id: doc.id,
      collection: withRequiredLocalizedFields,
      locale: 'es',              // active locale
      selectedLocales: ['en'],   // does not include it
    })

    Result — not an empty document, a hard failure:

    ValidationError: The following field is invalid: Title
      ❯ beforeChange packages/payload/src/fields/hooks/beforeChange/index.ts:77:11
      ❯ createOperation packages/payload/src/collections/operations/create.ts:230:29
    

    So when a localized field is required, the whole duplicate is rejected rather than silently emptied. Same precondition you identified: active locale ∉ selectedLocales.

    Why the suggested fix doesn't work

    I applied exactly the first suggestion — read at req.locale when it survives the filter, otherwise the first selected locale:

    const readLocale =
      selectedLocales?.length && req.locale && !selectedLocales.includes(req.locale)
        ? selectedLocales[0]!
        : req.locale!

    That does clear the ValidationError. But it then fails the existing test should retain non-localized fields when duplicating select locales (test/localization/int.spec.ts:1652):

    AssertionError: expected 'spanish' to be undefined
      1652|  expect(allLocales?.title?.en).toBe(undefined)
    

    The reason is that duplicatedFromDoc being empty is load-bearing. duplicateOperation calls createOperation with data: {}, and beforeChange writes its single-locale doc argument at req.locale. So today:

    • selected locales survive through docWithLocales, which is why duplication works at all;
    • the active locale stays empty because duplicatedFromDoc resolved to nothing.

    Resolving that read at a locale that survived the filter therefore copies the selected locale's content into the unselected active locale — which is the opposite of what "Duplicate Selected Locales" means.

    So the real question

    The empty duplicatedFromDoc is doing two jobs at once: it is the validation subject and the source that beforeChange writes at req.locale. Any fix that makes it non-empty pollutes an unselected locale; leaving it empty keeps the validation failure. Those two need separating — e.g. skipping required validation for locales that aren't being written — and that's a design call rather than a patch, which is why I'm not opening a PR.

    Two things I did not verify: I was on MongoDB, not Postgres, so I can't speak to whether the selected-locale content is also dropped on db-postgres as you describe. And I didn't test the fallbackLocale: null half of your suggestion, since the locale half already broke a test.

  3. p11yadrian commented on Sep 1, 2026

    @p11yadrian
    Author

    Thanks for digging into this, @luantaraschi — that confirms what we found independently on Postgres (push:true, minimal repro config, no plugins/hooks): the content is not actually dropped for optional fields. duplicatedFromDoc resolving empty is intentional — it's what beforeChange writes at req.locale, and it's the reason the unselected active locale correctly stays blank instead of getting polluted with the selected locale's content. So the "empty duplicate" report is a UI-only symptom for optional fields; your ValidationError repro is the real remaining bug.

    Agreed that "read afterRead at a locale that survives the filter" is the wrong axis to fix — it necessarily writes selected-locale content into an unselected locale, which is exactly what breaks int.spec.ts:1652.

    The angle we hadn't seen tried: leave duplicatedFromDoc empty (don't touch the read/write path at all) and instead skip validation for this one case, in createOperation:

    const skipValidation =
      incomingSkipValidation ||
      Boolean(
        duplicateFromID &&
          selectedLocales?.length &&
          locale &&
          !selectedLocales.includes(locale),
      )

    Reasoning: when req.locale ∉ selectedLocales, the duplicate is always going to write nothing at req.locale for localized fields — that's correct, by design, regardless of whether the field is required. The only thing that changes today based on required is whether that correct-but-empty write throws or silently succeeds. Skipping validation for exactly this precondition makes required and optional fields behave the same way (empty at the unselected locale, present at the selected ones), and doesn't touch the write path your test depends on — so int.spec.ts:1652 should hold unchanged, since nothing about what gets written at req.locale changes.

    Caveat: I don't have a monorepo checkout, so this is unverified against the actual suite — someone with the checkout should run test/localization/int.spec.ts plus a case matching your withRequiredLocalizedFields repro before treating this as more than a direction. If it holds, the same widened skipValidation should also cover the Postgres path, since it doesn't touch DB-adapter-specific code.

  4. luantaraschi commented on Sep 4, 2026

    @luantaraschi

    I have the monorepo checkout, so I ran it. Your direction holds, and it does not break int.spec.ts:1652.

    On main at c837756b, with my repro added to the Duplicate Collection describe as a 121st test, test/localization/int.spec.ts gives 120 passing and that one failing with ValidationError: The following field is invalid: Title. With the widened skipValidation, all 121 pass. The test the earlier read-locale suggestion broke passes untouched.

    One adjustment to the snippet. createOperation has no incomingSkipValidation. The line it passes today is:

    skipValidation: isSavingDraft && !hasDraftValidationEnabled(collectionConfig),

    So the same idea lands as:

    skipValidation:
      (isSavingDraft && !hasDraftValidationEnabled(collectionConfig)) ||
      Boolean(
        duplicateFromID &&
          selectedLocales?.length &&
          locale &&
          !selectedLocales.includes(locale),
      ),

    duplicateFromID, selectedLocales and locale are all already destructured at the top of the operation, so nothing else has to move.

    While checking it I found the reason this is more than a run of green tests. beforeChange validates one locale, not the document. Its own docblock says the input data is the normal document for one locale, and the gate in fields/hooks/beforeChange/promise.ts:165 reads siblingData[field.name], with the validate context built from doc and siblingDoc. Those are duplicatedFromDoc, which is the read at req.locale. docWithLocales never reaches validation at all, it only feeds the locale merge on the way to storage.

    Under your precondition, then, the only locale being validated is the one that is empty by design. Skipping it gives up nothing that was previously enforced, which is why the write path stays put and :1652 survives. That separates the two jobs the empty duplicatedFromDoc was doing, without making it non-empty.

    One thing the change does loosen. duplicateOperation calls create with data: incomingArgs?.data || {}, so a caller that passes data to payload.duplicate() while the active locale sits outside selectedLocales would have that data skip validation too. The admin Duplicate action sends none, but the API allows it. Adding an empty-data condition to the new clause would close that, if it is worth closing.

    The test I used:

    it('required localized fields with the active locale unselected', async () => {
      const doc = await payload.create({
        collection: withRequiredLocalizedFields,
        data: {
          nav: { layout: [{ blockType: 'text', text: 'english text' }] },
          title: 'hello',
        },
        locale: defaultLocale,
      })
    
      await payload.update({
        id: doc.id,
        collection: withRequiredLocalizedFields,
        data: {
          nav: { layout: [{ blockType: 'text', text: 'texto espanol' }] },
          title: 'hola',
        },
        locale: spanishLocale,
      })
    
      const duplicated = await payload.duplicate({
        id: doc.id,
        collection: withRequiredLocalizedFields,
        locale: spanishLocale,
        selectedLocales: [defaultLocale],
      })
    
      const allLocales = await payload.findByID({
        id: duplicated.id,
        collection: withRequiredLocalizedFields,
        locale: 'all',
      })
    
      expect(allLocales.title.en).toBe('hello')
      expect(allLocales.title.es).toBeUndefined()
      expect(allLocales.nav.layout.en[0].text).toBe('english text')
      expect(allLocales.nav.layout.es ?? null).toBeNull()
    })

    Worth knowing if anyone reuses it: title.es comes back undefined but nav.layout.es comes back null, so the blocks field needs the looser assertion.

    Still unverified on Postgres. I am on MongoDB, same as last time.

    Happy to open the PR with the change and this test if that is useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    (Select all that apply) area: localizationarea: localization

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions