Asked by: Nathan Siafa
I'm working on a laravel application. In this application I have three tables:
subjects
id | name
-- | ----
01 | maths
02 | english
divisions
id | name
-- | ----
01 | Senior High
02 | Junior High
division_subject
pivot table
division_id | subject_id
--- | ---
01 | maths
02 | english
A subject can have many divisions, so, in my form I have a list of all divisions as checkboxes. I the subject is taught in a single division a single division will be checked. If the subject is taught is many divisons all the divisions the subject is taught in will be checked also. Now this is working fine when inserting with no problems. This is how the form looks:
Problem
Now, I want to be able to edit a subject and when I click on a edit button I want all divisions that are checked to a subject checked or all divisions that are assigned to a subject in the pivot table checked. This is what I haven't been able to get my head around in laravel. so far this is how my code looks:
Division controller that returns all the divisions to be assigned to a subject:
public function index(Request $request)
{
//
if ($request->ajax()) {
$divisions = Division::all();
return $divisions->pluck('name', 'id')->toArray();
}
//return view('division.show', compact('divisions'));
}
This is how I'm rendering it in the table.
<td>
<!-- If a subject belongs to a division or divisions list all the divisions
that belongs to the subject -->
@if(count($subject->divisions))
@foreach($subject->divisions as $division)
<a href="#" data-type="checklist" data-value="{{$division->id}}" data-title="Select divisions" data-name="division" class="division" data-pk="{{$division->id}}" role="button">
<span class="badge label-primary">{{$division->name}}</span>
</a>
@endforeach
@endif
</td>
This i how I'm rendering it in a model that has a form.
<div class="form-group">
<label for="division">Level</label>
<p class="text-muted">Please select the division(s) the subject is taught within.</p>
@foreach($divisions as $division)
<label class="checkbox-inline">
<input type="checkbox" id="division_id" name="division_id[]" value="{{$division->id}}"> {{$division->name}}
</label>
@endforeach
</div>
The thing is I'm doing the same in the edit form but don't know how to checked up that values that have been assigned to a subject.
Is there a way that when the user click the edit button than all the divisions assigned to the subject be checked up.
anchor element that shows edit modal.
<td>
<a class="edit-modal" data-id="{{$subject->id}}" data-name="{{$subject->name}}" data-toggle="tooltip" title="Edit" href="#" role="button">
<i class="glyphicon glyphicon-edit text-info"></i>
</a>
</td>
This is my script for now:
$(document).on('click', '.edit-modal', function(event) {
event.preventDefault();
/* Act on the event */
$('#edit-name').val($(this).data('name'));
$('#edit-modal').modal({
show: true,
backdrop:'static',
keyboard:false
});
});
No comments:
Post a Comment