2009-12-29 11 views
6

Ho un modulo che richiede all'utente di immettere alcune informazioni. Se non riescono a completare i campi richiesti vengono ripresentati con il modulo; la parte superiore della pagina che notifica loro quali campi sono obbligatori e ho abilitato i moduli permanenti (set_value()) in modo che il loro input non vada perso.Codeigniter - modulo di ripopolamento in caso di convalida non riuscita dopo aver inviato

Sto utilizzando flashdata per visualizzare i messaggi all'utente (ad esempio, se ciò che hanno inserito esiste già nel database).

Il mio modulo è nel metodo dell'indice del mio controller. Quando si fa clic su invia dalla mia vista, chiama il metodo add() nel mio controller. Il metodo add() esegue la convalida e, in base ai risultati, viene inoltrato al database o riprende all'utente per ottenere più dati.

Ho diversi problemi con il modo in cui ho fatto questo. 1. Se la validazione fallisce, sto usando $ this-> index() per tornare al mio modulo e visualizzare gli errori di validazione. Se provo a utilizzare il reindirizzamento, perdo i miei errori di convalida e i miei dati $ _POST [] in modo che i moduli appiccicosi finiscano in bianco. 2. L'uso di $ this-> index() consente di aggiungere "aggiungi" alla fine del mio url 3. L'utilizzo di $ this-> index() causa problemi con i flashdata. Risultati casuali

Qualche idea?

<?php 
class Restaurant extends Controller { 

    function Restaurant() { 
     parent::Controller(); 
    } 

    function index() { 

     // Load libraries and models 
     $this->load->model('/restaurant/mRestaurantTypes'); 
     $this->load->model('/restaurant/mRestaurant'); 
     $this->load->model('/utilities/mUtilities'); 

     // Get states 
     $stateSelect = array(); 
     $getStates = $this->mUtilities->getStates(); 

     if($getStates->num_rows() > 0) { 
      foreach($getStates->result() as $row) { 
       $stateSelect[$row->abbr] = $row->name; 
      } 
     } 


     // Get restaurant types 
     $restaurantTypes = array(); 
     $getRestaurantTypes = $this->mRestaurantTypes->getRestaurantTypes(); 

     if($getRestaurantTypes->num_rows() > 0) { 
      foreach($getRestaurantTypes->result() as $row) { 
       $restaurantTypes[$row->restaurant_types_id] = $row->type; 
      } 
     } 

     // Create form elements 
     $data['name'] = array(
      'name'  => 'name', 
      'id'  => 'name', 
      'value'  => set_value('name'), 
      'maxlength' => '200', 
      'size'  => '50' 
     ); 

     $data['address'] = array(
      'name'  => 'address', 
      'id'  => 'address', 
      'value'  => set_value('address'), 
      'maxlength' => '200', 
      'size'  => '50' 
     ); 

     $data['city'] = array(
      'name'  => 'city', 
      'id'  => 'city', 
      'value'  => set_value('city'), 
      'maxlength' => '50', 
      'size'  => '25'   
     ); 

     $data['state'] = $stateSelect; 

     $data['zip'] = array(
      'name'  => 'zip', 
      'id'  => 'zip', 
      'value'  => set_value('zip'), 
      'maxlength' => '10', 
      'size'  => '10'  
     ); 

     $data['phone'] = array(
      'name'  => 'phone', 
      'id'  => 'phone', 
      'value'  => set_value('phone'), 
      'maxlength' => '15', 
      'size'  => '15'  
     ); 

     $data['url'] = array(
      'name'  => 'url', 
      'id'  => 'url', 
      'value'  => set_value('url'), 
      'maxlength' => '255', 
      'size'  => '50'  
     ); 

     $data['type'] = $restaurantTypes; 

     $data['tags'] = array(
      'name'  => 'tags', 
      'id'  => 'tags', 
      'value'  => set_value('tags'), 
      'maxlength' => '255', 
      'size'  => '50'  
     ); 

     $data['active'] = array(
      'name'  => 'active', 
      'id'  => 'active', 
      'value'  => 'Y', 
      'maxlength' => '1', 
      'size'  => '2' 
     ); 

     // Set page variables 
     $data_h['title'] = "Add new restaurant"; 

     // Load views 
     $this->load->view('/template/header', $data_h); 
     $this->load->view('/restaurant/index', $data); 
     $this->load->view('/template/footer');  

    } 


    /** 
    * Add the the new restaurant to the database. 
    */ 
    function add() { 

     // Load libraries and models 
     $this->load->library('form_validation'); 
     $this->load->model('/restaurant/mRestaurant'); 

     // Define validation rules 
     $this->form_validation->set_rules('name',  'Name',  'trim|required|max_length[255]|xss_clean'); 
     $this->form_validation->set_rules('address', 'Address', 'trim|required|max_length[100]|xss_clean'); 
     $this->form_validation->set_rules('city',  'City',  'trim|required|max_length[128]|xss_clean'); 
     //$this->form_validation->set_rules('state',  'State', 'trim|required'); 
     $this->form_validation->set_rules('zip',  'Zip',  'trim|required|max_length[128]|xss_clean'); 
     $this->form_validation->set_rules('phone',  'Phone', 'trim|required|max_length[10]|xss_clean'); 
     $this->form_validation->set_rules('url',  'URL',  'trim|required|max_length[255]|xss_clean'); 
     $this->form_validation->set_rules('tags',  'Tags',  'trim|xss_clean'); 


     // Form validation 
     if ($this->form_validation->run() == FALSE) { 

      // On failure 
      $this->index(); 

     } else { 

      // On success, prepare the data 
      $data = array(
       'name'  => $_POST['name'], 
       'address' => $_POST['address'], 
       'city'  => $_POST['city'], 
       'state'  => $_POST['state'], 
       'zip'  => $_POST['zip'], 
       'phone'  => $_POST['phone'], 
       'url'  => $_POST['url'], 
       'type'  => $_POST['type'], 
       'tags'  => $_POST['tags'], 
       'active' => $_POST['active'], 
      ); 

      // Check if the restaurant already exists 
      $check = $this->mRestaurant->getRestaurant($data['name'], $data['zip']); 

      // If no records were returned add the new restaurant 
      if($check->num_rows() == 0) { 
       $query = $this->mRestaurant->addRestaurant($data); 

       if ($query) { 
        // On success 
        $this->session->set_flashdata('status', '<div class="success">Added New Restaurant!</div>'); 
       } else { 
        // On failure 
        $this->session->set_flashdata('status', '<div class="error">Could not add a new restaurant.</div>');  
       } 

       redirect('restaurant/confirm', 'refresh'); 
      } else { 
       // Notify the user that the restaurant already exists in the database 
       $this->session->set_flashdata('status', '<div class="notice">This restaurant already exists in the database.</div>'); 
       redirect('restaurant/index'); 
      } 

     } 

    } 


    function confirm() { 

     $data['title'] = "Confirm"; 

     $this->load->view('/template/header'); 
     $this->load->view('/restaurant/confirm', $data); 
     $this->load->view('/template/footer'); 
    } 
} 
?> 

risposta

2

cercherò di aiutare con la logica del controllore che io uso sempre:

function index() 
{ 
    //set some default variables 
    $data['error_message'] = ''; 
    //if this is to edit existing value, load it here 
    // from database and assign to $data 
    //... 
    //set form validation rules 
    $validation = array(); 
    $validation['field_name'] = array(
    'field' => 'field_name', 
    'label' => 'Field label', 
    'rules' => 'trim|required' 
); 
    //more rules here 
    //... 
    $this->load->library('form_validation'); 
    $this->form_validation->set_rules($validation); 
    //run validation 
    if ($this->form_validation->run() == FALSE) 
    { 
    $data['error_message'] .= validation_errors(); 
    } 
    else 
    { 
    //do insert/update 
    // 
    //it's better to do redirection after receiving post request 
    //you can use flashdata for success message 
    if ($success) 
    { 
     $this->session_set_flashdata('success_message', MESSAGE_HERE); 
    } 
    redirect(RESULT_PAGE); 
    } 
    //reaching this block can have 2 meaning, direct page access, or not have valid form validation 
    //assign required variables, such as form dropdown option, etc 
    //... 
    //load view 
    $this->load->view(VIEW_FILE, $data); 
} 

Visualizza File:

... 
<?php if ($error_message): ?> 
    <?php echo $error_message; ?> 
<?php endif; ?> 
<?php echo form_open(current_url, array('id' => 'some_form_id')); ?> 
<!-- form field here --> 
<label for="field_name">Field label</label> 
<input name="field_name" value="<?php echo set_value('field_name', $DEFAULT_FIELD_NAME_IF_NEEDED); ?>" /> 
<!-- more form field here --> 
<?php echo form_close(); ?> 
... 

Spero che questo vi aiuterà.

Per lo $DEFAULT_FIELD_NAME_IF_NEEDED nel file di visualizzazione, lo utilizzo per passare il valore predefinito se questa pagina del modulo è per modificare i dati esistenti dal database. È possibile caricare i dati nel controller, quindi passarlo per visualizzare il file e visualizzarlo nel campo modulo.

0

Si potrebbe provare a fare in modo che il modulo di posta venga indicizzato e nel metodo di indice, effettuare la convalida se il modulo è stato inviato. Quindi rendere la vista indice (se ci sono errori) o aggiungere il ristorante e visualizzare la vista di conferma.

+0

ho spostato tutto il codice del metodo add() per indicizzare(), allora ho provato la convalida se la da è stata presentata: if (isset ($ _ POST [ 'aggiungere'])) {~~} Funziona la prima volta che il modulo viene reso; tuttavia, poiché $ _POST ['aggiungi'] è impostato, la prossima volta che l'utente fa clic su aggiungi e le regole di convalida non sono state ancora soddisfatte, il ciclo verrà ripetuto. Mi piacerebbe ancora usare il metodo add() invece di perdere tutto il codice nell'indice. – mazer

+0

Penso che vuoi che si fermi finché le regole di validazione non passano tutte, giusto? E si potrebbe spostare tutta la convalida e l'aggiunta di codice a metodi privati ​​o metodi di libreria e quindi chiamarli dal metodo indice, se desiderato. – Coomer

1

ho avuto un problema simile e ho finito per fare:

La mia forma è quello di creare un nuovo utente, ma si dovrebbe ottenere l'idea.

if($this->form_validation->run() == FALSE) 
     { 
      $this->data['title'] = "Add User"; 
      $this->load->vars($this->data); 
      $this->load->view('head'); 
      $this->load->view('header'); 
      $this->load->view('admin/sidebar'); 
      $this->load->view('admin/add_user'); 
      $this->load->view('footer'); 
     } 

Così, in modo efficace, invece di chiamare la nuova funzione stavo mostrando nuova vista dalla stessa funzione. Non è la soluzione più bella ma funziona. Inoltre si potrebbe desiderare di usare qualcosa di simile per controllare se il ristorante è già esistente:

function _check_username($str) 
{ 
    $this->db->where('username', $str); 
    $query = $this->db->get('sm_users'); 

    if($query->num_rows() == 0) 
    { 
     return TRUE; 
    } 
    else 
    { 
     $this->form_validation->set_message('_check_username', "User '$str' already exists!"); 
     return FALSE; 
    } 
} 

E l'uso funzione di convalida di callback:

$this->form_validation->set_rules('userName','User Name','trim|required|min_length[3]|callback__check_username'); 
+0

Ho avuto lo stesso problema, '$ this-> load-> library ('form_validation');' ha spostato questa riga nel '__constructor' e funziona –

2

------- regolatore ---- ---

 
$data['post'] = $_POST; 
$this->load->view('view/view', $data); 

quindi nella vista

<input type="text" value="><?=$post['username'];?>" name="username">

Problemi correlati