2013-08-17 76 views
0

我需要從URL向cakephp控制器發送參數。我有兩個參數'ufrom'和'uto'的消息表。在控制器中,我想將這些值保存在消息表中。從url傳遞參數到cakephp

我把網址:

http://localhost/ar/messages/add?ufrom=9&uto=3 
在MessagesController

我有功能:

public function add() { 

if(($this->request->query['uto'])and($this->request->query['ufrom'])){ 
     $this->Message->create(); 
     if ($this->Message->save($this->request->data)) { 
      $this->set('addMessage',TRUE); 
      $this->set('ufrom',$this->request->query['ufrom']); 
      $this->set('uto',$this->request->query['uto']); 
      $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The message could not be saved. Please, try again.')); 
     } 

     $targets = $this->Message->Target->find('list'); 
     $this->set(compact('targets')); 
} 
else{ 
    $this->set('error',true); 
} 

}

和add.ctp我有:

<?php 
if(isset($error)){ 
    echo('error'); 
} 
else{ 
    echo json_encode($ufrom); 
    echo json_encode($uto); 
    echo json_encode($addMessage); 
} 
?> 

但是當我使用上面的URL我看到:

Notice (8): Undefined variable: ufrom [APP\View\Messages\add.ctp, line 6]null 
Notice (8): Undefined variable: uto [APP\View\Messages\add.ctp, line 7]null 
Notice (8): Undefined variable: addMessage [APP\View\Messages\add.ctp, line 8]null 

並且Nothing存儲在數據庫中。我是cakephp新手。請幫忙。

回答

5

在這裏,我可以建議你使用PARAMS像下面

http://www.example.com/tester/retrieve_test/good/1/accepted/active 

,但如果你需要使用像這樣

http://www.example.com/tester/retrieve_test?status=200&id=1yOhjvRQBgY 

你可以像值低於

echo $this->params['url']['id']; 
echo $this->params['url']['status']; 

在你的情況下會像

echo $this->params['url']['uto']; 
echo $this->params['url']['ufrom']; 
+0

感謝您的支持描述但我的數據尚未存儲在數據庫中。 – sahar

+0

http://stackoverflow.com/questions/9394080/cakephp-2-0-cannot-save請參考這個 – liyakat

+0

非常感謝。我的問題解決了。 – sahar

0

參數傳遞給控制器​​的動作是簡單地通過操作作爲參數,像這樣通過他們最簡單的方法:

public function add($ufrom,$uto) 

您的網址應該是這樣的:

http://localhost/ar/messages/add/9/3 

其次如果數據來自URL,則不會使用此請求 - >數據,只需:

$message = array("Message"=>array("ufrom"=>$ufrom,"uto"=>$uto)); 
$this->Message->save($message);