我需要将参数从URL发送到cakephp控制器。我有两个参数'ufrom'和'uto'的消息表。在控制器中我想将此值保存在消息表中。
我输入了网址:
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);
}
?>
但是当我使用上述网址时,我会看到:
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的新手。请帮忙。
答案 0 :(得分:5)
在这里我可以建议你使用下面的参数
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'];
答案 1 :(得分:0)
将参数传递给控制器操作的最简单方法是简单地将它们作为参数传递给操作,如下所示:
public function add($ufrom,$uto)
您的网址应如下所示:
http://localhost/ar/messages/add/9/3
其次,如果数据来自网址,则不会使用此 - &gt; request-&gt;数据,只需:
$message = array("Message"=>array("ufrom"=>$ufrom,"uto"=>$uto));
$this->Message->save($message);