sahar
sahar

Reputation: 115

pass parameter from url to cakephp

I need to send parameter from URL to cakephp controller. I have message table with two parameter 'ufrom' and 'uto'. in controller i want to save this values in message table.

I put in the URL:

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

in MessagesController i have function:

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);
}

}

and in add.ctp i have:

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

but when i use the above URL i see:

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

and Nothing is stored in the database. I'm new in cakephp. please help.

Upvotes: 0

Views: 14285

Answers (2)

KevinCoder
KevinCoder

Reputation: 221

The easiest way to pass parameters to the controller action would be to simply pass them through the action as arguments like so:

  public function add($ufrom,$uto)

Your URL should look like:

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

Secondarily if the data is coming from the URL you wouldn't use this->request->data , simply :

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

Upvotes: 0

liyakat
liyakat

Reputation: 11853

here i can suggest you to use params like below

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

but if you need to use like this way

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

you can get the value like below

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

in your case would be like

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

Upvotes: 6

Related Questions