#Can't Unset Field in `afterChange` Hook

6 messages · Page 1 of 1 (latest)

paper jasper
#

As the title states, I'm trying to use the afterChange hook in a group field (with a nested row) to unset a child field if a sibling is unset (so essentially both become null). But this doesn't work:

{
  name: "basePackage",
  type: "group",
  fields: [
    {
      type: "row",
      fields: [
        {
          name: "basePackage",
          type: "relationship",
          relationTo: "health-insurance-packages",
        },
        {
          name: "premium",
          type: "number",
          admin: {
            condition: (_, siblingData) =>
              siblingData.basePackage != null,
          },
        },
      ],
    },
  ],
  hooks: {
    afterChange: [
      ({ value }) => {
        if (value?.basePackage != null) return value;
        return { basePackage: null, premium: null };
      },
    ] satisfies FieldHook<
      IHealthInsuranceComparison & { id: string },
      NonNullable<
        IHealthInsuranceComparison["combinations"]
      >[number]["basePackage"]
    >[],
  },
},```
Is this a limitation due to the nested usage of `group` and `row` or am I doing something wrong to trigger an unset?
ashen ravineBOT
robust python
#

Use beforeChange on the group, not afterChange.

#

afterChange runs after the document is saved, so clearing premium there only tweaks the response object. It doesn’t update what’s stored.

beforeChange runs before the write, so returning
{ basePackage: null, premium: null }

when the relationship is cleared actually persists both as null.

#

Same hook logic; wrong lifecycle hook was the issue, not the group + row structure.

hot crest
#

Another solid answer here @robust python ! Only thing I'd add here is the hook should also guard against value being undefined, which could happen on creation if the group hasn't been populated yet

beforeChange: [
  ({ value }) => {
    if (!value || value?.basePackage != null) return value
    return { basePackage: null, premium: null }
  },
]