Posting a solution for strapi versions above 4.5.0
To check if relation field is filled every time you change it you have to:
“check strapi data” - I check strapi data by doing this:
It goes through array of fields to “check” and it returns the field value if field was changed or false
function checkField(data, fieldName) {
const field = data[fieldName]
return { [fieldName]: field.connect.length > 0 && { id: field.connect[0].id} }
}
function checkContentData(data, fieldsArray) {
const checkedData = fieldsArray.reduce((result, field) => {
result[field] = checkField(data, field)[field];
return result;
}, {});
return {
...data,
...checkedData
}
}
and use it in lifecycles while passing an array of relation fields I want to check
so:
const checkedData = checkContentData(data, ['field_name', 'field_name_2'])
This gets you a connect value, you only use disconnect in if statements below
in if statement you must use the data from
const { data } = event.params;
but in your validation logic you pass in checkedData, because you only validate it if it was disconnected
This is used in beforeUpdate lifecycle:
if(data.field_name.disconnect.length === 1 && data.field_name.connect.length === 0) {
if(!checkedData.field_name) {
throw new ForbiddenError('relation field is empty)
}
}
This is used in beforeCreate:
because if it wasn’t touched then you know it’s empty
if(data.field_name.disconnect.length === 0 && data.field_name.connect.length === 0) {
if(!checkedData.field_name) {
throw new ForbiddenError('relation field is empty)
}
}