Bug Report: Writing Field in Before Creation Hook is failing

Feature(s) impacted

I have a model with fields A, B, and C. When a new record is created with fields A and B, I’d like to compute the field C, based on the fields B and C.

Observed behavior

Field C is empty after creation.

Expected behavior

Field C should not be empty after creation.

Failure Logs

None

Context

I have created a minimum repository, which recreates the issue. The relevant line is ./index.ts:30

Hello @David_Roegiers :wave:,

Thank you for the repository :pray: , i’m starting to look at your issue

Kind regards,

Florian

Hello @David_Roegiers :wave:
I have some questions for you :slight_smile: Does it have to change in edit? And is it possible for one of the two fields not to be filled in?

Thanks in advance

Hello @Florian_Gonzales

Does it have to change in edit?

Yes, but why is that relevant? I didn’t include it in the scope of this bug report, since it is already working on our end.

And is it possible for one of the two fields not to be filled in?

For the creation, both will always be filled in.

Thanks.

In this case you can use a solution with a replaceFieldWriting :

const getSlugFromContext = async (context:  HookBeforeCreateContext<Schema, 'test'> ) => {
  const slug = `${context.record.firstName.toLowerCase()}-${context.record.lastName.toLowerCase()}`;
  const namesake = await context.collection.list({ conditionTree: { field: 'slug', value: slug, operator: 'Equal' }}, [ '_id'])

  if (namesake.length > 0) {
    return slug;
  }
  
  return slug + 'random_number'
};

collection.replaceFieldWriting('firstName', (value, context) => {
  const delta = { firstName: value };

  if(context.action === 'create') {
    delta.slug =  getSlugFromContext(context);
  }

  return delta
});

If both fields are filled, you can juste place the replaceFieldWriting on a field :slight_smile:

I hope it will help you ! :pray:

Hello @Florian_Gonzales

Thanks for the suggestion, and yes, that works. I even tweaked it a bit to work for edit cases as well. I’m marking this as a solution.

2 Likes