Optional group field

default discord avatar
mvarendorff10 months ago
18

Is it possible to make a group field optional? Despite even an explicit

required: false

on the group, the type is generated as required. Am I missing anything?

  • discord user avatar
    jmikrut
    10 months ago

    I believe that group fields are set to required or not based on if there are any fields

    within

    a group field that are required or not



    if your group contains ONLY optional fields, it should be optionally typed

  • default discord avatar
    mvarendorff10 months ago

    I see 🤔 So there is no way to say "This whole thing can either be undefined, or if it exists, you are guaranteed to have these fields in it"?



    Especially for reused fields, that would help a lot



    In my specific case, we got a custom file-input that connects to an external service for files (beyond what upload is capable of, sadly), and we'd love to express an optional file



    But if a file is present, stuff like ID, filename and download URL should be required for instance

  • discord user avatar
    jmikrut
    10 months ago

    put a condition on the group



    i think that could do it?



    FYI - to calculate if a field should be marked as required in TS, here's the code:



    https://github.com/payloadcms/payload/blob/master/src/utilities/entityToJSONSchema.ts#L10


    notice how if the field has a condition, that will tell Payload to mark it as optional

  • default discord avatar
    mvarendorff10 months ago

    Feels like a hack but that does indeed work, so I'll take it, thanks!



    Out of curiosity: Why was the decision made to ignore the required field on things like groups?

  • discord user avatar
    jmikrut
    10 months ago

    just because a "group" doesn't really accept data on its own, it's up to the child fields to specify data



    and

    required

    is really not relevant to most things that

    required

    typically means - like, validation, form state, etc



    but i could see how it could affect the typescript types specifically, so i would not be opposed to respecting it within TS type gen

  • default discord avatar
    mvarendorff10 months ago

    I see, thanks for the insight!



    Maybe I'll find some time in the next days to give the TS gen thing a stab then!

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.