I am trying to pass a variable from a view (of mobile model) to a different controller (of inventory model), using the chtml:button with this code
echo CHtml::button(
'Sell It',
array('submit' => array('inventory/create', array('id'=>$data->id)))
);
Now how do I access the $id variable in the Inventory controller, so that I can prepopulate the create view with details corresponding to the passed 'id' variable of the mobile model.
In your inventory/create controller action do checking before getting the id like this :-
if (isset($_REQUEST['id'])) {
$id = $_REQUEST['id'];
$this->render('create',array('model'=>$inventory, 'id'=>$id));
}
else{
$this->render('create',array('model'=>$inventory);
}
If you are trying to come up an update/edit form with the values prefilled based on the Id passed then you should have to go through the CRUD options available within YII.. This is much better way to handle record updation and its easy too . See this topic for furhter info..
http://www.yiiframework.com/doc/guide/1.1/en/quickstart.first-app
In your inventory/create controller action do a test for $_GET['id'] something like:
$id = (#$_GET['id']) ? : DEFAULT_VALUE;
$this->render('create',array('model'=>$inventory, 'id'=>$id));
and then you pass the data through to the view by passing an array of variables you want to make available.
(you would want to filter the input better, this is just a sample -- using filter_input or some other method and define a default value and/or some test for it being null/invalid)
in your controller you can get the variable by giving an argument to your controller method like this:
public function actionCreate($id){
$id = isset($id)?$id:NULL; // Or whatever, you can access it like this.
}
You don't have to use $_GET, and yii has already done some security checks on the value.
Related
In my controller i used this way. i want to pass a variable data to my index function of the controller through redirect
$in=1;
redirect(base_url()."home/index/".$in);
and my index function is
function index($in)
{
if($in==1)
{
}
}
But I'm getting some errors like undefined variables.
How can i solve this?
Use session to pass data while redirecting. There are a special method in CodeIgniter to do it called "set_flashdata"
$this->session->set_flashdata('in',1);
redirect("home/index");
Now you may get in at index controller like
function index()
{
$in = $this->session->flashdata('in');
if($in==1)
{
}
}
Remember this data will available only for redirect and lost on next page request. If you need stable data then you can use URL with parameter & GET $this->input->get('param1')
So in the controller you can have in one function :
$in=1;
redirect(base_url()."home/index/".$in);
And in the target function you can access the $in value like this :
$in = $this->uri->segment(3);
if(!is_numeric($in))
{
redirect();
}else{
if($in == 1){
}
}
I put segment(3) because on your example $in is after 2 dashes. But if you have for example this link structure : www.mydomain.com/subdomain/home/index/$in you'll have to use segment(4).
Hope that helps.
Use session to pass data while redirecting.There are two steps
Step 1 (Post Function):
$id = $_POST['id'];
$this->session->set_flashdata('data_name', $id);
redirect('login/form', 'refresh');
Step2 (Redirect Function):
$id_value = $this->session->flashdata('data_name');
If you want to complicate things, here's how:
On your routes.php file under application/config/routes.php, insert the code:
$route['home/index/(:any)'] = 'My_Controller/index/$1';
Then on your controller [My_Controller], do:
function index($in){
if($in==1)
{
...
}
}
Finally, pass any value with redirect:
$in=1;
redirect(base_url()."home/index/".$in);
Keep up the good work!
I appreciate that this is Codeigniter 3 question, but now in 2021 we have Codeigniter 4 and so I hope this will help anyone wondering the same.
CI4 has a new redirect function (which works differently to CI3 and so is not a like for like re-use) but actually comes with the withInput() function which does exactly what is needed.
So to redirect to any URL (non named-routed) you would use:
return redirect()->to($to)->withInput();
In your controller - I emphasise because it cannot be called from libraries or other places.
In the function where you are expecting old data you can helpfully use the new old() function. So if you had a key in your original post of FooBar then you could call old('FooBar'). old() is useful because it also escapes data by default.
If however, like me, you want to see the whole post then old() isn't helpful as the key is required. In that instance (and a bit of a cheat) you can do this instead:
print'<pre>';print_r($_SESSION['_ci_old_input']['post']);print'</pre>';
CI4 uses the same flash data methods behind the scenes that were given in the above answers and so we can just pull out the relevant session data.
To then escape the data simply wrap it in the new esc() function.
More info would be very helpful, as this should be working.
Things you can check:
Is your controller named home.php? Going to redirect(base_url()."home"); shows your home page?
Make your index function public.
public function index($in) {
....
}
In a joomla custom made component there are multiple posts on a page, and every post contains multiple comment, so in view i want to call comments by post id. please suggest a good method to make it working.
You have two options. The first, is to attach the comment id as a URL paramater and retrieve it within the model as needed like so:
$comment_id = JRequest::getApplication()->input->get('comment_id');
If you wish to pass in a parameter when calling the model from the view class, you need to get an instance of the MVC path model instead of using the short cut method. So, instead of using this in the JView class:
$this->items = $this->get('Items');
You would do this instead:
$model = $this->getModel();
$this->items = $model->getItems($comment_id);
Hope this helps.
I'm looking to send the user to another page via a controller method. The other page expects POST data.
Normally, the page is accessed with a postLink(). Is there a way to use this in the controller, perhaps with redirect()?
A little bit old but still no answer accepted so...
The answer is no, and yes.
No, there is no direct method since you cannot pass POSTed data using redirect() function.
You could use requestAction(), since you can pass data as posted (see requestAction() here for version cakePHP>=2.0).
In that case you pass an url and then an array having the key data with the posted data, something like
$this->requestAction($url, array('data' =>$this->data));or if you prefer$this->requestAction($url, array('data' =>$this->request->data));
The problem with requestAction() is that the result is environmentally as if you were generating the page of the requested action in the current controller, not in the target, resulting in not very satisfactory effects (at least not usually for me with components behaving not very nicely), so still, no.
...but Yes, you can do something very similar using the Session component.
This is how I usually do it. The flow would be something like this:
View A=>through postLink() to Action in A controller=>=>A controller request->data to Session variable=>=>action in B controller through redirect()=>=>set B controller request->data from Session variable=>=>process data in B controller action=> View B
So, in your A controller, let's say in the sentToNewPage() action you would have something like
//Action in A controller
public function sentToNewPage()
{
$this->Session->write('previousPageInfo', $this->request->data);
$url = array('plugin' => 'your_plugin', 'controller'=>'B',
'action'=>'processFromPreviousPage');
$this->redirect($url);
}
and in B controller:
//Action in B controller
public function beforeFilter()
{//not completelly necessary but handy. You can recover directly the data
//from session in the action
if($this->Session->check('previousPageInfo'))
{$this->data = $this->Session->read('previousPageInfo')};
parent::beforeFilter();
}
public function processFromPreviousPage()
{
//do what ever you want to do. Data will be in $this->data or
// if you like it better in $this->request->data
$this->processUserData($this->request->data);
//...
}
Best solution would be use javascript to redirect.
But if you want more cake I give you some tools
CakeAPI: requestAction - it allow to execute controller method of desire with parameters, if you pass 'return', it will return full view output for that action.
//very useful in views
$result = $this->requestAction('Controller/method',
array('return','user_id'=>$userId)
);
parameter will be accessible in controller via request param
$this->request->params['user_id']
Long and short is that it's not easy to emulate an HTML form with POST data and a redirect, you kind of need to set a bunch of hidden variables containing the data and automatically post the form to your destination via Javascript.
What I would do is take the processing functionality out of the function that requires POST variables, and make it generic so that you can call it from both of your functions.
Consider this rough example:
public function myPostDataAction() {
$name = $_POST['name'];
$age = $_POST['age'];
// do stuff
echo $name . ', ' . $age;
}
Let's say that is the action you are trying to post data to in this scenario, but you can't because you can't emulate those $_POST variables over a redirect without the scenario mentioned at the top here. You can do this:
public function myPostDataAction() {
$name = $_POST['name'];
$age = $_POST['age'];
// call common function
echo $this->getMyResults($name, $age);
}
// accessible from inside the controller only
private function getMyResults($name, $age) {
return $name . ', ' . $age;
}
Now you can also use that getMyResults() functionality by passing regular old variables into it:
public function myProblemFunction() {
$name = 'John';
$age = 15;
echo $this->getMyResults($name, $age);
}
Now, obviously you won't be outputting anything like that straight from the controller action, you'll be setting it to your views etc, but that's an example of how you can centralize functionality to be used in multiple locations.
For the disclaimer, this kind of thing is exactly what models are for, and you should definitely consider putting this kind of function into a model instead of a controller - it depends on your specific application.
With cakephp 2.x Use this:
$this->autoRender = false;
$request = new CakeRequest(Router::url(array('controller' => 'mycontroller','action' => 'my_action')));
$request->data('dataIndex','value');
$response = new CakeResponse();
$d = new Dispatcher();
$d->dispatch(
$request,
$response
);
but it will not redirect but dispatch to a different controller/action so if you went on /controller/oldaction it will stays the current url (no HTTP redirection is done).
You could still change the url with javascript
see: Change the URL in the browser without loading the new page using JavaScript
I am quite new to CodeIgniter. In my application I have page where user enters his details. I want to get that detail in a variable (Lets say just Name ) and want to use that variable in one of the controller file.
How to do that ?
for a form value called "supername"
to use locally inside a method
$supername = $this->input->post( 'supername', TRUE ) ;
to use in any method in the class use $this->
$this->supername = $this->input->post( 'supername', TRUE ) ;
In your controller
$name= $this->input->post('name');
Better start off with some tutorials on Codeigniter.
From http://ellislab.com/codeigniter/user-guide/libraries/input.html :
$post = $this->input->post();
//on the controller you can access this and will return the array
//of the post data you submitted
You can also get them by variable name like:
$somedata = $this->input->post('some_data');
Make sure your form action is pointing to your controller as well. :)
CodeIgniter has this Input class wherein simplifies the inputs when they are used in some conditional statements.
To answer your question, on how to fetch the data entered by the user is by:
$name = $this->input->post('name');
Stores the value of name (it is the name of your field in the form) to a variable name $name.
Do you want to know if the field is empty or not?
try:
if($name = $this->input->post('name')){
//$name has the value of the name field and it is not empty, do something.
}else{
//$name has the value of the name field and it is empty, do something.
}
CodeIgniter Input class also has XSS Filtering capabilities, it filters input automatically to prevent cross-site scripting attacks.
All you have to do is:
Set it to TRUE in your config/config.php
$config['global_xss_filtering'] = TRUE;
I have just started learning Code Igniter .
I want to know how can I pass a variable from one controller(first_cont.php) to other controller (second_cont.php) ?
Any help would be appreciated .
Thanks in Advance :)
It will depend on the circumstances. If you want to retain the data for some time, then session data would be the way to go. However, if you only need to use it once, flash data might be more appropriate.
First step would be to initialise the session library:
$this->load->library('session');
Then store the information in flash data:
$this->session->set_flashdata('item', $myVar);
Finally, in the second controller, fetch the data:
$myVar = $this->session->flashdata('item');
Obviously this would mean you'd have to either initialise the session library again from the second controller, or create your own base controller that loads the session library and have both of your controllers inherit from that one.
I think in codeigniter you can't pass variable, between two different controller. One obvious mechanism is to use session data.
Ok, here is something about MVC most will readily quote:
A Controller is for taking input, a model is for your logic, and, a view is for displaying.
Now, strictly speaking you shouldn't want to send data from a controller to another. I can't think of any cases where that is required.
But, if it is absolutely needed, then you could simply use redirect to just redirect to the other controller.
Something like:
// some first_cont.php code here
redirect('/second_cont/valuereciever/value1')
// some second_cont.php code here
public function valureciever($value){
echo $value; // will output value1
}
In Codeigniter there are many way to pass the value from one controller to other.
You can use codeigniter Session to pass the data from one controller to another controller.
For that you have to first include the library for session
$this->load->library('session');
Then You can set the flash data value using variable name.
// Set flash data
$this->session->set_flashdata('variable_name', 'Value');
Them you can get the value where you want by using the codeigniter session flashdata
// Get flash data
$this->session->flashdata('variable_name');
Second Option codeigniter allow you to redirect the url from controll with controller name, method name and value and then you can get the value in another controller.
// Passing the value
redirect('/another_controller_name/method_name/variable');
Then you can get the value in another controller
public function method_name($variable)
{
echo $variable;
}
That all....
If you are using session in the first controller then dont unset that session in first controller, instead store the value which you want in the other controller like,
$sess_array = array('value_name1' => 'value1', 'value_name2' => 'value2');
$this->session->set_userdata('session_name', $sess_array);
then reload this session in the other controller as
$session_data= $this->session->userdata('session_name');
$any_var_name = $session_data['value1'];
$any_var_name = $session_data['value2'];
this is how you can pass values from one controller to another....
Stick to sessions where you can. But there's an alternative (for Codeigniter3) that I do not highly recommend. You can also pass the data through the url. You use the url helper and the url segment method in the receiving controller.
sending controller method
redirect("controller2/method/datastring", 'refresh');
receiving controller method
$this->load->helper('url');
$data = $this->uri->segment(3);
This should work for the default url structure. For a url: website.com/controller/method/data
To get controller $this->uri->segment(1)
To get method $this->uri->segment(2)
The limitation of this technique is you can only send strings that are allowed in the url so you cannot use special characters (eg. %#$)