Terminando formulario 2

This commit is contained in:
Jaime Jimenez
2023-07-12 12:53:52 +02:00
parent 810e1c8b37
commit 1908290167
5 changed files with 678 additions and 0 deletions

View File

@ -0,0 +1,309 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Models\Collection;
use App\Entities\Configuracion\MaquinasDefectoEntity;
use App\Models\Configuracion\MaquinaModel;
use App\Models\Configuracion\MaquinasDefectoModel;
class Maquinasdefecto extends \App\Controllers\GoBaseResourceController {
protected $modelName = MaquinasDefectoModel::class;
protected $format = 'json';
protected static $singularObjectName = 'Maquina Por Defecto';
protected static $singularObjectNameCc = 'maquinaPorDefecto';
protected static $pluralObjectName = 'Maquinas Por Defecto';
protected static $pluralObjectNameCc = 'maquinasPorDefecto';
protected static $controllerSlug = 'maquinasdefecto';
protected static $viewPath = 'themes/backend/vuexy/form/configuracion/maquinas/';
protected $indexRoute = 'maquinaPorDefectoList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) {
$this->viewData['pageTitle'] = lang('MaquinasPorDefecto.moduleTitle');
$this->viewData['usingSweetAlert'] = true;
parent::initController($request, $response, $logger);
}
public function index() {
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('MaquinasPorDefecto.maquinaPorDefecto')]),
'maquinasDefectoEntity' => new MaquinasDefectoEntity(),
'usingServerSideDataTable' => true,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath.'viewMaquinaPorDefectoList', $viewData);
}
public function add() {
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->save($sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['errorMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('MaquinasPorDefecto.maquinaPorDefecto'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$thenRedirect = true; // Change this to false if you want your user to stay on the form after submission
endif;
if ($noException && $successfulResult) :
$id = $this->model->db->insertID();
$message = lang('Basic.global.saveSuccess', [mb_strtolower(lang('MaquinasPorDefecto.maquinaPorDefecto'))]).'.';
$message .= anchor( "maquinasdefecto/{$id}/edit" , lang('Basic.global.continueEditing').'?');
$message = ucfirst(str_replace("'", "\'", $message));
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['maquinasDefectoEntity'] = isset($sanitizedData) ? new MaquinasDefectoEntity($sanitizedData) : new MaquinasDefectoEntity();
$this->viewData['maquinaList'] = $this->getMaquinaListItems($maquinasDefectoEntity->maquina_id ?? null);
$this->viewData['tipoList'] = $this->getTipoOptions();
$this->viewData['formAction'] = route_to('createMaquinaPorDefecto');
$this->viewData['boxTitle'] = lang('Basic.global.addNew').' '.lang('MaquinasPorDefecto.moduleTitle').' '.lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__);
} // end function add()
public function edit($requestedId = null) {
if ($requestedId == null) :
return $this->redirect2listView();
endif;
$id = filter_var($requestedId, FILTER_SANITIZE_URL);
$maquinasDefectoEntity = $this->model->find($id);
if ($maquinasDefectoEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('MaquinasPorDefecto.maquinaPorDefecto')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('MaquinasPorDefecto.maquinaPorDefecto'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$maquinasDefectoEntity->fill($sanitizedData);
$thenRedirect = true;
endif;
if ($noException && $successfulResult) :
$id = $maquinasDefectoEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('MaquinasPorDefecto.maquinaPorDefecto'))]).'.';
$message .= anchor( "maquinasdefecto/{$id}/edit" , lang('Basic.global.continueEditing').'?');
$message = ucfirst(str_replace("'", "\'", $message));
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['maquinasDefectoEntity'] = $maquinasDefectoEntity;
$this->viewData['maquinaList'] = $this->getMaquinaListItems($maquinasDefectoEntity->maquina_id ?? null);
$this->viewData['tipoList'] = $this->getTipoOptions();
$this->viewData['formAction'] = route_to('updateMaquinaPorDefecto', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2').' '.lang('MaquinasPorDefecto.moduleTitle').' '.lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
} // end function edit(...)
public function datatable() {
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$requestedOrder2 = $reqData['order']['1']['column'] ?? $requestedOrder;
$order = MaquinasDefectoModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0];
$order2 = MaquinasDefectoModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : 0];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$dir2 = $reqData['order']['1']['dir'] ?? $dir;
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->orderBy($order2, $dir2)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($search)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function allItemsSelect() {
if ($this->request->isAJAX()) {
$onlyActiveOnes = true;
$reqVal = $this->request->getPost('val') ?? 'id';
$menu = $this->model->getAllForMenu($reqVal.', tipo', 'tipo', $onlyActiveOnes, false);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->tipo = '- '.lang('Basic.global.None').' -';
array_unshift($menu , $nonItem);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function menuItems() {
if ($this->request->isAJAX()) {
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
$reqId = goSanitize($this->request->getPost('id'))[0];
$reqText = goSanitize($this->request->getPost('text'))[0];
$onlyActiveOnes = false;
$columns2select = [$reqId ?? 'id', $reqText ?? 'tipo'];
$onlyActiveOnes = false;
$menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr);
$nonItem = new \stdClass;
$nonItem->id = '';
$nonItem->text = '- '.lang('Basic.global.None').' -';
array_unshift($menu , $nonItem);
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$data = [
'menu' => $menu,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
protected function getMaquinaListItems($selId = null) {
$data = [''=>lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Maquinas.maquina'))])];
if (!empty($selId)) :
$maquinaModel = model('App\Models\Configuracion\MaquinaModel');
$selOption = $maquinaModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)) :
$data[$selId] = $selOption[0];
endif;
endif;
return $data;
}
protected function getTipoOptions() {
$tipoOptions = [
'' => lang('Basic.global.pleaseSelect'),
'bn' => 'bn',
'bnhq' => 'bnhq',
'color' => 'color',
'portada' => 'portada',
'cubierta' => 'cubierta',
'rotativa' => 'rotativa',
];
return $tipoOptions;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Entities\Configuracion;
use CodeIgniter\Entity;
class MaquinasDefectoEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
"id" => null,
"tipo" => null,
"ancho_min" => 0.0,
"ancho_max" => 0.0,
"alto_min" => 0.0,
"alto_max" => 0.0,
"tirada_min" => 1,
"tirada_max" => 10000,
"maquina_id" => null,
"user_created_id" => 0,
"user_updated_id" => 0,
"is_deleted" => 0,
"created_at" => null,
"updated_at" => null,
];
protected $casts = [
"ancho_min" => "float",
"ancho_max" => "float",
"alto_min" => "float",
"alto_max" => "float",
"tirada_min" => "int",
"tirada_max" => "int",
"maquina_id" => "int",
"user_created_id" => "int",
"user_updated_id" => "int",
"is_deleted" => "int",
];
}

View File

@ -0,0 +1,80 @@
<?php
return [
'altoMax' => 'Max Height',
'altoMin' => 'Min Height',
'anchoMax' => 'Max Width',
'anchoMin' => 'Min Width',
'bn' => 'B/W',
'bnhq' => 'B/W HQ',
'color' => 'Color',
'createdAt' => 'Created At',
'cubierta' => 'Cover',
'deletedAt' => 'Deleted At',
'id' => 'ID',
'isDeleted' => 'Is Deleted',
'maquinaId' => 'Machine',
'maquinaPorDefecto' => 'Default Machine',
'maquinaPorDefectoList' => 'Default Machine List',
'maquinadefecto' => 'Default Machines',
'maquinasPorDefecto' => 'Default Machines',
'maquinasdefecto' => 'Default Machines',
'moduleTitle' => 'Default Machines',
'portada' => 'Cover',
'rotativa' => 'Rotary',
'tipo' => 'Type',
'tiradaMax' => 'Max Printing',
'tiradaMin' => 'Min Printing',
'updatedAt' => 'Updated At',
'userCreatedId' => 'User Created ID',
'userUpdatedId' => 'User Updated ID',
'validation' => [
'alto_max' => [
'decimal' => 'The {field} field must contain a decimal number.',
'required' => 'The {field} field is required.',
],
'alto_min' => [
'decimal' => 'The {field} field must contain a decimal number.',
'required' => 'The {field} field is required.',
],
'ancho_max' => [
'decimal' => 'The {field} field must contain a decimal number.',
'required' => 'The {field} field is required.',
],
'ancho_min' => [
'decimal' => 'The {field} field must contain a decimal number.',
'required' => 'The {field} field is required.',
],
'tipo' => [
'in_list' => 'The {field} field must be one of: {param}.',
'required' => 'The {field} field is required.',
],
'tirada_max' => [
'integer' => 'The {field} field must contain an integer.',
'required' => 'The {field} field is required.',
],
'tirada_min' => [
'integer' => 'The {field} field must contain an integer.',
'required' => 'The {field} field is required.',
],
],
];

View File

@ -0,0 +1,80 @@
<?php
return [
'altoMax' => 'Alto Max',
'altoMin' => 'Alto Min',
'anchoMax' => 'Ancho Max',
'anchoMin' => 'Ancho Min',
'bn' => 'B/N',
'bnhq' => 'B/N HQ',
'color' => 'Color',
'createdAt' => 'Created At',
'cubierta' => 'Cubierta',
'deletedAt' => 'Deleted At',
'id' => 'ID',
'isDeleted' => 'Is Deleted',
'maquinaId' => 'Máquina',
'maquinaPorDefecto' => 'Máquina Por Defecto',
'maquinaPorDefectoList' => 'Lista Máquinas Por Defecto',
'maquinadefecto' => 'Máquinas Por Defecto',
'maquinasPorDefecto' => 'Máquinas Por Defecto',
'maquinasdefecto' => 'Máquinas Por Defecto',
'moduleTitle' => 'Máquinas Por Defecto',
'portada' => 'Portada',
'rotativa' => 'Rotativa',
'tipo' => 'Tipo',
'tiradaMax' => 'Tirada Max',
'tiradaMin' => 'Tirada Min',
'updatedAt' => 'Updated At',
'userCreatedId' => 'User Created ID',
'userUpdatedId' => 'User Updated ID',
'validation' => [
'alto_max' => [
'decimal' => 'El campo {field} debe contener un número decimal.',
'required' => 'El campo {field} es obligatorio.',
],
'alto_min' => [
'decimal' => 'El campo {field} debe contener un número decimal.',
'required' => 'El campo {field} es obligatorio.',
],
'ancho_max' => [
'decimal' => 'El campo {field} debe contener un número decimal.',
'required' => 'El campo {field} es obligatorio.',
],
'ancho_min' => [
'decimal' => 'El campo {field} debe contener un número decimal.',
'required' => 'El campo {field} es obligatorio.',
],
'tipo' => [
'in_list' => 'El campo {field} debe ser uno de: {param}.',
'required' => 'El campo {field} es obligatorio.',
],
'tirada_max' => [
'integer' => 'El campo {field} debe contener un número entero.',
'required' => 'El campo {field} es obligatorio.',
],
'tirada_min' => [
'integer' => 'El campo {field} debe contener un número entero.',
'required' => 'El campo {field} es obligatorio.',
],
],
];

View File

@ -0,0 +1,173 @@
<?php
namespace App\Models\Configuracion;
class MaquinasDefectoModel extends \App\Models\GoBaseModel
{
protected $table = "lg_maquina_por_defecto";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
const SORTABLE = [
0 => "t1.tipo",
1 => "t2.nombre",
2 => "t1.ancho_min",
3 => "t1.ancho_max",
4 => "t1.alto_min",
5 => "t1.alto_max",
6 => "t1.tirada_min",
7 => "t1.tirada_max",
];
protected $allowedFields = [
"tipo",
"ancho_min",
"ancho_max",
"alto_min",
"alto_max",
"tirada_min",
"tirada_max",
"maquina_id",
];
protected $returnType = "App\Entities\Configuracion\MaquinasDefectoEntity";
protected $useTimestamps = true;
protected $useSoftDeletes = false;
protected $createdField = "created_at";
protected $updatedField = "updated_at";
public static $labelField = "tipo";
protected $validationRules = [
"alto_max" => [
"label" => "MaquinaPorDefectoes.altoMax",
"rules" => "required|decimal",
],
"alto_min" => [
"label" => "MaquinaPorDefectoes.altoMin",
"rules" => "required|decimal",
],
"ancho_max" => [
"label" => "MaquinaPorDefectoes.anchoMax",
"rules" => "required|decimal",
],
"ancho_min" => [
"label" => "MaquinaPorDefectoes.anchoMin",
"rules" => "required|decimal",
],
"tipo" => [
"label" => "MaquinaPorDefectoes.tipo",
"rules" => "required|in_list[bn,bnhq,color,portada,cubierta,rotativa]",
],
"tirada_max" => [
"label" => "MaquinaPorDefectoes.tiradaMax",
"rules" => "required|integer",
],
"tirada_min" => [
"label" => "MaquinaPorDefectoes.tiradaMin",
"rules" => "required|integer",
],
];
protected $validationMessages = [
"alto_max" => [
"decimal" => "MaquinaPorDefectoes.validation.alto_max.decimal",
"required" => "MaquinaPorDefectoes.validation.alto_max.required",
],
"alto_min" => [
"decimal" => "MaquinaPorDefectoes.validation.alto_min.decimal",
"required" => "MaquinaPorDefectoes.validation.alto_min.required",
],
"ancho_max" => [
"decimal" => "MaquinaPorDefectoes.validation.ancho_max.decimal",
"required" => "MaquinaPorDefectoes.validation.ancho_max.required",
],
"ancho_min" => [
"decimal" => "MaquinaPorDefectoes.validation.ancho_min.decimal",
"required" => "MaquinaPorDefectoes.validation.ancho_min.required",
],
"tipo" => [
"in_list" => "MaquinaPorDefectoes.validation.tipo.in_list",
"required" => "MaquinaPorDefectoes.validation.tipo.required",
],
"tirada_max" => [
"integer" => "MaquinaPorDefectoes.validation.tirada_max.integer",
"required" => "MaquinaPorDefectoes.validation.tirada_max.required",
],
"tirada_min" => [
"integer" => "MaquinaPorDefectoes.validation.tirada_min.integer",
"required" => "MaquinaPorDefectoes.validation.tirada_min.required",
],
];
public function findAllWithMaquinas(string $selcols = "*", int $limit = null, int $offset = 0)
{
$sql =
"SELECT t1." .
$selcols .
", t2.nombre AS maquina FROM " .
$this->table .
" t1 LEFT JOIN lg_maquinas t2 ON t1.maquina_id = t2.id";
if (!is_null($limit) && intval($limit) > 0) {
$sql .= " LIMIT " . $limit;
}
if (!is_null($offset) && intval($offset) > 0) {
$sql .= " OFFSET " . $offset;
}
$query = $this->db->query($sql);
$result = $query->getResultObject();
return $result;
}
/**
* Get resource data.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResource(string $search = "")
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.tipo AS tipo, t1.ancho_min AS ancho_min, t1.ancho_max AS ancho_max, t1.alto_min AS alto_min, t1.alto_max AS alto_max, t1.tirada_min AS tirada_min, t1.tirada_max AS tirada_max, t2.nombre AS maquina"
);
$builder->join("lg_maquinas t2", "t1.maquina_id = t2.id", "left");
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.id", $search)
->orLike("t1.tipo", $search)
->orLike("t1.ancho_min", $search)
->orLike("t1.ancho_max", $search)
->orLike("t1.alto_min", $search)
->orLike("t1.alto_max", $search)
->orLike("t1.tirada_min", $search)
->orLike("t1.tirada_max", $search)
->orLike("t2.id", $search)
->orLike("t1.id", $search)
->orLike("t1.tipo", $search)
->orLike("t1.ancho_min", $search)
->orLike("t1.ancho_max", $search)
->orLike("t1.alto_min", $search)
->orLike("t1.alto_max", $search)
->orLike("t1.tirada_min", $search)
->orLike("t1.tirada_max", $search)
->orLike("t1.maquina_id", $search)
->orLike("t2.nombre", $search)
->groupEnd();
}
}