Ahora le toca al catalogo de choferes y debe contener los siguientes datos

- Empresa
- Nombre
- Apellido
Creamos el archivo de migración en App/Database/Migrations/2023-09-04154912_Choferes.php con el siguiente código
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Choferes extends Migration {
public function up() {
// Choferes
$this->forge->addField([
'id' => ['type' => 'int', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
'idEmpresa' => ['type' => 'bigint', 'constraint' => 20, 'null' => true],
'nombre' => ['type' => 'varchar', 'constraint' => 512, 'null' => true],
'Apellido' => ['type' => 'varchar', 'constraint' => 512, 'null' => true],
'created_at' => ['type' => 'datetime', 'null' => true],
'updated_at' => ['type' => 'datetime', 'null' => true],
'deleted_at' => ['type' => 'datetime', 'null' => true],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('choferes', true);
}
public function down() {
$this->forge->dropTable('choferes', true);
}
}
Creamos el archivo de modelo para choferes App/Models/ChoferesModel.php con el siguiente código
<?php
namespace App\Models;
use CodeIgniter\Model;
class ChoferesModel extends Model {
protected $table = 'choferes';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['id', 'idEmpresa', 'nombre', 'Apellido', 'created_at', 'updated_at', 'deleted_at'];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [
];
protected $validationMessages = [];
protected $skipValidation = false;
public function mdlGetChoferes($idEmpresas) {
$result = $this->db->table('choferes a, empresas b')
->select('a.id,a.idEmpresa,a.nombre,a.Apellido,a.created_at,a.updated_at,a.deleted_at ,b.nombre as nombreEmpresa')
->where('a.idEmpresa', 'b.id', FALSE)
->whereIn('a.idEmpresa', $idEmpresas);
return $result;
}
}
Creamos el archivo de controlador App/Controllers/ChoferesController.php con el siguiente código
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use \App\Models\{
ChoferesModel
};
use App\Models\LogModel;
use CodeIgniter\API\ResponseTrait;
use App\Models\EmpresasModel;
class ChoferesController extends BaseController {
use ResponseTrait;
protected $log;
protected $choferes;
public function __construct() {
$this->choferes = new ChoferesModel();
$this->log = new LogModel();
$this->empresa = new EmpresasModel();
helper('menu');
helper('utilerias');
}
public function index() {
helper('auth');
$idUser = user()->id;
$titulos["empresas"] = $this->empresa->mdlEmpresasPorUsuario($idUser);
if (count($titulos["empresas"]) == "0") {
$empresasID[0] = "0";
} else {
$empresasID = array_column($titulos["empresas"], "id");
}
if ($this->request->isAJAX()) {
$datos = $this->choferes->mdlGetChoferes($empresasID);
return \Hermawan\DataTables\DataTable::of($datos)->toJson(true);
}
$titulos["title"] = lang('choferes.title');
$titulos["subtitle"] = lang('choferes.subtitle');
return view('choferes', $titulos);
}
/**
* Read Choferes
*/
public function getChoferes() {
helper('auth');
$idUser = user()->id;
$titulos["empresas"] = $this->empresa->mdlEmpresasPorUsuario($idUser);
if (count($titulos["empresas"]) == "0") {
$empresasID[0] = "0";
} else {
$empresasID = array_column($titulos["empresas"], "id");
}
$idChoferes = $this->request->getPost("idChoferes");
$datosChoferes = $this->choferes->whereIn('idEmpresa', $empresasID)
->where("id", $idChoferes)->first();
echo json_encode($datosChoferes);
}
/**
* Save or update Choferes
*/
public function save() {
helper('auth');
$userName = user()->username;
$idUser = user()->id;
$datos = $this->request->getPost();
if ($datos["idChoferes"] == 0) {
try {
if ($this->choferes->save($datos) === false) {
$errores = $this->choferes->errors();
foreach ($errores as $field => $error) {
echo $error . " ";
}
return;
}
$dateLog["description"] = lang("vehicles.logDescription") . json_encode($datos);
$dateLog["user"] = $userName;
$this->log->save($dateLog);
echo "Guardado Correctamente";
} catch (\PHPUnit\Framework\Exception $ex) {
echo "Error al guardar " . $ex->getMessage();
}
} else {
if ($this->choferes->update($datos["idChoferes"], $datos) == false) {
$errores = $this->choferes->errors();
foreach ($errores as $field => $error) {
echo $error . " ";
}
return;
} else {
$dateLog["description"] = lang("choferes.logUpdated") . json_encode($datos);
$dateLog["user"] = $userName;
$this->log->save($dateLog);
echo "Actualizado Correctamente";
return;
}
}
return;
}
/**
* Get Custumers via AJax
*/
public function getChoferesAjax() {
$request = service('request');
$postData = $request->getPost();
$response = array();
// Read new token and assign in $response['token']
$response['token'] = csrf_hash();
$custumers = new ChoferesModel();
$idEmpresa = $postData['idEmpresa'];
if (!isset($postData['searchTerm'])) {
// Fetch record
$listCustumers = $custumers->select('id,nombre,apellido')->where("deleted_at", null)
->where('idEmpresa', $idEmpresa)
->orderBy('id')
->orderBy('nombre')
->orderBy('apellido')
->findAll(50);
} else {
$searchTerm = $postData['searchTerm'];
// Fetch record
$listCustumers = $custumers->select('id,nombre,apellido')->where("deleted_at", null)
->where('idEmpresa', $idEmpresa)
->groupStart()
->like('nombre', $searchTerm)
->orLike('id', $searchTerm)
->orLike('apellido', $searchTerm)
->groupEnd()
->findAll(50);
}
$data = array();
foreach ($listCustumers as $custumers) {
$data[] = array(
"id" => $custumers['id'],
"text" => $custumers['id'] . ' ' . $custumers['nombre'] . ' ' . $custumers['apellido'],
);
}
$response['data'] = $data;
return $this->response->setJSON($response);
}
/**
* Delete Choferes
* @param type $id
* @return type
*/
public function delete($id) {
$infoChoferes = $this->choferes->find($id);
helper('auth');
$userName = user()->username;
if (!$found = $this->choferes->delete($id)) {
return $this->failNotFound(lang('choferes.msg.msg_get_fail'));
}
$this->choferes->purgeDeleted();
$logData["description"] = lang("choferes.logDeleted") . json_encode($infoChoferes);
$logData["user"] = $userName;
$this->log->save($logData);
return $this->respondDeleted($found, lang('choferes.msg_delete'));
}
}
Creamos el archivo App/Views/choferes.php con el siguiente código
<?= $this->include('julio101290\boilerplate\Views\load\select2') ?>
<?= $this->include('julio101290\boilerplate\Views\load\datatables') ?>
<?= $this->include('julio101290\boilerplate\Views\load\nestable') ?>
<!-- Extend from layout index -->
<?= $this->extend('julio101290\boilerplate\Views\layout\index') ?>
<!-- Section content -->
<?= $this->section('content') ?>
<?= $this->include('modulesChoferes/modalCaptureChoferes') ?>
<!-- SELECT2 EXAMPLE -->
<div class="card card-default">
<div class="card-header">
<div class="float-right">
<div class="btn-group">
<button class="btn btn-primary btnAddChoferes" data-toggle="modal" data-target="#modalAddChoferes"><i class="fa fa-plus"></i>
<?= lang('choferes.add') ?>
</button>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="tableChoferes" class="table table-striped table-hover va-middle tableChoferes">
<thead>
<tr>
<th>#</th>
<th><?= lang('choferes.fields.idEmpresa') ?></th>
<th><?= lang('choferes.fields.nombre') ?></th>
<th><?= lang('choferes.fields.Apellido') ?></th>
<th><?= lang('choferes.fields.created_at') ?></th>
<th><?= lang('choferes.fields.updated_at') ?></th>
<th><?= lang('choferes.fields.deleted_at') ?></th>
<th><?= lang('choferes.fields.actions') ?> </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- /.card -->
<?= $this->endSection() ?>
<?= $this->section('js') ?>
<script>
/**
* Cargamos la tabla
*/
var tableChoferes = $('#tableChoferes').DataTable({
processing: true,
serverSide: true,
responsive: true,
autoWidth: false,
order: [[1, 'asc']],
ajax: {
url: '<?= base_url('admin/choferes') ?>',
method: 'GET',
dataType: "json"
},
columnDefs: [{
orderable: false,
targets: [7],
searchable: false,
targets: [7]
}],
columns: [{
'data': 'id'
},
{
'data': 'nombreEmpresa'
},
{
'data': 'nombre'
},
{
'data': 'Apellido'
},
{
'data': 'created_at'
},
{
'data': 'updated_at'
},
{
'data': 'deleted_at'
},
{
"data": function (data) {
return `<td class="text-right py-0 align-middle">
<div class="btn-group btn-group-sm">
<button class="btn btn-warning btnEditChoferes" data-toggle="modal" idChoferes="${data.id}" data-target="#modalAddChoferes"> <i class=" fa fa-edit"></i></button>
<button class="btn btn-danger btn-delete" data-id="${data.id}"><i class="fas fa-trash"></i></button>
</div>
</td>`
}
}
]
});
$(document).on('click', '#btnSaveChoferes', function (e) {
var idChoferes = $("#idChoferes").val();
var idEmpresa = $("#idEmpresaChoferes").val();
var nombre = $("#nombre").val();
var Apellido = $("#Apellido").val();
if (idEmpresa == 0 || idEmpresa == null) {
Toast.fire({
icon: 'error',
title: "Tiene que seleccionar la empresa"
});
return;
}
$("#btnSaveChoferes").attr("disabled", true);
var datos = new FormData();
datos.append("idChoferes", idChoferes);
datos.append("idEmpresa", idEmpresa);
datos.append("nombre", nombre);
datos.append("Apellido", Apellido);
$.ajax({
url: "<?= base_url('admin/choferes/save') ?>",
method: "POST",
data: datos,
cache: false,
contentType: false,
processData: false,
success: function (respuesta) {
if (respuesta.match(/Correctamente.*/)) {
Toast.fire({
icon: 'success',
title: "Guardado Correctamente"
});
tableChoferes.ajax.reload();
$("#btnSaveChoferes").removeAttr("disabled");
$('#modalAddChoferes').modal('hide');
} else {
Toast.fire({
icon: 'error',
title: respuesta
});
$("#btnSaveChoferes").removeAttr("disabled");
}
}
}
)
});
/**
* Carga datos actualizar
*/
/*=============================================
EDITAR Choferes
=============================================*/
$(".tableChoferes").on("click", ".btnEditChoferes", function () {
var idChoferes = $(this).attr("idChoferes");
var datos = new FormData();
datos.append("idChoferes", idChoferes);
$.ajax({
url: "<?= base_url('admin/choferes/getChoferes') ?>",
method: "POST",
data: datos,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function (respuesta) {
$("#idChoferes").val(respuesta["id"]);
$("#idEmpresaChoferes").val(respuesta["idEmpresa"]);
$("#idEmpresaChoferes").trigger("change");
$("#nombre").val(respuesta["nombre"]);
$("#Apellido").val(respuesta["Apellido"]);
}
})
})
/*=============================================
ELIMINAR choferes
=============================================*/
$(".tableChoferes").on("click", ".btn-delete", function () {
var idChoferes = $(this).attr("data-id");
Swal.fire({
title: '<?= lang('boilerplate.global.sweet.title') ?>',
text: "<?= lang('boilerplate.global.sweet.text') ?>",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '<?= lang('boilerplate.global.sweet.confirm_delete') ?>'
})
.then((result) => {
if (result.value) {
$.ajax({
url: `<?= base_url('admin/choferes') ?>/` + idChoferes,
method: 'DELETE',
}).done((data, textStatus, jqXHR) => {
Toast.fire({
icon: 'success',
title: jqXHR.statusText,
});
tableChoferes.ajax.reload();
}).fail((error) => {
Toast.fire({
icon: 'error',
title: error.responseJSON.messages.error,
});
})
}
})
})
$(function () {
$("#modalAddChoferes").draggable();
});
</script>
<?= $this->endSection() ?>
Creamos el siguiente archivo para la captura App/Views/modulesChoferes/modalCaptureChoferes.php con el siguiente código
<!-- Modal Choferes -->
<div class="modal fade" id="modalAddChoferes" tabindex="-1" role="dialog" aria-labelledby="modalAddChoferes" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><?= lang('choferes.createEdit') ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="form-choferes" class="form-horizontal">
<input type="hidden" id="idChoferes" name="idChoferes" value="0">
<div class="form-group row">
<label for="idEmpresa" class="col-sm-2 col-form-label">Empresa</label>
<div class="col-sm-10">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-pencil-alt"></i></span>
</div>
<select class="form-control idEmpresaChoferes form-controlVehiculos" name="idEmpresaChoferes" id="idEmpresaChoferes" style="width:80%;">
<option value="0">Seleccione empresa</option>
<?php
foreach ($empresas as $key => $value) {
echo "<option value='$value[id]'>$value[id] - $value[nombre] </option> ";
}
?>
</select>
</div>
</div>
</div>
<div class="form-group row">
<label for="nombre" class="col-sm-2 col-form-label"><?= lang('choferes.fields.nombre') ?></label>
<div class="col-sm-10">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-pencil-alt"></i></span>
</div>
<input type="text" name="nombre" id="nombre" class="form-control datosChoferes <?= session('error.nombre') ? 'is-invalid' : '' ?>" value="<?= old('nombre') ?>" placeholder="<?= lang('choferes.fields.nombre') ?>" autocomplete="off">
</div>
</div>
</div>
<div class="form-group row">
<label for="Apellido" class="col-sm-2 col-form-label"><?= lang('choferes.fields.Apellido') ?></label>
<div class="col-sm-10">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-pencil-alt"></i></span>
</div>
<input type="text" name="Apellido" id="Apellido" class="form-control datosChoferes <?= session('error.Apellido') ? 'is-invalid' : '' ?>" value="<?= old('Apellido') ?>" placeholder="<?= lang('choferes.fields.Apellido') ?>" autocomplete="off">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal"><?= lang('boilerplate.global.close') ?></button>
<button type="button" class="btn btn-primary btn-sm" id="btnSaveChoferes"><?= lang('boilerplate.global.save') ?></button>
</div>
</div>
</div>
</div>
<?= $this->section('js') ?>
<script>
$(document).on('click', '.btnAddChoferes', function (e) {
$("#idChoferes").val("0");
$(".datosChoferes").val("");
$("#idEmpresaChoferes").val("0");
$("#idEmpresaChoferes").trigger("change");
$("#btnSaveChoferes").removeAttr("disabled");
});
/*
* AL hacer click al editar
*/
$(document).on('click', '.btnEditChoferes', function (e) {
var idChoferes = $(this).attr("idChoferes");
//LIMPIAMOS CONTROLES
$(".form-control").val("");
$("#idChoferes").val(idChoferes);
$("#btnGuardarChoferes").removeAttr("disabled");
});
$("#idEmpresaChoferes").select2();
</script>
<?= $this->endSection() ?>
En App/Config/Routes.php agregamos las rutas en el grupo admin
$routes->resource('choferes', [
'filter' => 'permission:choferes-permission',
'controller' => 'choferesController',
'except' => 'show'
]);
$routes->post('choferes/save', 'ChoferesController::save');
$routes->post('choferes/getChoferes', 'ChoferesController::getChoferes');
$routes->post('choferes/getChoferesAjax', 'ChoferesController::getChoferesAjax');
Agregamos el archivo de lenguaje para ingles en App/Languaje/en/choferes.php con el siguiente código.
<?php
$choferes["logDescription"] = "The choferes was saved with the following data:";
$choferes["logUpdate"] = "The choferes was updated with the following data:";
$choferes["logDeleted"] = "The choferes was deleted with the following data:";
$choferes["msg_delete"] = "The choferes was deleted correctly:";
$choferes["add"] = "Add Choferes";
$choferes["edit"] = "Edit choferes";
$choferes["createEdit"] = "Create / Edit";
$choferes["title"] = "choferes management";
$choferes["subtitle"] = "choferes list";
$choferes["fields"]["idEmpresa"] = "IdEmpresa";
$choferes["fields"]["nombre"] = "Nombre";
$choferes["fields"]["Apellido"] = "Apellido";
$choferes["fields"]["created_at"] = "Created_at";
$choferes["fields"]["updated_at"] = "Updated_at";
$choferes["fields"]["deleted_at"] = "Deleted_at";
$choferes["fields"]["actions"] = "Actions";
$choferes["msg"]["msg_insert"] = "The choferes has been correctly added.";
$choferes["msg"]["msg_update"] = "The choferes has been correctly modified.";
$choferes["msg"]["msg_delete"] = "The choferes has been correctly deleted.";
$choferes["msg"]["msg_get"] = "The Choferes has been successfully get.";
$choferes["msg"]["msg_get_fail"] = "The choferes not found or already deleted.";
return $choferes;
Agregamos el archivo de lenguaje para ingles en App/Languaje/es/choferes.php con el siguiente código.
<?php
$choferes["logDescription"] = "El registro en choferes fue guardado con los siguientes datos:";
$choferes["logUpdate"] = "El registro en choferes fue actualizado con los siguientes datos:";
$choferes["logDeleted"] = "El registro en choferes fue eliminado con los siguientes datos:";
$choferes["msg_delete"] = "El Registro en choferes fue eliminado correctamente:";
$choferes["add"] = "Agregar Choferes";
$choferes["edit"] = "Editar choferes";
$choferes["createEdit"] = "Crear / Editar";
$choferes["title"] = "Admon. choferes";
$choferes["subtitle"] = "Lista choferes";
$choferes["fields"]["idEmpresa"] = "Empresa";
$choferes["fields"]["nombre"] = "Nombre";
$choferes["fields"]["Apellido"] = "Apellido";
$choferes["fields"]["created_at"] = "Created_at";
$choferes["fields"]["updated_at"] = "Updated_at";
$choferes["fields"]["deleted_at"] = "Deleted_at";
$choferes["fields"]["actions"] = "Acciones";
$choferes["msg"]["msg_insert"] = "Registro agregado correctamente.";
$choferes["msg"]["msg_update"] = "Registro modificado correctamente.";
$choferes["msg"]["msg_delete"] = "Registro eliminado correctamente.";
$choferes["msg"]["msg_get"] = "Registro obtenido correctamente.";
$choferes["msg"]["msg_get_fail"] = "Registro no encontrado o eliminado.";
return $choferes;
Agregamos el menú de choferes con los siguientes datos

Agregamos el permiso

Y listo ya tenemos nuestro catalogo de choferes

1 pingback