Waiting for someone to rescue me :(
Dynamic route path in form action based on the selected option
I have a form like this in laravel 5.4 view:
<form action="#" method="POST" class="form-inline" role="form">
{{ csrf_field() }}
<div class="form-group">
<select id="tdcategory" class="selectpicker show-tick show-menu-arrow" onchange="this.form.submit()">
@foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach
</select>
</div>
<div class="form-group">
<select id="tdlocation" class="selectpicker show-tick show-menu-arrow" onchange="this.form.submit()">
@foreach($locations as $location)
<option value="{{ $location->id }}">{{ $location->name }}</option>
@endforeach
</select>
</div>
</form>
I have two questions:
#1 How can I dynamically set the form action to something like
`categories/{category->id}/locations/{location->id}`
Where, both category id and location id will be based on the value of the option the user has currently selected
#2 Since the form gets submitted as the user changes the option, the page is then reloaded and resets both of the <select> tag. How do I keep track of previously selected option and as the page loads, I can show the user which one did he/she select before the form was submitted?
well you could do it dynamically with any front end library/framework/language but if you want to stick with php (Laravel)
1.Add the select box name attributes like name="category_id" so that they can be available in the request object
2.Have a general end point that does the redirection
Route::get("categories",function(\Illuminate\Http\Request $request){
$url="categories/{$request->category_id}/locations/{$request->location_id}";
return redirect($url);
});
2.For keeping track of the old records with in the select box, laravel has a helper function called old(), you could use in your blade views
just make sure you return back the user input when you are returning back
Something along the lines of this with in you route closure or controller method
return back()->withInput();
/** or something like this depending on what your are using*/
return redirect("/you-url")->withInput();
For the select boxes use javascript on any other front end tool of your choice to repopulate them with old data something like this
document.getElementById("category_id").value = "{{ old("category_id") }}";
Please or to participate in this conversation.