F
Filamentβ€’16mo ago
Shavik

Unexpected Behavior from mutateFormDataBeforeCreate

Working on a little test learning Filament project. It is an issue tracker. I have made an Issue model/resource, etc. The issue has a user_id that is the user that created the issue. I have the select box working on the resource that shows the users in the dropdown, etc. That works great. I was trying to implement it so that if a user isn't selected, it will just pick the currently logged in user when saving. I searched discord here and found an old post where they linked to the website and it mentioned adding
protected function mutateFormDataBeforeCreate(array $data): array
{
if (empty($data['user_id'])) {
$data['user_id'] = auth()->id();
}

return $data;
}
protected function mutateFormDataBeforeCreate(array $data): array
{
if (empty($data['user_id'])) {
$data['user_id'] = auth()->id();
}

return $data;
}
to the CreateIssue.php I added the if empty in hopes that it would only set the user if not given from the form. It appears that it does create the issue without problem AND that it sets the user_id so that part looks good. The issue is that sometime after the model actually saves and the 'save' succeeding from the perspective of the frontend, I get this:
Not null violation: 7 ERROR: null value in column "user_id" of relation "issues" violates not-null constraint DETAIL: Failing row contains (8, 2186f6af-4a49-48b3-b2fd-6a8b5e8ed730, null, First Issue, <p>Test3</p>, medium, null, 2023-08-02 10:09:38, 2023-08-02 10:09:38).
update "issues" SET "user_id" = ?, "updated_at" = 2023-08-02 10:09:38 WHERE "id" = 8
Not null violation: 7 ERROR: null value in column "user_id" of relation "issues" violates not-null constraint DETAIL: Failing row contains (8, 2186f6af-4a49-48b3-b2fd-6a8b5e8ed730, null, First Issue, <p>Test3</p>, medium, null, 2023-08-02 10:09:38, 2023-08-02 10:09:38).
update "issues" SET "user_id" = ?, "updated_at" = 2023-08-02 10:09:38 WHERE "id" = 8
I'm not sure why it would be trying to update the record that it just saved other than perhaps trying to set the updated_at time? But in that case, why is the user_id null? Perhaps it has old (submitted) data for the issue (before the mutate call)?
2 Replies
Shavik
ShavikOPβ€’16mo ago
Noticed this buried in the stack trace. Not sure if it helps or is related.
Shavik
ShavikOPβ€’16mo ago
Looks like the issue is more related to this line:
$this->form->model($this->getRecord())->saveRelationships();
$this->form->model($this->getRecord())->saveRelationships();
wow, this works to poplate the select box.. πŸ™‚
->default(fn() => auth()->id()),
->default(fn() => auth()->id()),
on the form component.
Want results from more Discord servers?
Add your server