Multi-tenancy and createOptionForm on Select, Field 'company_id' doesn't have a default value
I have a resource that takes Contacts as a Select options. I want to add a Create form to the Select to create a new Contact but when saving get the following error:
SQLSTATE[HY000]: General error: 1364 Field 'company_id' doesn't have a default value
The ContactResource
form works when used standalone from the menu, but does not when used as the createOptionForm
Solution:Jump to solution
Here’s now to do it for anyone finding this:
createOptionAction()
is where you need to pass in your additional data
```php...11 Replies
You need to add company_id to the save method:
That would be great
I can add that to the Edit page for contacts as in the docs https://filamentphp.com/docs/3.x/panels/resources/editing-records#customizing-data-before-filling-the-form
but this isn’t run for the save operation:
->createOptionForm(fn(Form $form) => ContactResource::form($form)),
Do I need to put it somewhere else?And if I use
mutateFormDataBeforeCreate
in the CreateContact
this fires on the form’s own page, but not when used with createOptionForm
.Add it to the form there too? form($form)->mutateBeforeCreate
No good I’m afraid. I’ve done a composer update and tried
mutateFormDataBeforeCreate
Interesting, I would have assumed it would be supported. I am not that familiar with that function, so hopefully source code diving will show you how to handle it, orderwise maybe others can advise.
On the save function in the model, just set the default team_id
what about this?
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['company_id'] = auth()->user()->company_id;
return $data;
}
there’s nowhere that runs on the create option form, it’s only used when creating a standalone form as far as I can see. I shall need to try digging deeper
What about mutateRelationshipDataBeforeCreateUsing? as creationoptionform is for the relationship
Solution
Here’s now to do it for anyone finding this:
createOptionAction()
is where you need to pass in your additional data