-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
rmcastro
committed
May 27, 2024
1 parent
feb4bd4
commit 3ec72b8
Showing
8 changed files
with
514 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
<?php | ||
|
||
use Rmunate\EasyDatatable\EasyDataTable; | ||
|
||
class NameController extends Controller | ||
{ | ||
/** | ||
* ES: Define un método que maneje la ruta tipo GET recibiendo una variable de tipo Request. | ||
* EN: Define a method that handles the GET type route receiving a Request type variable. | ||
*/ | ||
public function dataTable(Request $request) | ||
{ | ||
/** | ||
* ES: Crea una consulta con Query Builder, puedes aplicar todas las condiciones que requieras, solo NO apliques el método final get(). | ||
* EN Create a query using Query Builder, you can apply all the conditions you require, just DO NOT apply the final get() method. | ||
*/ | ||
$query = DB::table('novedades') | ||
->leftJoin('tipo_novedades', 'tipo_novedades.id', '=', 'novedades.tipo_novedad_id') | ||
->leftJoin('empleados', 'empleados.id', '=', 'novedades.empleado_id') | ||
->select( | ||
'empleados.cedula AS identification', | ||
'empleados.nombre AS employee', | ||
'tipo_novedades.nombre AS novelty_type', | ||
'novedades.descripcion AS description', | ||
'novedades.dias_calendario AS calendar_days', | ||
'novedades.dias_habiles AS business_days', | ||
'novedades.fecha_inicial AS initial_date', | ||
'novedades.fecha_final AS final_date' | ||
) | ||
->where('empleados.empresa', $request->company); | ||
|
||
/** | ||
* ES: (Opcional) A veces, para determinar si un usuario tiene permisos sobre alguna acción en las filas de la tabla, debes realizar consultas como estas. | ||
* EN: (Optional) Sometimes, to determine if a user has permissions for some action on the table rows, you need to make queries like these. | ||
*/ | ||
$permissionEdit = Auth::user()->can('novedades.editar'); | ||
|
||
/** | ||
* ES: El uso de la librería es tan simple como emplear el siguiente código. | ||
* EN: Using the library is as simple as using the following code. | ||
*/ | ||
$datatable = new EasyDataTable(); | ||
$datatable->clientSide(); /* Obligatorio / Requerid */ | ||
$datatable->query($query); | ||
$datatable->map(function ($row) use ($permissionEdit) { | ||
/** | ||
* ES: (Opcional) Si necesitas personalizar la forma en que se visualiza la información en la tabla, el método map() será de gran ayuda. | ||
* Además, si necesitas enviar datos adicionales o realizar validaciones, aquí puedes aplicar la lógica. | ||
* Es importante que el alias de cada valor en la consulta sea el mismo valor que se utiliza en el array, como se muestra a continuación. | ||
*/ | ||
|
||
/** | ||
* EN: (Optional) If you need to customize how the information is displayed in the table, the map() method will be very helpful. | ||
* Additionally, if you need to send additional data or perform validations, you can apply the logic here. | ||
* It's important that the alias of each value in the query is the same as the value used in the array, as shown below. | ||
*/ | ||
return [ | ||
'identification' => $row->identification, | ||
'employee' => strtolower($row->employee), | ||
'novelty_type' => strtolower($row->novelty_type), | ||
'description' => strtolower($row->description), | ||
'calendar_days' => $row->calendar_days, | ||
'business_days' => $row->business_days, | ||
'initial_date' => date('d/m/Y', strtotime($row->initial_date)), | ||
'final_date' => date('d/m/Y', strtotime($row->final_date)), | ||
'action' => [ | ||
'editar' => $permissionEdit, | ||
], | ||
]; | ||
}); | ||
|
||
/** | ||
* ES: Este método retorna la estructura construida tal como la requiere la librería DataTable en el Front. | ||
* EN: This method returns the constructed structure as required by the DataTable library on the Front. | ||
*/ | ||
return $datatable->response(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
<!-- ES: Asegúrate de tener la importación de jQuery y la biblioteca DataTable o las importaciones del tema metronic si trabjas con el --> | ||
<!-- EN: Make sure you have the jQuery import and the DataTable library or the Metronic theme imports if you're working with it. --> | ||
<script src="../jquery-3.6.0.min.js"></script> | ||
<script src="../dataTables.min.js"></script> | ||
|
||
<!-- ES: Deberás crear la estructura de la tabla y asignarle un ID que se utilizará como selector para convertirla en una "DataTable". Además, asegúrate de que los encabezados coincidan con el número de columnas configurado en JavaScript. --> | ||
<!-- EN: You should create the table structure and assign it an ID that will be used as a selector to make it a "DataTable". Additionally, ensure that the headers match the number of columns configured in JavaScript. --> | ||
<table id="datatable" class="table table-striped table-hover"> | ||
<thead> | ||
<tr> | ||
<th>Identification</th> | ||
<th>Employee</th> | ||
<th>Novelty Type</th> | ||
<th>Description</th> | ||
<th>Ccalendar Days</th> | ||
<th>Business Days</th> | ||
<th>Initial Date</th> | ||
<th>Final Date</th> | ||
<th>Action</th> | ||
</tr> | ||
</thead> | ||
</table> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
/* ES: Crearás una variable global en el archivo JS para almacenar el valor de la tabla de datos a construir. Esto te será de gran utilidad cuando necesites actualizar la información de la tabla sin tener que recargar la página. */ | ||
/* EN: You will create a global variable in the JS file to store the value of the data table to be built. This will be very useful when you need to update the table information without reloading the page. */ | ||
var dataTable; | ||
|
||
/* ES: Define esta variable que contendrá la base del servidor a donde se enviarán las peticiones */ | ||
/* EN: Define this variable that will hold the server base where requests will be sent to */ | ||
var baseUrl = window.location.protocol + "//" + window.location.host | ||
|
||
/* ES: Al Cargar el archivo */ | ||
/* EN: Upon loading the file */ | ||
$(document).ready(function () { | ||
|
||
/* ES: Aquí le asignaremos a la variable una instancia de dataTable, garantiza que sea el mismo ID del tag table */ | ||
/* EN: Here, we will assign an instance of dataTable to the variable, ensure it matches the ID of the table tag */ | ||
dataTable = $("#datatable").DataTable({ | ||
processing: true, | ||
responsive: true, | ||
pagingType: "full_numbers", | ||
ajax: { | ||
/* ES: Asegúrate de que la ruta (web.php) sea de tipo GET */ | ||
/* EN: Ensure that the route (web.php) is of type GET */ | ||
url: baseUrl + "/modulo/datatable", | ||
dataSrc: "data", | ||
}, | ||
columns: [ | ||
/* ES: El nombre debe ser el mismo que el del arreglo asociativo devuelto desde el BackEnd */ | ||
/* EN: The name must be the same as that of the associative array returned from the BackEnd */ | ||
{ data: "identification" }, | ||
{ data: "employee" }, | ||
{ data: "novelty_type" }, | ||
{ data: "description" }, | ||
{ data: "calendar_days" }, | ||
{ data: "business_days" }, | ||
{ data: "initial_date" }, | ||
{ data: "final_date" }, | ||
{ | ||
data: "action", | ||
render: function (data, type, row, meta) { | ||
let btnEdit = ""; | ||
if (data.editar) { | ||
btnEdit = `<button class="btn btn-sm btn-info btn-edit" data-id="${row.identification}" data-employee="${row.employee}" title="Edit"> | ||
<i class="fa flaticon-edit-1"></i> | ||
</button>`; | ||
} | ||
return `<div class='btn-group'>${btnEdit}</div>`; | ||
}, | ||
orderable: false, | ||
}, | ||
], | ||
/* ES: Recuerda que puedes aplicar la configuración de idioma de tu región. */ | ||
/* EN: Remember that you can apply the language configuration of your region. */ | ||
language: { | ||
url: "https://cdn.datatables.net/plug-ins/1.13.5/i18n/es-ES.json", | ||
}, | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
/** | ||
* ESTE CODIGO ES EXCLUSIVO PARA USARLO EN LOS PROYECTOS QUE EMPLEEN EL TEMA METRONIC | ||
* THIS CODE IS EXCLUSIVE FOR USE IN PROJECTS THAT USE THE METRONIC THEME | ||
* https://keenthemes.com/metronic | ||
* https://preview.keenthemes.com/html/metronic/docs/general/datatables/server-side (See For More Settings) | ||
*/ | ||
|
||
/* ES: Define esta variable que contendrá la base del servidor a donde se enviarán las peticiones */ | ||
/* EN: Define this variable that will hold the server base where requests will be sent to */ | ||
var baseUrl = window.location.protocol + "//" + window.location.host | ||
|
||
/* ES: Se requiere crear una variable global en la cual se aloje una función autoinvocada. */ | ||
/* EN: It is required to create a global variable in which a self-invoking function is hosted. */ | ||
var KTDatatablesServerSide = function () { | ||
|
||
|
||
/* ES: Variables que se emplearan durante la ejecucion de la funcion autoinvocada. */ | ||
/* EN: Variables that will be used during the execution of the self-invoking function. */ | ||
var table; | ||
var dt; | ||
|
||
/* ES: Funcion privada para la construccion de la datatable */ | ||
/* EN: Private function for datatable construction. */ | ||
var initDatatable = function () { | ||
dt = $("#datatable").DataTable({ | ||
processing: true, | ||
responsive: true, | ||
pagingType: "full_numbers", | ||
ajax: { | ||
/* ES: Asegúrate de que la ruta (web.php) sea de tipo GET */ | ||
/* EN: Ensure that the route (web.php) is of type GET */ | ||
url: baseUrl + "/modulo/datatable", | ||
dataType: "JSON", | ||
type: "GET", | ||
}, | ||
columns: [ | ||
/* ES: El nombre debe ser el mismo que el del arreglo asociativo devuelto desde el BackEnd */ | ||
/* EN: The name must be the same as that of the associative array returned from the BackEnd */ | ||
{ data: "identification" }, | ||
{ data: "employee" }, | ||
{ data: "novelty_type" }, | ||
{ data: "description" }, | ||
{ data: "calendar_days" }, | ||
{ data: "business_days" }, | ||
{ data: "initial_date" }, | ||
{ data: "final_date" }, | ||
{ | ||
data: "action", | ||
render: function (data, type, row, meta) { | ||
let btnEdit = ""; | ||
if (data.editar) { | ||
btnEdit = `<button class="btn btn-sm btn-info btn-edit" data-id="${row.identification}" data-employee="${row.employee}" title="Edit"> | ||
<i class="fa flaticon-edit-1"></i> | ||
</button>`; | ||
} | ||
return `<div class='btn-group'>${btnEdit}</div>`; | ||
}, | ||
orderable: false, | ||
}, | ||
], | ||
/* ES: Recuerda que puedes aplicar la configuración de idioma de tu región. */ | ||
/* EN: Remember that you can apply the language configuration of your region. */ | ||
"oLanguage": { | ||
"sUrl": "https://cdn.datatables.net/plug-ins/1.13.5/i18n/es-ES.json" | ||
} | ||
}); | ||
|
||
table = dt.$; | ||
} | ||
|
||
/* ES: Aqui puedes definir cual será el input de busqueda (official docs reference: https://datatables.net/reference/api/search()) */ | ||
/* EN: Here you can define which will be the search input.(official docs reference: https://datatables.net/reference/api/search()) */ | ||
var handleSearchDatatable = function () { | ||
const filterSearch = document.querySelector('[data-kt-docs-table-filter="search"]'); | ||
filterSearch.addEventListener('keyup', function (e) { | ||
dt.search(e.target.value).draw(); | ||
}); | ||
} | ||
|
||
/* ES: Metodo para la inicializacion de la datatable. */ | ||
/* EN: Method for the initialization of the datatable. */ | ||
return { | ||
init: function () { | ||
initDatatable(); | ||
handleSearchDatatable(); | ||
} | ||
} | ||
}(); | ||
|
||
/* ES: Cuando cargue el documento se llamará la variable con su funcion, algo importante es que tambien se podria usar el metodo de Jquery */ | ||
/* EN: When the document loads, the variable will be called with its function; something important is that you could also use the jQuery method. */ | ||
// KTUtil.onDOMContentLoaded() == $(document).ready() | ||
KTUtil.onDOMContentLoaded(function () { | ||
KTDatatablesServerSide.init(); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
<?php | ||
|
||
use Rmunate\EasyDatatable\EasyDataTable; | ||
|
||
class NameController extends Controller | ||
{ | ||
/** | ||
* ES: Define un método que maneje la ruta tipo GET recibiendo una variable de tipo Request. | ||
* EN: Define a method that handles the GET type route receiving a Request type variable. | ||
*/ | ||
public function dataTable(Request $request) | ||
{ | ||
/** | ||
* ES: Crea una consulta con Query Builder, puedes aplicar todas las condiciones que requieras, solo NO apliques el método final get(). | ||
* EN Create a query using Query Builder, you can apply all the conditions you require, just DO NOT apply the final get() method. | ||
*/ | ||
$query = DB::table('novedades') | ||
->leftJoin('tipo_novedades', 'tipo_novedades.id', '=', 'novedades.tipo_novedad_id') | ||
->leftJoin('empleados', 'empleados.id', '=', 'novedades.empleado_id') | ||
->select( | ||
'empleados.cedula AS identification', | ||
'empleados.nombre AS employee', | ||
'tipo_novedades.nombre AS novelty_type', | ||
'novedades.descripcion AS description', | ||
'novedades.dias_calendario AS calendar_days', | ||
'novedades.dias_habiles AS business_days', | ||
'novedades.fecha_inicial AS initial_date', | ||
'novedades.fecha_final AS final_date', | ||
); | ||
|
||
/** | ||
* ES: (Opcional) A veces, para determinar si un usuario tiene permisos sobre alguna acción en las filas de la tabla, debes realizar consultas como estas. | ||
* EN: (Optional) Sometimes, to determine if a user has permissions for some action on the table rows, you need to make queries like these. | ||
*/ | ||
$permissionEdit = Auth::user()->can('novedades.editar'); /* (Opcional) */ | ||
|
||
/** | ||
* ES: El uso de la librería es tan simple como emplear el siguiente código. | ||
* EN: Using the library is as simple as using the following code. | ||
*/ | ||
$datatable = new EasyDataTable(); | ||
$datatable->serverSide(); /* Obligatorio / Requerid */ | ||
$datatable->request($request); | ||
$datatable->query($query); | ||
$datatable->map(function ($row) use ($editar) { | ||
/** | ||
* ES: (Opcional) Si necesitas personalizar la forma en que se visualiza la información en la tabla, el método map() será de gran ayuda. | ||
* Además, si necesitas enviar datos adicionales o realizar validaciones, aquí puedes aplicar la lógica. | ||
* Es importante que el alias de cada valor en la consulta sea el mismo valor que se utiliza en el array, como se muestra a continuación. | ||
*/ | ||
|
||
/** | ||
* EN: (Optional) If you need to customize how the information is displayed in the table, the map() method will be very helpful. | ||
* Additionally, if you need to send additional data or perform validations, you can apply the logic here. | ||
* It's important that the alias of each value in the query is the same as the value used in the array, as shown below. | ||
*/ | ||
|
||
return [ | ||
'identification' => $row->identification, | ||
'employee' => strtolower($row->employee), | ||
'novelty_type' => strtolower($row->novelty_type), | ||
'description' => strtolower($row->description), | ||
'calendar_days' => $row->calendar_days, | ||
'business_days' => $row->business_days, | ||
'initial_date' => date('d/m/Y', strtotime($row->initial_date)), | ||
'final_date' => date('d/m/Y', strtotime($row->final_date)), | ||
'action' => [ | ||
'editar' => $editar, | ||
], | ||
]; | ||
}); | ||
$datatable->search(function ($query, $search) { | ||
/* ES: Este método será de gran utilidad para definir qué filtros debe ejecutar el backend cuando se ingresen valores dentro del campo de búsqueda. La variable $search contendrá este valor. Recuerda utilizar la estructura tabla.campo en las condiciones y no los alias. */ | ||
/* EN: This method will be very useful to define which filters the backend should execute when values are entered in the search field. The variable $search will contain this value. Remember to use the table.field structure in the conditions and not the aliases. */ | ||
return $query->where(function ($query) use ($search) { | ||
$query->where('novedades.id', 'like', "%{$search}%") | ||
->orWhere('novedades.descripcion', 'like', "%{$search}%") | ||
->orWhere('tipo_novedades.nombre', 'like', "%{$search}%") | ||
->orWhere('empleados.nombre', 'like', "%{$search}%") | ||
->orWhere('empleados.cedula', 'like', "%{$search}%"); | ||
}); | ||
}); | ||
|
||
/** | ||
* ES: Este método retorna la estructura construida tal como la requiere la librería DataTable en el Front. | ||
* EN: This method returns the constructed structure as required by the DataTable library on the Front. | ||
*/ | ||
return $datatable->response(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
<!-- ES: Asegúrate de tener la importación de jQuery y la biblioteca DataTable --> | ||
<!-- EN: Ensure you have the jQuery and DataTable library imports --> | ||
<script src="../jquery-3.6.0.min.js"></script> | ||
<script src="../dataTables.min.js"></script> | ||
|
||
<!-- ES: Deberás crear la estructura de la tabla y asignarle un ID que se utilizará como selector para convertirla en una "DataTable". Además, asegúrate de que los encabezados coincidan con el número de columnas configurado en JavaScript. --> | ||
<!-- EN: You should create the table structure and assign it an ID that will be used as a selector to make it a "DataTable". Additionally, ensure that the headers match the number of columns configured in JavaScript. --> | ||
<table id="datatable" class="table table-striped table-hover"> | ||
<thead> | ||
<tr> | ||
<th>Identification</th> | ||
<th>Employee</th> | ||
<th>Novelty Type</th> | ||
<th>Description</th> | ||
<th>Ccalendar Days</th> | ||
<th>Business Days</th> | ||
<th>Initial Date</th> | ||
<th>Final Date</th> | ||
<th>Action</th> | ||
</tr> | ||
</thead> | ||
</table> |
Oops, something went wrong.