¿Manejo de errores en CakePHP que devuelve los valores publicados por el usuario para formarse?
-
26-10-2019 - |
Pregunta
Por lo general, la forma común de manejar un error es hacer la redirección simple así:
if ({something that is error}) {
$this->Session->setFlash(__('Error message'), true);
$this->redirect(array('controller' => 'some_controller', 'action' => 'some_action'));
}
Sin embargo, hay múltiples controles que ocurren durante el if ($this->request->is('post')) {
Sección del método. Si cualquiera de los cheques falla, quiero salir del resto de los cheques, devolver al usuario al formulario con todas las configuraciones que ingresó anteriormente para que no tengan que completar los formularios nuevamente. ¿Cómo lograría esto?
public function custom_method() {
// get some information here
if ($this->request->is('post')) {
// do_check
if (!do_check) {
// set flash
// log error
// don't run the rest of the checks - go to end of the if ($this->request->is('post'))
}
// do other check
if (!do_other_check) {
// set flash
// log error
// don't run the rest of the checks - go to end of the if ($this->request->is('post'))
}
// do database update
}
// do other stuff here
// then it goes to render view
}
Solución
¡Trabajé en una gran solución a esto después de hablar con un buen amigo mío (gracias @utoxin)! Ayudó a empujarme en la dirección correcta con su mención de validación del modelo.
Así es como lo lograré:
public function prepare() {
// do some stuff here
if ($this->request->is('post')) {
$postValid = true;
if ($postValid and !some_check) {
$this->log('Log error here', 'error');
$this->Model->invalidate('form_field', 'No valid installation file was found for this version.');
$postValid = false;
}
if($postValid){
// no error, do redirect, continue successfully
}
}
// do other stuff here
// show form
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow