0

I am using Laravel5.8for a web application project. I have successfully saved data into the database, but I have problem retrieving it on modal form.

Model

class AppraisalGoalType extends Model
{
  protected $table = 'appraisal_goal_types';
  protected $fillable = [
   'name',
   'parent_id',
   'max_score'
 ];

 public function children()
 {
   return $this->hasMany('App\AppraisalGoalType', 'parent_id');
 }
}

Controller

public function edit($id)
{
  $category = AppraisalGoalType::where('id', $id)->first();       
  return view('goal_types.edit')->with('category', $category);
}

public function update(UpdateGoalTypeRequest $request, $id)
{   
  $category = AppraisalGoalType::find($id);                            
  $category->name           = $request->name;
  $category->parent_id      = $request->parent_id;
  $category->max_score      = $request->max_score;

  $category->save();
  Session::flash('success', 'Updated successfully');
  return redirect()->route('goal_types.index');
}

index view

<div class="col-md-8">
 <div class="card card-secondary">
   <div class="card-header">
    <h3 class="card-title">Goal Type(s)</h3>
   </div>
   <div class="card-body">
    <ul class="list-group">
     @foreach ($categories as $category)
     <li class="list-group-item">
     <div class="d-flex justify-content-between">
       {{ $category->name }} 
       <strong>{{ $category->max_score }}</strong>
       <div class="button-group d-flex">
         <button type="button" class="btn btn-sm btn-primary mr-1 edit-category" data-toggle="modal" data-target="#editCategoryModal" data-id="{{ $category->id }}" data-name="{{ $category->name }}" data-max-score="{{ $category->max_score }}" data-parent-id="{{ $category->parent_id }}">Edit</button>

         <form action="{{ route('appraisal.goal_types.destroy', $category->id) }}" method="POST">
           @csrf
           @method('DELETE')

           <button type="submit" class="btn btn-sm btn-danger">Delete</button>
         </form>
       </div>
      </div>

      @if ($category->children)
      <ul class="list-group mt-2">
       @foreach ($category->children as $child)
       <li class="list-group-item">
       <div class="d-flex justify-content-between">
        {{ $child->name }} 
        <div class="button-group d-flex">
          <button type="button" class="btn btn-sm btn-primary mr-1 edit-category" data-toggle="modal" data-target="#editCategoryModal" data-id="{{ $child->id }}" data-name="{{ $child->name }}">Edit</button>
          <form action="{{ route('appraisal.goal_types.destroy', $child->id) }}" method="POST">
            @csrf
            @method('DELETE')
            <button type="submit" class="btn btn-sm btn-danger">Delete</button>
          </form>
         </div>
        </div>
        </li>
        @endforeach
       </ul>
       @endif
     </li>
     @endforeach
     </ul>
   </div>
  </div>
</div>

edit modal view

<div class="modal fade" id="editCategoryModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Edit Goal Type</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>                    
      <form action="" method="POST">
        @csrf
        @method('PUT')

        <div class="modal-body">
          <div class="form-group">
           <label class="control-label"> Parent Goal Type:</label>
           <select class="form-control select2bs4" data-placeholder="Choose Parent Goal Type" tabindex="1" name="parent_id" style="width: 100%;">
           <option value="">Select Parent Goal Type</option>
             @foreach ($categories as $category)
             <option value="{{ $category->id }}">{{ $category->name }}</option>
             @endforeach
            </select>
           </div>
           <div class="form-group">
             <label class="control-label"> Name:<span style="color:red;">*</span></label>
             <input type="text" name="name" class="form-control" value="" placeholder="Category Name" required>
            </div>
            <div class="form-group">
             <label class="control-label"> Max. Score:</label>
             <input type="number" name="max_score" class="form-control" value="" step="0.01" placeholder="Enter maximum score here: 15, 50, 75 etc" style="width: 100%;">
            </div>                       
           </div>

           <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Update</button>
           </div>
        </div>
    </form>
  </div>
</div>
            
<script type="text/javascript">
 $('.edit-category').on('click', function() {
 var id = $(this).data('id');
 var name = $(this).data('name');
 var parentId = $(this).data('parent-id');
 var maxScore = $(this).data('max-score');
 var url = "{{ url('category') }}/" + id;

 $('#editCategoryModal form').attr('action', url);
 $('#editCategoryModal form input[name="name"]').val(name);
 $('#editCategoryModal form select[name="parent_id"]').val(parentId);
 $('#editCategoryModal form input[name="max_score"]').val(maxScore);
 });
</script>            

The index view blade and the create are working perfectly

I have three fields

name, parent_id, max_score

When I clicked on the edit button on index view blade to display edit modal form fields with the data, name field and max_score field displayed loaded data. However, parent_id (dropdownlist) did not display any data. See the diagram below. When I clicked on it, I saw the data.

edit modal form

expected result:

expected edit modal form

How do I resolve this?

Thank you.

mikefolu
  • 1,203
  • 6
  • 24
  • 57
  • where is $categories array? – PHP Geek Jan 22 '20 at 04:53
  • Have you checked the rendered HTML of your index, are all values like `data-parent-id` correct? How about `$('#editCategoryModal form select[name="parent_id"][value="' + parentId + '"]').prop('selected', true);` ? – Don't Panic Jan 22 '20 at 10:05
  • Also see https://stackoverflow.com/questions/4680075/set-selected-option-of-select-box – Don't Panic Jan 22 '20 at 10:05

2 Answers2

0

Use the change() event after selecting the value. If the field loses focus without the contents having changed, the event is not triggered. To trigger the event manually, apply .change() without arguments. In your case it should be.

$('#editCategoryModal form select[name="parent_id"]').val(parentId).change();
Qonvex620
  • 3,819
  • 1
  • 8
  • 15
  • Still the same thing. I don't need to click the dropdown before I see the saved data from the database on edit modal. But its still behaving like that. As it is on the two textboxs (name and max_score) the saved data on the dropdown (parent_id->name) needs to also be displayed as the form loads. See the edit post where I added the expected result (image). Thanks – mikefolu Jan 22 '20 at 07:05
0

My solution would be to get the name in the select database query in controller instead of getting all the data

public function index()
{
     // $incomes = Income::all();

     $banks = Bank::all();

     $incomes = DB::table('table_income')
         ->select('table_income.id', 'table_income.amount', 'table_income.bank', 'table_income.desc', 'table_bank.account_name as bank_account', 'table_bank.id', 'table_income.created_at as date')
         ->join('table_bank', 'table_income.id', '=', 'table_bank.id')
         ->get();

     return view('income', compact('incomes', 'banks'));
}
bounav
  • 4,886
  • 4
  • 28
  • 33