Yii can't access session variables - php

My problem: I can't access session data in the view, which I tried to save in the controller before rendering the view.
In my opinion there's an error when storing the session data. (It's necessary for me to modify the session data after creating it, not only in the single action.)
ProcessController.php
public function actionNew() {
$formhash = md5(time());
$hashList = array();
$hashList[$formhash]['processingNumber'] = '';
//fill with empty model
$hashList[$formhash]['model'] = $this->loadModel();
//store hashList in session
Yii::app()->session['hashList'] = $hashList;
$this->render('/process', array('hashValue => $formHash));
}
Now in the view I need the data from the session to show them to the user. But when dumping the hashList it just dumps "null" (Maybe because the saving in the controller didn't went well).
process.php
<?php
$form = this->beginWidget('CActiveForm', array(
'id' => 'process_form',
//several other things...
));
//Output: null
CVarDumper::dump(Yii::app()->session['hashList'],10,true);
?>
I tried to use $_SESSION instead of Yii::app()->session, which gives me access to the data in the view. But when handling other actions in the Controller the $_SESSION variable is undefined.
Any suggestions?
Thank you.

Long answer is:
Regarding to this documents:
$session=new CHttpSession;
$session->open();
$value1=$session['name1']; // get session variable 'name1'
$value2=$session['name2']; // get session variable 'name2'
foreach($session as $name=>$value) // traverse all session variables
$session['name3']=$value3; // set session variable 'name3'
You can use as well:
Yii::app()->session->set('hashList', $hashList);
Yii::app()->session->get('hashList');
And set it again.
Beside this session thing, why do not you use this:
$this->render('/process', array('hashValue => $formHash, 'hashList' => $hashList));
So you do not need to save it in a session if you can reach it directly into the view.

According to the documentation your code should work. An alternative might be to use the following, but it does the same:
Yii::app()->session->add('hashList', $hashList); // set the value
$hashList = Yii::app()->session->get('hashList'); // get the value
I expect the problem either a debugging problem, meaning you have observed cached or otherwise outdated data or a problem in parts of your code that you have not shown.

Related

maintain form data after a post

I'm doing a function that receives some form data and an Excel file which I walk and earned some data to store them in my database. So far so good, the point is that after you post, validate the Excel (good or bad this is independent of what I need) the form data is clear and I would like to keep them selected. The point is that all my code to complete all validations that I have run the following:
return $this->redirect(array('admin' => true, 'controller'=>'test', 'action'=>'test'));
I'm starting with cake and I think this may be the problem, also if I remove this code, then the data is loaded, the screen goes blank without displaying any error. It is possible, with this code, to keep the form data as they were?
You would need to store the data in the session, and then read it:
$session = $this->request->session();
$session->write('form-data', $this->request->data());
return $this->redirect(array('admin' => true, 'controller'=>'test', 'action'=>'test'));
And then in your controller:
if ($this->request->is('post')) {
$post_data = $this->request->data();
} else {
$session = $this->request->session();
$post_data = $session->consume('form-data');
}
//do stuff with $post_data

CodeIgniter adding session variable to an already defined "named session"

I already created as session named "verified" as shown below (in my login controller):
foreach($result as $row)
{
$sess_array = array(
'id' => $row->memberid, //Session field: id.
'username' => $row->member_userunique //Session field: username.
);
// Create a session with a name verified, with the content from the array above.
$this->session->set_userdata('verified', $sess_array);
}
Now, when a user open a page called book (with a controller named book) i want to add one more additional variable called "book_id" to my "verified" session.
This is what i have done
function index()
{
//Add a new varible called book_id
$this->session->set_userdata('book_id', $titleID);
}
When i tried to retrieve the 'book_id' using the following method:
$session_data = $this->session->userdata('verified');
$article_id = $session_data['book_id'];
$user_id = $session_data['id'];
It only able to retrieve the 'id' however the 'book_id' is not defined. But if do a var_dump() on $this->session->all_userdata() i can see that the 'book_id' session variable has been successfully appended.
After reading the CI documentation about session, i realized that the code above will not work as i have not tell it to which session should i add the variable to.
Can anyone point me to the right direction?
You do as follows in your index() method:
$session_data = $this->session->userdata('verified');
$session_data['book_id'] = "something";
$this->session->set_userdata("verified", $session_data);
This way you retrieve the contents of the variable (i.e. the array that you persisted earlier), you add another key to the array (book_id), and then store it again. Now you will be able to do, as I assume you want to:
$sess = $this->session->userdata("verified");
echo $sess['book_id'];

Codeigniter: Accessing a array in view

I am completely new in the codigniter i just started day befire Yesterday i am having a problem
Here is my snippet of my controller code
$allcalldetails_array = array(
'id' => $row->id,
'customer_id' => $row->customer_id
);
$this->session->set_userdata('logged',$allcalldetails_array);
I want to iterate the $allcalldetails_array in my views please tell me the way to do this
i tried iterating logged but could not get anything .
If i am printing the array in my views like print_r($allcalldetails_array); but this is also disappointing me .Please help me to get back on track .
Thanks
Its not necessary for session variables to be parsed via controller, access it on view directly:
$logged = $this->session->userdata('logged');
print_r($logged);
If you would like data to be send to your view as variables, you should add the corresponding data to your view load.
Controller:
$logged = $this->session->userdata('logged');
$this->load->view('viewfile', $logged);
View
print "logged id:".$id;
best regards.
Jonas
To get the data from session your need to do the following:
// controller logic
$logged = $data['logged_for_view'] = $this->session->userdata('logged'); // since 'logged' is the name you set it to
// more controller logic
$this->load->view('view_name', $data);
// in view
var_dump($logged_for_view); // this is the key of the $data variable you assigned for the view
Regarding the CodeIgniter's documentation :
Data is passed from the controller to the view by way of an array or
an object in the second parameter of the view loading function.
Then you could use something like :
// Controller side
$data['allcalldetails_array'] = array(
'id' => $row->id,
'customer_id' => $row->customer_id
);
$this->load->view('your_view', $data);
// View side
print_r($allcalldetails_array);
// Loop through your array
foreach ($allcalldetails_array as $detail){
// Do something with your $detail.
}

Zend View array variable inside a partialLoop

Here is the code in my controller:
$this->view->myArray = array();
$this->view->test = "";
$out = $this->view->partialLoop('tab/partial.phtml', $data);
echo $this->view->test; // Output: This works
echo count($this->view->myArray); // Output: 0
And the partial partial.phtml:
$v->test = $this->partialLoop()->view;
$v = "This works";
echo $v->test; // Output: This works
$v->myArray[] = "hello";
echo count($v->myArray); // Output: 0
I don't think that accessing view variables from a partialLoop is a wonderful idea. That aside, why doesn't it work for my array variable?
it doesn't work because you don't have access to the view variables in the partial. You have access to the data you pass to the partial.
$out = $this->view->partialLoop('tab/partial.phtml', $data);
This line of code would have access to the information contained in $data.
So this code in your current partial is basically meaningless:
$v = $this->partialLoop()->view; //you choose to assign view data to the partial, and I don't think it's working as expected.
//By not passing any args to the partial you have at least some access to the view object.
$this->view->test = "This works";//assign data to view locally
echo $v->test; // you seem to be echoing out locally assigned data
$v->myArray[] = "hello";//you didn't assign this to the view
echo count($v->myArray); // myArray probably doesn't exist in this context or dosen't work as expected. If you make this an associative array it might work.
I don't think I've ever seen partials used in quite this manner before. The point of the partial is to establish a different variable scope for a specific portion of the view.
The partial and partialLoop are view helpers so the only action you need to take in your controller (data may be or come from a model as well) is to make available any data you want to use in your partials as well as any data you want available in your normal view scope.
//in a controller
public function userAction() {
$model = Application_Model_DbTable_User();//Table columns = id, name, role
$this->view->partailData = $model->fetchAll();//assign data to view that we want to use in partial, should be an array or object.
}
//in a view script
<?php
//pass the path to the partial as the first arg and the data to be displayed as the second arg
echo $this->partialLoop('/path/to/partial.phtml', $this->partialData);
//we could pass data explicitly as well
echo $this->partial('/path/to/partial.phtml', array('id'=>1,'name'=>'jason','role'=>'user'));
?>
//now for our partial.phtml
//this could be used a simple partial or as a partialLoop
<p>My name is <?php echo $this->name ?>.</p>
<p>My data file id is <?php echo $this->id ?>.</p>
<p>My access control role is <?php echo $this->role ?>. </p>
<!-- name, id and role would be column names that we retrieved from the database and assigned to the view -->
To use a partial or partialLoop you need to pass an array of some type or an object that implements toArray().
[EDIT]
Clean up your code your still in left field.
//controller code
$this->view->myArray = array();
//view code
<?php $v = $this->partial()->view ?>
<?php $v->myArray[] = 'newName' ?>
<?php Zend_Debug::dump(count($this->partial()->view->myArray)) ?>
//my output =
int(1)
I don't seem to be able to pass the view any further then this, if I assign to an actual partial script and attempt to output the view object errors are thrown:
//my view again
<?php echo $this->partial('partial.phtml', $this->partial()->view) ?>
//This and attempts similar result in the error
/*Catchable fatal error: Object of class Zend_View could not be converted to string in E:\www\home-local\application\views\scripts\partial.phtml on line 1*/
//when the partial.phtml looks like
<?php echo $this />
//however when I access the data available in the view
<?php echo $this->myArray[0] ?>
//the result works and the output is
newName
it looks like an empty partial() (partialLoop()) call will give you access to the view object, when you already have access to the view object. If you leave the scope of the view object you will have only the access available to your current scope as provided by __get() and __call().
I hope I was able to explain this enough to help.
maybe you cant set the value of $v or the item because its private or static or discarded
also from the code you posted its using recursion which could make it a lot more breakable (ie the controller is referencing the views data, and the view is setting it or hasnt set it or has set it twice)
agreed i dont think accessing view var's from a partialLoop is a good idea.
edit:
$this->view->assign('variablename', $my_array);
I think the variable is otherwise "lost" on the Rerender, so work on your variables in your controller, and before you are done assign them to the view. I wouldn't really do array operations on $this->view->myArray

passing parameters securely in Zend

I am in service controller, login action (/service/login) and I want to pass the name,email and company to profile controller, register action(/profile/register).
Currently I am doing this way
$this->_redirect('/profile/register/?name='.$name.'&emailid='.$email.'&companyid='.$company);
But I want to pass this info to /profile/register in a way such that the user can't see these in the url.
I tried with $this->_forward like this
$params = array(
name=>$name,
emailid=>$email,
companyid=>$company
);
$this->_forward('register','profile',null,$params);
But this isn't working. Is there any other way I can do this?
To pass parameters securely, you should store the data in a session, or if you cannot use sessions, then in the database.
You could use Zend_Session to store the data temporarily until the next page view where you can retrieve it and it will be deleted (or you can let it persist).
$s = new Zend_Session_Namespace('registrationData');
$s->setExpirationHops(1); // expire the namespace after 1 page view
$s->name = $name;
$s->email = $email;
$s->companyId = $company;
// ...
return $this->_redirect('/profile/register);
And then in profile/register:
$s = new Zend_Session_Namespace('registrationData');
$name = $s->name;
$email = $s->email;
$companyId = $s->companyId;
// when this request terminates, the data will be deleted if you leave
// setExpirationHops as 1.
See also Zend_Session - namespace expiration

Categories