Created
January 9, 2017 12:11
-
-
Save elton182/444e8d2d07c340395732e6f4f841484b to your computer and use it in GitHub Desktop.
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
<?php | |
namespace safed\Traits; | |
Trait DataTablesTrait{ | |
/** | |
* receices the model collection with records and return a json needed for the datatable | |
* receives de name of the Controller to generate correct URLs | |
* receives the customfields (for relations) that you want to return with the json | |
* | |
* @param $records | |
* @param $name | |
* @param $customfields | |
*/ | |
public static function getDataTableJson($records,$name = '',$Customfields = []) | |
{ | |
$cont = 0; | |
$json = []; | |
foreach ($records as $record) { | |
$fields = []; | |
foreach ($record->getAttributes() as $key => $value) { | |
$fields[$key] = $record->{$key}; | |
} | |
if (!empty($Customfields)) { | |
foreach ($Customfields['relations'] as $customfield => $customfieldvalue) { | |
foreach ($customfieldvalue as $fieldName) { | |
debug($fieldName); | |
$fields[$customfield . '_' . $fieldName] = $record->{$customfield}->{$fieldName}; | |
} | |
} | |
} | |
$fields['actions'] = DataTablesTrait::withCrudActions($fields,$name); | |
array_push($json, $fields); | |
$cont++; | |
} | |
$data = | |
[ | |
"draw" => 1, | |
"recordsTotal" => $cont, | |
"recordsFiltered" => $cont, | |
'data' => $json, | |
]; | |
return json_encode($data); | |
} | |
public static function withCrudActions($array,$name){ | |
$params = ['id' => $array['id']]; | |
$consultar = '<a class="btn btn-info" href="'.action( $name . '@view', $params).'"> <i class="fa fa-eye" aria-hidden="true"></i></a>'; | |
$editar = '<a class="btn btn-warning" href="'.action( $name . '@edit', $params).'"> <i class="fa fa-pencil" aria-hidden="true"></i></a>'; | |
$excluir = '<a class="btn btn-danger" onclick=deleteRecord("'.$params['id'].'","'.action( $name . '@delete' ).'",refresh)><i class="fa fa-trash" aria-hidden="true"></i></a>'; | |
// debug($consultar); | |
return $consultar . $editar . $excluir ; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use it, make your Model use the trait, then on the controller create a method that calls the getDataTableJson
`
`