Domanda

In genere, il modo comune per gestire un errore è quello di semplice fare il redirect in questo modo:

if ({something that is error}) {
    $this->Session->setFlash(__('Error message'), true);
    $this->redirect(array('controller' => 'some_controller', 'action' => 'some_action'));
}

Tuttavia, ci sono più controlli che si verificano durante la sezione if ($this->request->is('post')) { del metodo. Se uno dei controlli fallisce, voglio uscire dal resto dei controlli, riportare l'utente al form con tutte le impostazioni sono entrati in precedenza in modo da non devono compilare i moduli di nuovo. Come faccio a fare questo?

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 
}
È stato utile?

Soluzione

ho lavorato fuori una grande soluzione a questo dopo aver parlato con un mio caro amico (grazie @utoxin)! Mi ha aiutato a spingere nella giusta direzione con la sua menzione di validazione del modello.

Ecco come mi servirà allo scopo:

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
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top