2011-06-16 67 views
0

你好,我剛剛開始CodeIgniter。我在加載視圖時遇到問題。在codeigniter中加載兩次視圖

我的情景是我正在創建一個樣本添加表單。提交後,它將轉到控制器並在數據庫中插入條目。如果數據庫操作成功,我希望它再次來到同一個視圖,並再次顯示一些值。並根據這些值我顯示了一些特定的行通知用戶有關插入操作。我在控制器功能看起來像

public function add_user() 
{ 
    $this->load->view('add_user'); 
    $post=$this->input->post(); 
    if(isset($post['name'])) 
    { 
     $data=array(
     'name'=>$post['name'], 
     'designation'=>$post['designation'] 
     ); 
     if($this->db->insert('user',$data)) 
     $result['update']=true; 
     else 
     $result['update']=false; 
     $this->load->view('add_user',$result); 
    } 

} 

而我的觀點看起來像

<h1 align="center">Add User</h1> 
    <table border="0" cellpadding="2" cellspacing="2" align="center"> 
     <?php 
     if(isset($update)) 
     { 
      if($update) 
      { 
       ?> 
       <tr bgcolor="#00FF00"> 
        <td>Record Added Successfully</td> 
       </tr> 
      <?php 
      } 
      else 
      { 
       ?> 
       <tr bgcolor="#FF0000"> 
        <td>Insertion Operation Failed</td> 
       </tr> 
      <?php 
      } 
     } 
     ?> 
     <?php echo(form_open('first/add_user'));?> 
      <tr> 
       <td>Name</td> 
       <td><input type="text" name="name" /></td> 
      </tr> 
      <tr> 
       <td>Designation</td> 
       <td> 
        <select name="designation"> 
         <option value="Junior PHP Developer">Junior PHP Developer</option> 
         <option value="Senior PHP Developer">Senior PHP Developer</option> 
        </select> 
       </td> 
      </tr> 
      <tr> 
       <td colspan="2" align="center"> 
        <input type="submit" name="submit" value="Add User" /> 
       </td> 
      </tr> 
     </form> 
    </table> 

現在我想要什麼,如果植入術是全成我發送真正的價值來查看,如果不是我送假值。在這個價值的基礎上,我展示了一些行。根據我理解的邏輯,我加載視圖兩次。因爲它第一次加載表單,第二次它加載視圖的某些值爲true或false。但是,重新加載後會發生什麼,有兩種形式。我知道這個問題是由於我的視圖的雙重加載。我想問在數據庫操作後是否有另一種發送值的方式來查看?

回答

2

只需一次加載您的看法:它

public function add_user() 
{ 
    $post=$this->input->post(); 
    $result = array(); 
    if(isset($post['name'])) 
    { 
     $data=array(
     'name'=>$post['name'], 
     'designation'=>$post['designation'] 
    ); 
     if($this->db->insert('user',$data)) 
     $result['update']=true; 
     else 
     $result['update']=false; 
    } 
    $this->load->view('add_user',$result); 
} 

通過你的代碼是有點亂的樣子,工作

+0

我這樣做,但它再次顯示了從數據庫回去後兩種形式操作。 – 2011-06-16 11:12:22

+0

再次檢查您的代碼或將其粘貼 - 如果代碼如上所示,則無法加載兩次 – 2011-06-16 21:49:16

0
// try something like this 
//you may need to use form validation helper 

//load add user form 
public function add_user(){ 
//any data required for the form 
$data['anything'] = ''; 
$this->load->view('add_user',$data); 
} 
//to process adding user action, form action will point to this 
function adding_user(){ 
if($this->input->post('name')){ 
    $data=array(
    'name'=>$post['name'], 
    'designation'=>$post['designation']; 
    if($this->db->insert('user',$data)){ 
    echo 'user added successfully!'; 
    }else{ 
    redirect(user/add_user); 
    } 
); 

} 
}