Aug 18, 2022
0
Level 1
How should I update subcategory dropdown
I’m editing product and it takes product id and return Product information including Category ID and Subcategory ID
- Frontend: VueJs (v3)
- Server Side Rendering: IneratiaJs
- Backend: Laravel (v9)
props:
I have declared 3 props categories, subcategories and product.
Design: Edit Product Page
category and subcategory have dropdown and all other fields have Textbox
I want to do two things (both using subcategories prop).
- Not Working: First thing is when user open product page I want to take subcategory from product array and show it in Subcategory Dropdown. I collect data from product prop and showed it in HTML Input Elements as per field except Subcategory because I'm stuck here??????
- Working: Secondly, on category change load it’s subcategories and it’s working fine.
- Loading it's subcategories using Inertia.Js (Partial Reload)
vue
<script setup>
const props = defineProps({
errors: Object,
categories: Object,
subcategories: Object,
product: Object,
})
const form = useForm({
category_id: props.product[0].category.id,
subcategory_id: props.subcategories, //Problem is here, 2 things on same props
product_id: props.product[0].id,
name: props.product[0].name,
price: props.product[0].price,
discount: props.product[0].discount,
});
let getSubcategory = (event) => {
if(event.target.value !== "") {
Inertia.visit(
route('edit.product', {
product_id: form.product_id,
category_id: event.target.value
}),{
only: ['subcategories'],
preserveState: true,
preserveScroll: true,
}
);
}
}
const submit = () => {
form.put(route('update.product'), {
onFinish: () => form.reset(),
});
};
</script>
Controller Method
public function edit(Product $product, $product_id, $category_id = null)
{
return Inertia::render('Product/Edit', [
'categories' => Category::has('subcategories')->get(['id', 'name']),
'product' => Product::with('category:id,name')
->with('subcategory:id,name')
->where('id', '=', $product_id)
->get()->toArray(),
'subcategories' => Inertia::lazy(fn () =>
Subcategory::with('category')
->where('category_id', '=', $category_id)
->get())
]);
}
Please or to participate in this conversation.