Select2 init data
i have select 2 in create page
how i can load with option user selected from db (save from create page) to edit/show page
i'm using laravel
thanks
Replies (3)
Hi,
Sorry for the delay. Select2 with multiple select, you can add multiple="multiple" attribute to the select input. And the name
<select name="selectedOptions[]" multiple="multiple"> For more information, please check the select2 docs.
Thanks
Hi,
Assuming you have stored the selected options in your database during the creation process, retrieve these options for the specific record you are editing. You might have a model representing the data, and you can use that model to retrieve the data from the database.
In your controller, retrieve the data and pass it to the view where you want to show the edit form.
// In your controller method
public function edit($id)
{
// Replace "YourModel" with your actual model name
$record = YourModel::find($id);
return view("your.edit.view", compact("record"));
} In your view file (blade file), use the passed data to initialize Select2 with the selected options.
<!-- Your form code -->
<form action="{{ route("your.update.route", $record->id) }}" method="POST">
@csrf
@method("PUT")
<!-- Other form fields -->
<select name="your_select_field" class="form-control">
<!-- Populate options from database -->
@foreach ($optionsFromDatabase as $option)
<option value="{{ $option->id }}" {{ $record->selectedOption == $option->id ? "selected" : "" }}>
{{ $option->name }}
</option>
@endforeach
</select>
<!-- Other form fields -->
<button type="submit">Update</button>
</form> In this example, optionsFromDatabase represents the options you have in your database, and selectedOption is the property from your model that holds the selected option for the record being edited.
Make sure to replace YourModel with the actual name of your model, and adjust the field names accordingly based on your database schema.