Can't access session variable in Kohana controller - php

I have mysterious issue with kohana framework.
I create session variable in controller function:
public function action_authorise()
{
session_start();
$_SESSION["user"] = "superAdmin";
}
Later in the same controller's another function I try to access this season:
public function action_getSession()
{
$this->template->test = $_SESSION["user"];
$this->template->content = View::factory('admin/main');
}
The problem is that when I call $test variable in admin/main view it returns empty string, but if I call implicitily $_SESSION["user"] in admin/main view, it returns "superAdmin" as it should.
Can anyone see mistake while calling session variable in controller? Thanks

The problem here is that you're passing the variable test to the view template and it needs to be passed to the view admin/main. You can do this a couple of ways, pick whichever one you like best:
// Create the view object
$partial_view = View::factory('admin/main');
// Assign the session value to the partial view's scope as `test`
$partial_view->test = $_SESSION["user"];
// Assign the partial view to the main template's scope as `content`
$this->template->content = $partial_view;
Shortcut syntax:
$this->template->content = View::factory('admin/main', array(
'test' => $_SESSION['user'],
));

You passing test variable to template view, but trying to access it it admin/main view. There is no test variable in admin/main view. These are different views. Each one has its own variables.
You should set test to admin/main view like:
public function action_getSession()
{
$this->template->content = View::factory('admin/main')
->set('test', $_SESSION["user"]);
}
Also there is very usefull Session class in Kohana. It takes care of session business within framework.
Take a look at user guide.

Related

Change class property value in method A and access updated value in method B

I'm using a custom PHP framework which is largely based on CodeIgniter.
In one of my controller files, I've set a class property called $orderId. After the user has filled in the form and submitted, I'll do a DB insert, get the order no. and override the $orderId class property value with that order no.
Then I'll redirect to the submit page where I want to access that updated $orderId class property value. This final part is not working, the submit class gets a blank value for property $orderId.
Where am I going wrong pls? The basic example below. Maybe I can't do this because of the redirect and should use a session var instead?
Thanks!
[EDIT] Or I could pass the orderId as the 3rd URL param in the redirect. E.G. redirect('orders/submit/'.self::$orderId); in which case I'll turn all the self:: instances into $this-> for class level scope.
class Orders extends Controller {
private static $orderId;
public function __construct() {
// assign db model
}
public function index() {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = [
// form data to pass to db model
];
self::$orderId = 12345; // example order no. return from db model
if(!empty(self::$orderId)) {
redirect('orders/submit');
}
}
}
public function submit() {
$data = [
'orderId' => self::$orderId
];
$this->view('orders/submit', $data);
}
}
The issue itself is a fundamental architecture problem. static only works when you're working with the same instance. But since you're redirecting, the framework is getting reinitialised. Losing the value of your static property. Best way to go about doing this is by storing the order id in a session variable and then read that variable. Sessions last for the as long as the browser window is open

pass data from controller to view inside another view in codeigniter

I fetched data from model in controller . i want to display this data in view inside another view. its showing blank page.
here is my code..
controller -
public function Listblog()
{
$listblog=$this->Login->listblog();
$listblogwithpage=$this->load->view('list_blog',$listblog);
$this->load->view('Welcome_message',$listblogwithpage);
}
model -
public function listblog()
{
$query=$this->db->get('new_employee');
return $query->result();
}
To assign a view to a variable the 3rd param must be true:
$listblogwithpage=$this->load->view('list_blog',$listblog, true);
Further the 2nd param must be an array. E.g. $data['listblog'] = 123;
$var = $this->load->view('somepage', $data, true);
This applies to any usage of view.
If you want to pass data from a controller to the first view and then have the second view pass data to the second view, you should do the following, always remembering that CI expects data passed to a view to be in form of an array. Take this and feel free to adapt it to suit your needs
In controller:
// populate an array and pass it to the first view
$first_view_data = array(
'listblog' => $listblog_query_result,
);
$this->load->view('firstview', $first_view_data);
In the first view, populate a new array with whatever data you need and call the second view from within the first one, passing the second data array:
$second_view_data = array(
'second_data_var' => $variable,
'other_data_var' => $other_var,
);
$this->load->view('second_view', $second_view_data);
CI is intelligent enough to let you call a view from within a view and pass data from each to the next in this way. Just remember, it has to be an array.
Using the data:
In the first view you'd call $listblog
In the second view, you would access $second_data_var and $other_data_var
$listblog $second_data_var and $other_data_var each could be single variables, arrays, objects and mostly anything as long as they are passed to the view as elements of an array
try this way.
//Controller
function Listblog() {
$data = array();
$data['listblog']=$this->Login->listblog();
$this->load->view(''list_blog',$listblog');
}
in view page you have to call that data array $listblog

Accessing session data in controller(Laravel)

I have a page 'A'. I create a session variable on this page.
This page is then redirected to a function 'A' in a controller 'A' using window.location.
I try to access the session variable in the function 'A' using the following line
var_dump($request->session->get('variableSetOnPageA'));
This returns NULL.
Why? I need the 'variableSetOnPageA'.
You can also get Session variable in Laravel like below in any of your function in Controller file:
$value = Session::get('variableSetOnPageA');
And you can set your Session variable like below in any of your function:
$variableSetOnPageA = "Can be anything";
Session::put('variableSetOnPageA',$variableSetOnPageA);
In your Controller file, make sure you add below code at top:
use Session;
You ought to invoke the session method from \Illuminate\Http\Request:
$request->session()->get('foo')
or global helper function
session('foo')
Important: It is very important that you call save function after you set any session value like this:
$request->session()->put('any-key', 'value');
$request->session()->save(); // This will actually store the value in session and it will be available then all over.
Check if you have $request available in the function.
public function A(Request $request) // Notice Request $request here.
{
$value = $request->session()->get('your-key');
//
}
This might be help you
if (session()->has('variableSetOnPageA')) {
$result=session()->get('variableSetOnPageA')
}

How to get last inserted id, then assign it to a global variable

I want to get last inserted id, and then assign it to a global variable to use it later.
I'm use callback_after_insert as the following:
$crud->callback_after_insert(array($this, '_callback_get_lastInsertID'));
function _callback_get_lastInsertID($post_array,$primary_key) {
$this->lastInsertedId = $primary_key;
}
Then, when use the $this->lastInsertedId to get its value, but I do not find any value ​​stored.
function featured_ad_offer() {
echo $this->lastInsertedId;
#$data['content'] .= $this->load->view('featured_ad_offer', '', true);
$this->load->view('index', $data);
}
There is an error message say Undefined property: Content::$lastInsertedId
Now, how to do that ?
Please try declaring your variable in class (assuming both functions are in the same class) right after "declaring" class itself i.e.
class Blog extends CI_Controller {
private $lastInsertedId = NULL;
public function fcn1() {$this->lastInsertedId = 3.14;}
public function fcn2() {var_dump($this->lastIndertedId);}
}
If you really mean using it as global variable you need to declare it in CI_Controller, or better yet create file in /core/Public_Controller that extends CI_Controller and let all your controllers be extended not by CI_Controller but Public_Controller therefore you can easily declare variables that are "global".
For more information on extending use this tutorial by Phil.
If you have troubles here is a user guide link.
There is another option (not recommended!) config class,
$this->config->set_item('item_name', 'item_value'); //setting a config value
$this->config->item('item name'); //accesing config value
maybe you can use this to get the last inserted id
$this->db->insert_id();
store it in the session
$this->load->library('session');
$this>session->set_userdata('last_inserted_id');
and use this session variable in other places
$last_inserted_id = $this->session->userdata('last_inserted_id');
wish this help :D
The solution that you need it can easily be resolved with Codeigniter sessions. So for example, what you can do is:
$crud->callback_after_insert(array($this, '_callback_get_lastInsertID'));
function _callback_get_lastInsertID($post_array,$primary_key) {
$this->session->set_userdata('last_insert_id', $primary_key);
}
Make sure that you have session class loaded first. The best way to do it is to actually have the sessions library at the autoload.
Now to actually call the last_insert_id again, you can simply do it by calling:
echo $this->session->userdata('last_insert_id');
So in your example you can simple do:
function featured_ad_offer() {
echo $this->session->userdata('last_insert_id');
#$data['content'] .= $this->load->view('featured_ad_offer', '', true);
$this->load->view('index', $data);
}

How to get view as an object into an action helper

I have a custom Action Helper that is working fine.
It's generating a dynamic login box if user is not logged in, and if he is, it is generating a menu.
But here I have a problem.
I want to generate that menu from a small view that's called user_menu.phtml
How I can get that view into my view helper, and assign it to an object?
Ok, some update, sorry for being stupid, actualy I have Action Helper:
I'm sorry If I was specific enough while writing my initial question.
So I have a Action helper in: library/Hlp/Action/Helper
That helper renders a form, if user is not loged inn.
Here is my Helper method, that does that job:
public function preDispatch()
{
$view = $this->getView();
$identity = Zend_Auth::getInstance()->getIdentity();
$session = new Zend_Session_Namespace('users_session');
$user_id = $session->idd;
if( !empty($identity) ) {
$userModel = new Application_Model_Vartotojai();
$user_email = $userModel->geUserRowBy('id', $user_id);
$user_email = $user_email['email'];
$view->login_meniu = $identity.' -
[id:'.$user_id.']<br />['.$user_email.'] <br/>
Log OUt';
//here I would like to read view file to an object or some other variable
//if posible to an object si I would be able to inject some values
} else {
$form = new Application_Form_LoginForm();
$view->login_meniu = $form;
$view->register_link = '<br />Register';
//here I would like to read view file to an object or some other variable
//if posible to an object si I would be able to inject some values
}
Additionaly to that form I want to add some links, or other HTML content, that would br stored in a view file.
All you have to do is to extend the Zend_View_Helper_Abstract class. Then you have the view object stored in the public property $view.
By using that object you could render your file with
return $this->view->partial('user_menu.phtml');
Update
Since you've updated your question I will update my answer leaving the previous answer because it's still valid for your previous question.
In your case you already have the $view object, to do what you're asking for in the comments simply use the partial helper attached to the view in this way:
$renderedScript = $view->partial('user_menu.phtml',
array('id' => $user_id, 'email' => $user_email['email']));
By giving an array or an object as second argument to the partial call you can use them as model in your script file. Example:
// content of user_menu.phtml
<h1>Login info</h1>
<p>
[id: <?=$this->user_id?>]<br />
[<?=$this->email?>] <br/>
Log Out'
</p>
P.s. I've used the short_tags + the equal sign (=) shorthand for echo in the view script, if you are not using them you should replace with <?php echo $this->email ?>
From the view, you can pass the this to the helper
myHelper($this,$otherVars )
And then from the helper you can call the other helper
myHelper($view, $otherVars){
$view->otherHelper()
}

Categories