2017-05-12 3 views
0

CRUD 할 일 목록을 만들고 있습니다. 편집을 클릭하면 모달이 시작됩니다. 모달 내에서 수정하여 제출하면 모든 항목이 올바르게 업데이트됩니다. 즉 update() 메소드가 정상적으로 작동합니다. 그러나 $task은 배열의 마지막 항목 값을 저장하므로 클릭 한 행의 편집 단추에 상관없이 항상 해당 항목의 값을 표시합니다.Laravel 5 - 모달이 데이터 테이블 행의 값을 검색 할 수 없습니다.

할 일 테이블 :

<div id="tasks-chart"> 
      <table id="datatable-table" class="table table-striped table-hover"> 
       <thead> 
       <tr> 
        <th>Task</th> 
        <th style="width: 40%">Description</th> 
        <th>Status</th> 
        <th>Actions</th> 
       </tr> 
       </thead> 
       <tbody> 
       @foreach($tasks as $task) 
        <tr id="task{{$task->id}}"> 
         <td>{{$task->task}}</td> 
         <td style="width: 40%">{{$task->description}}</td> 
         <td>@if($task->done) Completed @else Incomplete @endif</td> 
         <td> 
          <button class="btn btn-warning btn-sm btn-detail open-modal" value="{{$task->id}}" 
            data-toggle="modal" 
            data-target="#myModal2" 
            data-backdrop="static" 
            data-task ="{{$task->task}}" 
            data-description ="{{$task->description}}" 
            data-done ="{{ $task->iscomplete }}">Edit</button> 
          <button class="btn btn-danger btn-sm btn-delete delete-task" value="{{$task->id}}">Delete</button> 
         </td> 
        </tr> 
       @endforeach 
       </tbody> 
      </table> 
     </div> 

모달 편집 버튼을 클릭하면 시작됩니다 또한 매우 간단하다 :

<div id="myModal2" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;"> 
      <div class="modal-dialog"> 
       <div class="modal-content"> 
        <div class="modal-header"> 
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true" aria-label="Close">×</button> 
         <h4 class="modal-title" id="myModalLabel2">Edit Task</h4> 
        </div> 
        <div class="modal-body"> 
         {{ Form::model($task, ['method' => 'PATCH', 'route' => ['tasks.update', $task->id], 'role' => 'form']) }} 
         <fieldset> 
          <label for="edit-name" class="control-label col-sm-4">Task</label> 
          <div class="col-md-8"> 
           {{Form::text('task',null,['id'=>'edit-name','class'=>'form-control col-sm-8','required'=>'required'])}} 
           <p class="error text-center alert alert-danger hidden"></p> 
          </div> 
         <br><br> 
          <label for="edit-description" class="control-label col-sm-4">Description</label> 
          <div class="col-sm-8"> 
           {{Form::textarea('description',null,['id'=>'edit-description','class'=>'form-control','rows'=>'5','cols'=>'45'])}} 
          </div> 
         <br><br> 
          <label for="edit-status" class="control-label col-sm-4">Status</label> 
          <div id="edit-status" class="col-sm-8"> 
           {{Form::select('done', ['0'=>'Incomplete','1'=>'Completed'],null, 
           ['id'=>'edit-status','class'=>'selectpicker', 'data-style'=>'btn-success', 'data-width'=>'auto'])}} 
          </div> 
         </fieldset> 
        </div> 
        <div class="modal-footer"> 
         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
         {{ Form::submit('Submit', ['class' => 'btn btn-success']) }} 
        </div> 
        {{ Form::close() }} 
       </div><!-- /.modal-content --> 
      </div><!-- /.modal-dialog --> 
     </div> 

routes.php :

Route::resource('tasks','TaskController'); 

컨트롤러에는 하나의 메소드 만 구현되었습니다.

public function update(Request $request, $id) 
{ 
    $user = Auth::user(); 


    // validation of the request 
    $rules = array(

     'task' => 'required|string', 
     'description'=>'string' 

    ); 
    $validator = Validator::make(Input::all(), $rules); 

    // return to the creation page if the request is invalid 
    if ($validator->fails()) { 
     return Redirect::to('/') 
      ->withErrors($validator) 
      ->withInput(); 
    } 
    else{ 
     $task    = Task::findOrFail($id); 

     $task->task   = Input::get('task'); 
     if(Input::get('description')) 
     { 
      $task->description = Input::get('description'); 
     } 
     $task->done   = Input::get('done'); 
     $task->save(); 

     \Session::flash('flash_message','Task succesfully updated!'); 
     // redirect 
     return redirect('/'); 
    } 
} 

JQuery와 나는 나의 버튼에 data- 속성을 사용 모달의 필드

$('button.open-modal').on('click', function (e) { 
// Make sure the click of the button doesn't perform any action 
e.preventDefault(); 

// Get the modal by ID 
var modal = $('#myModal2'); 

// Set the value of the input fields 
modal.find('#edit-name').val($(this).data('task')); 
modal.find('#edit-description').val($(this).data('description')); 
modal.find('#edit-status').val($(this).data('done')); 

// Update the action of the form 
modal.find('form').attr('action', 'tasks/update/' + $(this).val()); 

입니다 채우는 데 사용});

하지만 내가 만든 행의 버튼에 관계없이 마지막으로 생성 된 작업에 대한 작업 ID, 작업 설명 등이 표시됩니다. 이 문제를 어떻게 해결할 수 있습니까?

답변

1

를 기준으로 값을 얻을! 단추를 DOM에 추가하기 전에 대상 단추에 jquery 이벤트를 추가하려고 할 수 있습니다. 따라서 코드를 $(document).ready(function(){}); 블록 안에 작성해야합니다. 이 같은

시도 :

$(document).ready(function() { 
    $('button.open-modal').on('click', function (e) { 
     // Make sure the click of the button doesn't perform any action 
     e.preventDefault(); 

     // Get the modal by ID 
     var modal = $('#myModal2'); 

     // Set the value of the input fields 
     modal.find('#edit-name').val($(this).data('task')); 
     modal.find('#edit-description').val($(this).data('description')); 
     modal.find('#edit-status').val($(this).data('done')); 

     // Update the action of the form 
     modal.find('form').attr('action', 'tasks/update/' + $(this).val()); 

    }); 
}); 
1

모달가 표시 될 때, 값을 추가 귀하의 코드가 잘 보이는 클릭 된 버튼

$('#myModal2').on('show.bs.modal', function (e) { 
//get the button 
var el = $(e.relatedTarget); 
var modal = $(this); 

// Set the value of the input fields 
modal.find('#edit-name').val(el.data('task')); 
modal.find('#edit-description').val(el.data('description')); 
modal.find('#edit-status').val(el.data('done')); 

// Update the action of the form 
modal.find('form').attr('action', 'tasks/update/' + el.val()); 
관련 문제