2017-02-20 237 views
0

我已經花了幾天研究datatables和yajra包,這表示我沒有接近獲得我需要的結果,並將非常感激這一個幫助,如果任何人比我的新手方法更多的知識!Laravel Yajra datatables呈現自定義html /列樣式

爲了更好地解釋我附加了兩張圖片,第一張圖片是一個已經實現了這個功能的應用程序,第二張圖片是我展示的一個快速模擬圖。


期望得到的結果,我希望能實現...... enter image description here


本視圖我有... enter image description here


我基本上試圖添加自定義的HTML到每個需要功能的列..我已經設法通過返回一個自定義的數組像這樣取得一些輕微的成功:

foreach ($tasks as $task) { 
    $checkBox = '<div class="checkbox"><input type="checkbox" value="63"><label></label></div>'; 
    $taskPriority = '<span class="text-info inline-block">Medium</span>'; 
      ... so on ... 
    $row = array(
     $checkBox, 
     $taskPriority, 
     ... so on ... 
    ); 
    $rows[] = $row; 
} 
$list['data'] = $rows; 
return $list; 

雖然這工作我不會說的最好的方法和人們想象的有一些什麼這樣做的更好,更優雅的方式?

我知道yajra有addColumn和editColumn方法,我用這些來添加一個動作列,因爲這是唯一一個似乎呈現任何html,除了addColumn('行動','等等等')似乎不想呈現html,而是將其顯示爲行中的原始文本。

以防萬一這是爲了幫助任何人,這裏是獲取表數據的Ajax調用。

$('#taskstable').DataTable({ 
    "processing": true, 
    "retrieve": true, 
    "serverSide": true, 
    'paginate': true, 
    'searchDelay': 700, 
    "bDeferRender": true, 
    "responsive": true, 
    "autoWidth": false, 
    "pageLength": 5, 
    "lengthMenu": [[5, 10, 25, 50, 100], [5, 10, 25, 50, 100]], 
    ajax: '/tasks/get-tasks' 
}); 

希望有人能幫助緩解作爲新手的壓力!謝謝。

回答

1

兄弟我可以你一些想法這可能會幫助你得到你想要的結果。 控制器:

public function index(Request $request) 
    { 
     $data = []; 
     $data['page_title'] = trans($this->trans_path . 'general.page.index.page-title'); 
     $data['show_modal'] = false; 
     $data['trans_path'] = $this->trans_path; 
     if ($request->get('add') && $request->get('add') == "true") { 
      $data['show_modal'] = true; 
     } 

     // TODO: Confirm this logic 
     //count no. of promoter admin 
     $data['promoter'] = User::where('user_type', AclHelper::getUsersTypeKey('promoter-admin'))->count(); 

     // for mapping policy 
     $data['admin_user_model'] = new AdminUser(); 

     //generate add Button 
     $data['add_btn_html'] = view($this->loadDefaultVars($this->view_path . '.partials._promoter_add_button'))->render(); 
     $data['assignable_user_roles'] = $this->getAssignableRolesByAuthUser(); 

     return view($this->loadDefaultVars($this->view_path . '.index'), compact('data')); 
    } 

    public function search(Request $request) 
    { 

     $data = []; 
     $columns = ['rud.*', 'us.first_name as promoter_first_name', 'us.last_name as promoter_last_name', 'users.email', 'users.username', 
      'r.name', 'r.display_name', 'rud.created_by', 'rud.promoter_id', 'users.enabled']; 
     $users = $this->getUserListJoinQuery($columns) 
      ->leftJoin('role_users_details as us', 'rud.promoter_id', '=', 'us.id') 
      ->groupBy('users.id'); 

     if (in_array(AclHelper::getUsersTypeKey('super-admin'), AclHelper::getUserRoles(), 1) || 
      in_array(AclHelper::getUsersTypeKey('support-admin'), AclHelper::getUserRoles(), 1) 
     ) { 
      $users->where('users.id', '!=', auth()->user()->id); 
      $data['users'] = $users->get(); 
     } else { 

      if (in_array(AclHelper::getUsersTypeKey('promoter-admin'), AclHelper::getUserRoles(), 1)) 
       $data['users'] = $users->where('rud.promoter_id', Auth::user()->id)->get(); 
      elseif (in_array(AclHelper::getUsersTypeKey('promoter-editor'), AclHelper::getUserRoles(), 1)) { 
       $promoter_id = Auth::user()->userDetail->promoter_id; 
       $users->where('r.name', '!=', AclHelper::getUsersTypeKey('promoter-editor')); 
       $data['users'] = $users->where('rud.promoter_id', $promoter_id)->get(); 
      } else { 
       return response('Unauthorized request made.', 401); 
      } 
     } 

     return Datatables::of($data['users']) 
      ->editColumn('user_id', function ($users) { 
       $data = view($this->loadDefaultVars($this->view_path . '.partials._action_fields'), compact('users'))->render(); 
       return $data; 
      }) 
      ->editColumn('profile_image', function ($users) { 
       if (!isset($users->profile_image)) { 
        return ""; 
       } 
       return '<img src="' . asset(config('neptrox.admin_user_path.thumbnail') . $users->profile_image) . 
       '" alt="' . $users->first_name . '" style="height: 40px;" >'; 
      }) 
      ->editColumn('name', function ($users) { 
       return $users->first_name . ' ' . $users->middle_name . ' ' . $users->last_name; 
      }) 
      ->editColumn('gender', function ($users) { 
       if ($users->gender === 'male') 
        return 'Male'; 
       elseif ($users->gender === 'female') 
        return 'Female'; 
       else 
        return 'Other'; 
      }) 
      ->editColumn('user_type', function ($users) { 
//    return $users->pivot->display_name; 
       return config('neptrox.admin-users-roles.' . $users->name . '.title'); 
      }) 
      ->editColumn('promoter', function ($users) { 
       return $users->promoter_first_name . ' ' . $users->promoter_last_name; 
      }) 
      ->editColumn('status', function ($users) { 
       if ($users->enabled === 1) { 
        return "<span class='text-success'> " . 
        '<i class="fa fa-check-circle-o text-info"></i>' . 
        "</span>"; 
       } 
       return "<span class='text-danger'>" . 
       '<i class="fa fa-ban text-danger"></i>' . 
       "</span>"; 
      }) 
      ->make(true); 

    } 

jQuery的腳本

<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js" type="text/javascript"></script> 
<script> 

    (function (options) { 

     var route_url = options.dataTableConfigVariable.route_url; 
     var columns = options.dataTableConfigVariable.columns; 
     var order = options.dataTableConfigVariable.orderColumn; 
     if (order == 'undefined' || order == null || order == "") { 
      order = 1; 
     } 
     var config = { 
      "dom": '<t>' + 
      '<"card-footer card-pagination"<"row"<"col-md-8"p><"col-md-4 form-design1 right"l>>>', 
      "oLanguage": { 
       "sLengthMenu": " _MENU_ ", 
       "sSearchPlaceholder": "Search", 
       "oPaginate": { 
        "sNext": "<span aria-hidden='true'>»</span><span class='sr-only'>Next</span>", 
        "sPrevious": "<span aria-hidden='true'>«</span><span class='sr-only'>Previous</span>" 
       }, 
      }, 
      processing: true, 
      serverSide: true, 
      ajax: { 
       type: 'POST', 
       url: route_url.dataTable_url, 
       data: { 
        _token: $('meta[name=csrf-token]').attr("content") 
       } 
      }, 
      columns: columns, 
      'order': [[order, 'asc']] 
     }; 

     //initialize dataTables 
     var table = $('table.table').DataTable(config); 

     $('#searchField').keyup(function(){ 
      table.search($(this).val()).draw() ; 
     }); 


     //Enables or disables the performer and reload the ajax after success 
     $('body').on('click', '.enableDisable', function (e) { 
      e.preventDefault(); 
      var url = $(this).attr('href'); 
      $.ajax({ 
       type: 'GET', 
       url: url, 
       success: function (response) { 
        table.ajax.reload(null, false); 
       } 
      }); 
     }); 

     //toggle all checkbox checked or unchecked 
     $('body').on('click', 'input[name="checkAll"]', function() { 
      var checkBoxes = $("input[name=checkbox\\[\\]]"); 
      checkBoxes.prop("checked", $(this).prop("checked")); 
     }); 

     //enable selected performers 
     $('body').on('click', '#enable', function (e) { 
      var url = route_url.enableAll; 
      enableDisablePerformer(e, url); 
     }); 

     //disable selected performers 
     $('body').on('click', '#disable', function (e) { 
      var url = route_url.disableAll; 
      enableDisablePerformer(e, url); 
     }); 

     function enableDisablePerformer(e, url) { 
      e.preventDefault(); 
      var formData = $('input[name^=checkbox]'); 
      var data = {}; 
      formData.each(function (index) { 
       if ($(this).is(':checked')) { 
        data[index] = $(this).val(); 
       } 
      }); 
      $.ajax({ 
       type: 'POST', 
       url: url, 
       data: { 
        _token: $('meta[name=csrf-token]').attr("content"), 
        id: data 
       }, 
       success: function (response) { 
        if (response == 'ok') { 
         table.ajax.reload(null, false); 
         $('body').find('input[name="checkAll"]').prop('checked', false); 
        } 
       } 
      }); 
     } 


     //Delete confirmation popup 
     $('body').on('click', '.try-sweet-warningConfirm', function() { 
      var id = $(this).attr('id'); 
      swal({ 
       title: "{{ trans($trans_path.'general.delete.sure') }}", 
       text: "{{ trans($trans_path.'general.delete.message') }}", 
       type: "warning", 
       showCancelButton: true, 
       confirmButtonColor: "{{ trans($trans_path.'general.delete.confirmButtonColor') }}", 
       confirmButtonText: "{{ trans('general.button.delete') }}", 
       cancelButtonText: "{{ trans('general.button.cancel') }}", 
       closeOnConfirm: true 
      }, function (isConfirm) { 
       if (isConfirm) { 
        $.ajax({ 
         type: 'POST', 
         url: route_url.delete, 
         data: { 
          _token: $('meta[name=csrf-token]').attr("content"), 
          id: id 
         }, 
         success: function (response) { 
          table.row($(this).closest('tr')).remove().draw(); 
          if (response == 'ok') { 
           swal({ 
            title: "{{ trans($trans_path.'general.status.delete') }}", 
            text: "{{ trans($trans_path.'general.status.deleted') }}", 
            type: "success", 
            timer: 2000, 
            confirmButtonColor: "{{ trans($trans_path.'general.delete.confirmButtonColor') }}" 
           }); 
          } 
         } 
        }); 

       } 
      }); 
     }); 

     //Delete bulk confirmation popup 
     $('body').on('click', '#delete', function() { 
      swal({ 
       title: "{{ trans($trans_path.'general.delete.sure') }}", 
       text: "{{ trans($trans_path.'general.delete.message') }}", 
       type: "warning", 
       showCancelButton: true, 
       confirmButtonColor: "{{ trans($trans_path.'general.delete.confirmButtonColor') }}", 
       confirmButtonText: "{{ trans('general.button.delete') }}", 
       cancelButtonText: "{{ trans('general.button.cancel') }}", 
       closeOnConfirm: true 
      }, function (isConfirm) { 
       if (isConfirm) { 
        var url =route_url.delete; 
        deleteBulkPerformer(url); 
        $('body').find('input[name="checkAll"]').prop('checked', false); 
        swal({ 
         title: "{{ trans($trans_path.'general.status.delete') }}", 
         text: "{{ trans($trans_path.'general.status.deleted') }}", 
         type: "success", 
         timer: 2000, 
         confirmButtonColor: "{{ trans($trans_path.'general.delete.confirmButtonColor') }}" 
        }); 
       } 
      }); 
     }); 

     function deleteBulkPerformer(url){ 
      var formData = $('input[name^=checkbox]'); 

      var data = {}; 
      formData.each(function (index) { 
       if ($(this).is(':checked')) { 
        data[index] = $(this).val(); 
       } 
      }); 
      $.ajax({ 
       type: 'POST', 
       url: url, 
       data: { 
        _token: $('meta[name=csrf-token]').attr("content"), 
        id: data, 
        bulk: 'bulk' 
       }, 
       success: function (response) { 
        if (response == 'ok') { 
         table.row($(this).closest('tr')).remove().draw(); 
        } 
       } 
      }); 
     } 

    })({dataTableConfigVariable:dataTableConfigVariable}); 

</script> 

查看頁面

<script> 
     var dataTableConfigVariable = { 
      route_url: { 
       dataTable_url: '{{route("admin.admin_users.search")}}', 
       enableAll: '{{route("admin.admin_users.enableAll")}}', 
       disableAll: '{{route("admin.admin_users.disableAll")}}', 
       delete: '{{route("admin.admin_users.delete")}}' 
      }, 
      columns: [ 
       {data: 'user_id', name: 'user_id', orderable: false, searchable: false}, 
       {data: 'profile_image', name: 'profile_image', orderable: false, searchable: false}, 
       {data: 'name', name: 'name'}, 
       {data: 'user_code', name: 'user_code', orderable: false}, 
       {data: 'email', name: 'email'}, 
       {data: 'username', name: 'username'}, 
       {data: 'gender', name: 'gender'}, 
       {data: 'user_type', name: 'user_type'}, 
       {data: 'promoter', name: 'promoter', orderable: false, searchable: false}, 
       {data: 'status', name: 'status', orderable: false, searchable: false}, 
      ], 
      orderColumn: 2 
     }; 
    </script> 
+0

感謝您抽出時間發佈您的代碼,我很快就會在手機上看到它,因此我無法看到整篇文章,但期待着閱讀您的解決方案:)謝謝 – Birdy

0

我發現因爲我張貼此答案如下的時間,最簡單的方法,這是說,我相信這不是最好的辦法,也許及時來我擁有比我更多的經驗將能夠發佈更好的解決方案。


在我的項目,我使用所謂的Laravel集體特定的軟件包,可以發現:...here..

使用此數據包,您可以訪問一個輔助類和門面。隨着我的應用程序特定的一些細微修改,我已經能夠很好地使用這個軟件包。

一個類似的方法是這樣:

public function getTasks() 
{ 
    $tasks = $this->taskInterface->model()->all(); 
    return $this->datatables->collection($tasks) 
     ->editColumn('name', function ($model) { 
      return HtmlFacade::link("admin/tasks/{$model->id}", $model->name); 
     }) 
     ->addColumn('action', function($query) { 
      return view('backend.global.tables.actions.all-tasks-actions', compact('query')); 
     }) 
     ->make(true); 
} 

注意

使用回收HtmlFacade ::鏈接()的時候;方法,這將返回在數據表上呈現的html。可以通過查看文檔或在我的案例中查看其自身的類並查看源代碼讓我更好地瞭解它們的包工作,不僅如此,它還能夠爲班級添加更多的方法,這就是我得到我需要的結果的方式。

我不打算髮布所有的自定義類,因爲我認爲這對於未來幫助任何人來說太不相關,因爲我已經添加了這些方法,或者與開箱即用的方法非常類似,唯一的區別是允許onclick JavaScript事件和傾斜CSS。

這個答案的寓意是讓任何處於類似位置的人知道,如果您已經使用此包,那麼您可能不需要手動將所有行轉換爲數組,只是將自定義html傳遞給鑑於我不再需要這樣做:

$rows = []; 
$checkBox = '<div class="checkbox"><input type="checkbox" value="63"><label></label></div>'; 
$taskPriority = '<span class="text-info inline-block">Medium</span>'; 
ect... As seen in original post.. 

,而不是你可以通過自定義屬性,類和從laravel集體包建起來,這裏是鏈接方法laravel集體自帶的,可以是一個構建塊,以將自定義方法添加到其包中。

public function link($url, $title = null, $attributes = [], $secure = null, $escape = true) 
{ 
    $url = $this->url->to($url, [], $secure); 

    if (is_null($title) || $title === false) { 
     $title = $url; 
    } 

    if ($escape) { 
     $title = $this->entities($title); 
    } 

    return $this->toHtmlString('<a href="' . $url . '"' . $this->attributes($attributes) . '>' . $title . '</a>'); 
} 

這應該會給人怎樣可以輕鬆地修改此HTML生成器到你的需求的概念,正如我說我敢肯定這是不是如果沒有更好的結果,從而達到相同的最好的和最優雅的想我將把問題留給未來解決方案,我只是想分享我的解決方案。