Please share your store method.
Submit data to database using Inertia with React
I have a form that is supposed to submit order details to the orders table through a custom select element (headlessUI Combobox). The element works fine but I can't seem to pass the data selected to the database, in this case, customer_id.
Here's the form on the Create.js page:
export default function Create(props) {
const [selected, setSelected] = useState(""),
{customers} = usePage().props
const {post, processing, data, setData} = useForm({
customer_id: ""
})
const customerList = customers.map((customer, index) => (
{key: customer.id, name: customer.name}
))
const submit = (e) => {
e.preventDefault()
data.customer_id = selected.key
post(route('resources.orders.store'), data)
}
<Form submit={submit}>
<SelectSearch options={customerList} name={customer_id} value={selected}
onChange={setSelected} />
{/* other form elements in here */}
<Button processing={processing} />
</Form>
}
When I console.log(data) I get the selected value in the console: customer_id: 4. But I get the Error SQLSTATE[HY000]: General error: 1364 Field 'customer_id' doesn't have a default value when the data is posted. The customer_id is a foreignId() field. I can't seem to create the record.
I solved the issue. I had to pick the value of the custom input and append it to data.customer_id in the submit method:
const submit = (e) => {
data.customer_id = document.querySelector('[name="customer_id[id]"]').value
post(route("resources.orders.store"), data)
}
Headless UI Combobox component renders hidden input(s) that stores the values you select. So I had to just append the value of that hidden input to the data.customer_id. Then I had to change my store() method:
public function store(StoreOrderRequest $request) : RedirectResponse
{
Order::create([
$request->validated(),
'customer_id' => $request->customer_id,
'order_date' => $request->order_date,
'service_id' => $request->service_id,
'discount' => $request->discount,
'user_id' => auth()->user()->id,
'updated_by' => auth()->user()->id,
]);
}
Please or to participate in this conversation.