How can i delete a session in view in cakephp 2.0? - cakephp

I have read in the cake book that Session in view uses SessionHelper, but that helper doesn't have method to delete session. Is this really so, could anyone help?

To delete session data, use the Session Component within a Controller, not a View.
//example from the CakePHP book (linked above)
$this->Session->delete('Person');
Or:
The destroy method will delete the session cookie and all session data
stored in the temporary file system. It will then destroy the PHP
session and then create a fresh session:
$this->Session->destroy();
While it's technically possible to delete session data in a view (it's just a PHP file after all), the CakePHP Framework was built with the MVC structure in mind. The "V" (for "view") should only be related to displaying the data provided by the Controller (retrieved from the Model).
The Model deals with accessing the data/database, and the Controller does the application logic. So - the Session Component (components are for controllers) is given a method to delete session data, but the Session Helper (helpers are for views) is not.

Based on what is the situation Custom Flash Messages can be used. Set flash message with custom key, like this
$this->Session->setFlash('my_value', 'default', array(), 'my_key');
and read it in view using flash method (which will automatically delete it)
$value = $this->Session->flash('my_key');
more details in this post http://hashmode.com/cakephp-delete-session-in-view/81

try unset($_SESSION['YOUR_SESSION_KEY']); in your view.

To delete a session variable, you can use the following code (in a Controller).
// same as unset($_SESSION['your_session_varable'])
$this->Session->delete('your_session_varable');
You can destroy all session variables calling the following:
$this->Session->destroy();

If the session data is an array and you want to access it just once just like the setFlash, you can set the array to setFlash with no template = false.
$this->Session->setFlash($arrayData,false,array(),'formData');
And then access it in the view
$data = $this->Session->flash('formData');
pr($data);

Related

Codeigniter database session update inconsistency

In Codeigniter, the function session->userdata($item) is used to retrieve session data and the definition of this function in Session class is :
function userdata($item)
{
return ( ! isset($this->userdata[$item])) ? FALSE : $this->userdata[$item];
}
Now the problem is this:
Each time a script is executed, a session object is created and the retrieved data is persistent untill end of the script. So if another script for example update session values, new values will be stored in DB, but retrieved data in other session objects are not updated and it makes an obvious inconsistency and inaccuracy in data.
I think it can be a serious problem in many cases.
Is it right or I'm misunderstanding something here? And if
IN codeigniter session object is created during the class initialization and userdata(session values) are updated every time user makes request. You can view whole session object via below piece of code:
print_r($this->session);
This will show you the complete session object with all necessary configurations you have set in your config file for session related variables like:
sess_encrypt_cookie, sess_use_database,sess_expiration ..etc
plus your current session user data. Now when you make next request session values are overridden by the new one or old values are just replaced by the new one. So there is no chance of data duplicacy or inconsistancy. It is recommended to use session table whenever you are saving large amount of data in session.

Get View Output In CakePHP 2.x Model

Context: I'm generating a PDF in a model callback (afterSave). I found a library I'm comfortable with called FPDF. I'm adding the FPDF class as a vendor.
So, without going into too much detail, essentially, once all checks have been completed for a particular contract application, the app needs to prepopulate a PDF file and attach it to an email.
I can figure everything out except how to generate the PDF in the model. I want to use a view to pass view vars to so that I can populate the template file and use the FPDF class to save a PDF file.
This file will in turn be attached the automated email and sent to the applicant.
So the flow is:
Once all checks have been complete (via crons and a CakePHP Shell), we trigger a function inside the model afterSave callback.
The function performs some logic and determines whether a declined or approved email should be sent.
If approved, then a PDF is generated using a view file and saved in /Views/pdf/
This file is attached to CakeEmail object and sent.
It's just the view rendering part here that I'm stuck with:
3. If approved, then a PDF is generated using a view file and saved in /Views/pdf/
How can I populate a view file with view variables and return the result into a variable?
For example, think of how the CakeEmail class does it with the CakeEmail->template('example') function......
Any ideas?
The answer is to construct your view class manually:
$view = new View(null, false);
$view->set(compact('variable1', 'variable2'));
$view->viewPath = 'ViewFolder';
$output = $view->render('view_file', 'layout');

ExtJS CRUD operations on Grid Panel and Grails backend

I am an absolute novice and have been working and struggling with ExtJS ! I am supposed to get a list of user records and dipslay them on Ext grid Panel. I have an ExtJS frontend and Grails ( Groovy Controllers ) backend. I have referred to a few links like:
http://docs.sencha.com/extjs/4.0.7/#!/example/grid/row-editing.html
http://docs.sencha.com/extjs/4.0.7/#!/example/restful/restful.html
http://docs.sencha.com/extjs/4.0.7/#!/example/writer/writer.html
The api property ( or ) tag ( or )attribute ( I don't know what it is called ) helps me in getting the list of JSON objects to be displayed in the Grid. Also, when I select a row and click on Delete, the request is reaching the delete action in my controller. But my problems begins here: how do I make sure that:
1) the selected row is deleted from Database? How do I pass the identifier or something to controller so that it will delete the record?
2) When I add a row, how do I pass the field values to backend Controller?
Most of the code is same as given in the restful link above. For reference, this is my Datastore:
https://docs.google.com/document/d/1gQyLCt6xWXTm-OUgYu7hku47r5WcS0my5yPBSKj2B7I/edit?usp=sharing
If you use a Rest proxy, ExtJS will auto generate the urls for you, based on the url stub that you specify. So if your proxy is configured to point to something like: /api/users, the following urls would be generated for each of the 4 actions:
read: /api/users (GET)
create: /api/users (POST)
update: /api/users/SomeIDFromTheUpdatedRecord (PUT)
delete: /api/users/SomeIDFromTheDeletedRecord (DELETE)
As you can see, the end point for each request is precisely the same (api/users), but for PUT and DELETEs, the id of the affected record is included in the URL automatically.
And of course, with POST and PUT requests, you can add any additional params that you'd like to send through to the server, although this will be done automatically when you persist the model instance via the store's configured proxy.

Cake PHP: How do I make one variable avaiable across all view and elements

I want to access
id of current logged user
name of current logged user
group_id of current logged user
group_name of current logged user
across the view files, to switch menus and tabs on and off according to group_id.
How can I achieve this with minimum sacrifice of performance?
Thanks
If you use the AuthComponent, it'll store the record of the currently logged-in user in the Session under the key Auth. You can access this anywhere through the session component or helper:
$this->Session->read('Auth.User.name')
Even if you're not using the AuthComponent, the Session is the best place to store information about the current user.
Otherwise and in general, the Configure class is usually a good place to store this kind of global information:
Configure::write('User', array('id' => $id, ...));
Configure::read('User.id');
What I always do is create a AppHelper and create a method for this.
Off course this is similar to deceze's answer but it reduces some code you need to write ;)
function user($key) {
$user = $this->Session->read('Auth.User');
if (isset($user[$key])) {
return $user[$key];
}
return false;
}
Then you can call the id of the user by $this->Html->user('id');
Perhaps you could set the variables you want in your AppController (extended by all sub controllers). You should then be able to access them from all views, though be careful to name them uniquely.
CakePHP book - App Controller

how to find out my current user id in other page controller after i login?

i am planing to set a permission on my event index page, which just allow certain user to view which had set when i add the event. After user click into my event, the event controller will 1st check the user id and check the event database which control the user can see which event in his calendar. The permission is added when user create a event and share to other user. Beside, how can i find the current user id to compare with my event database which is the accurate 1?
any suggestion for me to did this function?
i need to know the code and concept how i get the current user id to compare with all the event database, and allow the current user see the certain event.
thanks alot for your information.
The recommended approach for getting logged in user data is via the AuthComponent itself:
// in any controller
$userId = $this->Auth->user('id');
See Accessing the logged in user in the Auth section of the CakePHP Book.
Use sessions to save and read data for a user between pages.
Within Controllers:
// store a user id in the session
$this->Session->write('User.id', $userId);
// read a user id from the session
$userId = $this->Session->read('User.id');
Within Views:
// read a user id from the session
$userId = $session->read('User.id');
You can use any key you want if you prefer something over "User.id". I simply use this since it is what the AuthComponent defaults to if you are using that.
What you're looking for are ACLs (Access Control Lists). There's an AclComponent built into Cake which you should look into. It works together with the AuthComponent, which will hold the user id. It's a little complicated at first, but worth the hassle.
Also, for a simple approach, have a look at the model and controller settings of AuthComponent::authorize. This allows you to define an isAuthorized() method in your controller or model (your choice) which will store logic that determines access (should return true if access allowed and false if denied).
to see sessions, queries, data, and everything else that is passed from page to page in cake use this amazing little helper http://thechaw.com/debug_kit

Resources