pass parameter from url to cakephp - 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.

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'];

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

Related

db query in codeigniter active record returing object

I'm trying to pull a column out of the database, simple enough right? I'm using codeigniter's active record.
My Model Function
public function getcolumn($field, $table, $kfield, $key)
{
$this->db->select($field);
$this->db->from($table);
$this->db->where($kfield, $key);
$query = $this->db->get();
$results = $query->result();
return $results;
}
My Controller has:
public function users()
{
$body['handle'] = $this->admin->getcolumn('handle', 'users', 'userid', $userid)
$this->load->view('template/header');
$this->load->view('admin/users', $body);
$this->load->view('template/footer');
}
now when I print_r that variable in my view I get "Array ( [0] => stdClass Object ( [handle] => Zanigade ) ) "
Since I'm trying to use this function as a global "grab and go" function without writing a ton of functions, why won't it just return the name? What am I doing wrong? I've been playing with the output for 3 hours and I know this is a stupid easy fix and I'm just missing the mark.
Any help will be appreciated.
Put it all together using the "chaining" capability like so
$results = this->db->get()->row()->$field;
We get() one row() which (should) contain a field named $field.
It seems you are returning the result instead of single row, try this
public function getcolumn($field, $table, $kfield, $key)
{
$this->db->select($field);
$this->db->from($table);
$this->db->where($kfield, $key);
$query = $this->db->get();
return $query->row()->$field;
}
For More Information, Check the codeigniter user guide
https://www.codeigniter.com/userguide3/database/examples.html

Cakephp 1.2 this->set not working

So I am setting a variable to be used in view.
This happens during a form POST. Maybe this can give some hints to someone.
public function confirm_card(){
if(!isset ($this->data['UserPayment']) && empty($this->data['UserPayment'])){
$this->Session->setFlash(__d('payments', 'Select payment method', true), 'flash_error');
$this->redirect($this->referer());
}
else{
foreach($this->data['UserPayment'] as $key=>$up){
if(!empty($up)){
$this->set(array('paytype'=>$key));
return;
}
}
}
}
And in view
echo $paytype;
Result in view
Notice (8): Undefined variable: paytype
The key is returned as it should be so no empty values there.
This should be very basic... I am missing something here?
Try with
$this->set('paytype', $key);
Change
$this->redirect($this->referer());
The problem was !empty($up) vs $up != '' ?
$up is normally 0 or 1 ?

Drupal 7, insert user_profile_form into a page

I tried to insert user_profile_form into a page. the code is rather simple:
global $user;
module_load_include('inc', 'user', 'user.pages');
print drupal_render(drupal_get_form('user_profile_form', $user, 'account'));
everything works fine except when uploading images, it shows:
"Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'user_profile_form' was given in drupal_retrieve_form()"
Any ideas, thx a lot
you need to use form_load_include() instead of module_load_include to load/build a form, and you have to pass arguments inside $form_state.
the code you are looking for looks like:
$form_id = 'user_profile_form';
$form_state = array();
//passing arguments to form.
$form_state['build_info']['args'] = array($account, 'account');
form_load_include($form_state, 'inc', 'user', 'user.pages');
$form = drupal_build_form($form_id, $form_state);
To prevent the notice or warning:
Trying to get property of non-object in user_account_form() (line 1019 of /var/www/modules/user/user.module)
Change the last two lines to:
<?php
$output_form = drupal_get_form($form_id);
print render($output_form);
?>

CakePHP, GET Parameters and routing

I am fairly new to cakephp but I have a question relating to urls and parameters. I would like to be able to have a url that looks like a standard url e.g:
http://www.mysite.com/controller/myaction?arg=value&arg2=val
I would like that url to map to an action in my controller as follows:
function myaction($arg = null, $arg2 = null)
{
// do work
}
I realize that cakephp has routing as described here, however, honestly this seems over engineered and results in a url string that is nonstandard.
In my current situation the url is being generated and invoked by an external (billing) system that knows nothing about cake and doesn't support the cake url format.
You can have your URL in any form. It's just CakePHP allows you to retrieve the variable passed through GET from the variable $this->params['url']
function myaction()
{
if(isset($this->params['url']['arg']))
$arg = $this->params['url']['arg'];
if(isset($this->params['url']['arg2']))
$arg2 = $this->params['url']['arg2'];
}
Solution in AppController for CakePHP 2.x
class AppController extends Controller {
....
/***
* Recupera los Named envias por URL
* si es null $key emtraga el array completo de named
*
* #param String $key
*
* #return mixed
*/
protected function getNamed($key=null){
// Is null..?
if(is_string($key)==true){
// get key in array
return Hash::get($this->request->param('named'), $key);
}else{
// all key in array
return $this->request->param('named');
}
}
...
}
I have a similar problem. Not because I have an external system, but because I don't like to put all parameters into the URL-path. In my example, I have some search queries that are assembled and passed to the controller. IMHO, these queries should be GET parameters and not part of the URL-path.
One advantage of using GET parameters is that the order of the given parameters is not important, in contrast to passing params via the URL path.
To solve this problem in a generic way, I'm replacing all method arguments with the value of the GET-param, if one with the same name is given:
class MyController extends AppController
{
function test($var1 = null, $var2 = "content2")
{
foreach (get_defined_vars() as $key => $value) {
if (isset($this->params['url'][$key])) {
$getvalue = $this->params['url'][$key];
$$key = $getvalue;
CakeLog::write("debug", "Setting:$key to $getvalue");
}
}
CakeLog::write("debug", print_r(get_defined_vars(), true));
}
}
Now I can access this controller method and pass parameters via GET like this:
http://myapp/mycontroller/test?var1=foo&var2=bar

Cakephp using two models

In my CakePHP forms_controller I have:
var $uses=array('Form','Field');
// ...
$this->set('retrived',$this->Field->find("all",array('conditions'=>array('Field.formname'=>$formname,))));
and in the view:
<?php foreach ($retrived as $r): ?>
<?php echo $r['Field']['fieldname']; ?><br>
<?php endforeach; ?>
I'm not getting the answer for it
Actually my table fields wil be like:
fieldname
formname
type
value
More details from my forms_controller:
function views()
{
if (!empty($this->params['form']))
{
$this->set('fieldctr',$this->params['form']['formfieldctr']);
$fieldctr=$this->params['form']['formfieldctr'];
if(!empty($this->params['form']['formnameelements']))
{
$this->set('formname',$this->params['form']['formnameelements']);//formname
$this->Form->saveField('name',$this->params['form']['formnameelements']);
}
else
{
$this->set('formname','MyForm');//formname
$this->Form->saveField('name','MyForm');
}
$this->Form->saveField('body',$this->params['form']['formelements']);//inserts into database
$ret = $this->Form->query("Select id from forms order by id DESC LIMIT 1");
$newid=$ret[0]['forms']['id'];echo $newid;
$upd=$this->Form->query("update forms set ctr=$fieldctr where id= $newid");
$formname=$this->params['form']['formnameelements'];
$n="$formname";
$array = $this->params['form']['formfieldnameelements'];
$comma_separated = explode(",", $array);
for($i=0;$i<$fieldctr;$i++)
{
echo $comma_separated[$i];
echo " ";
$n="$comma_separated[$i]";
//insert the fields of each form to the table fields
$this->data['Field']['fieldname'] = $comma_separated[$i];
$this->data['Field']['formname'] = $formname;
$this->Field->saveAll($this->data);
}
The above method is where I'm inserting the formname in my forms table.
And inserting that formname with their fieldsname in the fields table:
function formupdate()
{
$this->set('fieldctr',$this->params['form']['formfieldctr']);
$fieldctr=$this->params['form']['formfieldctr'];
$this->set('formname',$this->params['form']['formnameelements']);//formname
$formname=$this->params['form']['formnameelements'];
$ret = $this->Field->query("SELECT fieldname FROM fields WHERE fields.formname = "."'$formname'"."order by id ASC");
for($q=0;$q<$fieldctr;$q++)
{
$fieldname[$q]=$ret[$q]['fields']['fieldname'];
}
$this->set('retrived',$this->Field->find("all",array('conditions'=>array('Field.formname'=>$formname))));
$array = $this->params['form']['formfieldvalueelements'];
$comma_separated = explode(",", $array);
for($i=0;$i<$fieldctr;$i++)
{
echo $comma_separated[$i];
echo " ";
$n="$comma_separated[$i]";
echo $fieldname[$i];
$this->Field->updateAll(array('Field.value' => "'$comma_separated[$i]'"),array('Field.fieldname' => $fieldname[$i],'Field.formname'=>$formname));
}
$this->set('retrived',$this->Field->find("all",array('conditions'=>array('Field.formname'=>$formname,))));
} // end of function formupdate
In the above formupdate method I'm inserting the values of the corresponding values of that fields in the fields table... All the values are inserted correctly - but in my formupdate.ctp view:
Nothing is displayed in my view... eventhough the content is there in the table..
Please resolve my problem
By the names of your models, I think it's safe to conclude that you're trying to ouput some HTML. Since the question isn't really complete (where is the code?), we can't tell what's wrong with it.
A wild guess would be that something is being stripped there or ignored by your browser.
Aruna,
Please post the code you're using! It's possible that the error is something small, but without knowing what you're doing, it's impossible to help more than dr. Lecter did.
When you say that the fields table is updated correctly, do you mean that you can safely invoke the Model::save() method? Are you then calling Model::read() or Model::find() in the controller, then using the returned values from that to set a variable that can be accessed in the view?

Resources