I'm a newbie to codeigniter and I'm creating a project in which users are created and managed. here I'm using flashdata to display the temporary messages like "user created",etc.,
My code to set flash data is
$this->session->set_flashdata('message', 'User Created.');
In my view I called it as
$this->session->flashdata('message');
My problem is that when the user is created,flashdata is displayed and when i click home link the flash data is still available but when i click refresh/home again it disappears. I want it to be cleared when i click the home link for the first time itself. Is there a way to code it??.
Flashdata will only be available for the next server request, and are then automatically cleared.
if($user_created)
{
$this->session->set_flashdata('success', 'User created!');
redirect('login');
}
else
{
redirect('register');
}
if you want to clear set_flash in controller or another view file, then you can use this simple code.
$this->session->set_flashdata('error', 'User not found...'); //create set_flash
unset set_flash
//echo "<pre>"; print_r($_SESSION); die; //for check
if(isset($_SESSION['error'])){
unset($_SESSION['error']);
}
You should redirect after user created. Then when next time you click on home link it will not appear, try this,
$this->session->set_flashdata('message', 'User Created.');
redirect(base_url().'home.php');// you can change accordingly
The flashdata is supposed to display once.
And it gets disappears on page refresh.
So, if you redirect the page to another, it should work.
If you do not refresh the page, you can do it through jQuery.
Say your div displaying flash:
<div id="flash-messages">Success Message</div>
Write jQuery:
<script type="text/javascript">
$(function(){
$("#flash-messages").click(function(){$(this).hide()});
});
</script>
You must redirect the page somewhere after $this->session->set_flash('item','value');
Example:
if ($this->form_validation->run() == FALSE){
$this->session->set_flashdata('error',validation_errors());
redirect(base_url().'user/login');
}
else{
$this->session->set_flashdata('success','Thank you');
redirect(base_url().'user/login');
}
Usually developer make a mistake when they submit data to same page. They set flash data but forget to redirect.
You can use a Ajax framework for automatically hide the flash message.Also their contains all of the flash operation.
You can get more information from here.
https://github.com/EllisLab/CodeIgniter/wiki/Ajax-Framework-For-CodeIgniter
If nothing else helps, just extend the Session library and add a clear_flashdata function.
<?php defined('BASEPATH') or exit('No direct script access allowed');
// application/libraries/Session/MY_Session.php
class MY_Session extends CI_Session
{
public function __construct(array $params = array())
{
parent::__construct($params);
}
/**
* Clear flashdata
*
* Legacy CI_Session compatibility method
*
* #param mixed $data Session data key or an associative array
* #return void
*/
public function clear_flashdata($data)
{
$this->set_userdata($data, null);
}
}
Related
I am trying to redirect to a page on my external page, what I have tried till now is. Manually I added some files.
In /custom/modules/Users/logic_hooks.php
<?php
$hook_version = 1;
$hook_array = Array();
$hook_array['after_logout'] = Array();
$hook_array['after_logout'][] = Array(
//Processing index. For sorting the array.
1,
//Label. A string value to identify the hook.
'after_logout example',
//The PHP file where your class is located.
'custom/modules/Users/logic_hooks_class.php',
//The class the method is in.
'logic_hooks_class',
//The method to call.
'after_logout_method'
);
?>
And another file in In /custom/modules/Users/logic_hooks_class.php
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class logic_hooks_class
{
function after_logout_method($bean, $event, $arguments)
{
header('Location: http://raviranjan.info/');
}
function AfterLogout(&$bean, $event, $arguments)
{
SugarApplication::redirect('http://raviranjan.info/');
}
}
?>
So is there any other way to redirecting or just show something on screen before or after logging out from SugarCRM application.
Advance Thanks for any help.
There are multiple ways of doing this. Read following details:
show alert of any other type of message by handling click event of logout link. e.g. when user click that link then show alert of any other type of message.
after logout redirect user to your custom page( you can build custom entry point which will be accessible with auth=>false).
you can add any button or java-script to show message then redirect it to your target page.
Simple jquery selector, see following:
$("a.utilsLink").click(function(){
var r = confirm("Are you sure to logout?");
if (r == true) {
console.log("yes is clicked");
} else {
console.log("cancel is clicked...");
return false;
}
});
I have /signup/select-plan which lets the user select a plan, and /signup/tos which displays the terms of services. I want /signup/tos to be only accessible from /signup/select-plan. So if I try to go directly to /signup/tos without selecting a plan, I want it to not allow it. How do I go about this?
In the constructor, or the route (if you are not using contructors), you can check for the previous URL using the global helper url().
public function tos() {
if ( !request()->is('signup/tos') && url()->previous() != url('signup/select-plan') ) {
return redirect()->to('/'); //Send them somewhere else
}
}
In the controller of /signup/tos which returns the tos view just add the following code:
$referer = Request::referer();
// or
// $referer = Request::server('HTTP_REFERER');
if (strpos($referer,'signup/select-plan') !== false) {
//SHOW THE PAGE
}
else
{
dd("YOU ARE NOT ALLOWED")
}
What we are doing here is checking the HTTP referrer and allowing the page access only if user comes from select-plan
You are need of sessions in laravel. You can see the following docs to get more info: Laravel Sessions
First of all you need to configure till how much time you want to have the session variable so you can go to your directory config/sessions.php and you can edit the fields 'lifetime' => 120, also you can set expire_on_close by default it is being set to false.
Now you can have following routes:
Route::get('signup/select-plan', 'SignupController#selectPlan');
Route::post('signup/select-token', 'SignupController#selectToken');
Route::get('signup/tos', 'SignupController#tos');
Route::get('registered', 'SignupController#registered');
Now in your Signupcontroller you can have something like this:
public function selectPlan()
{
// return your views/form...
}
public function selectToken(Request $request)
{
$request->session()->put('select_plan_token', 'value');
return redirect('/signup/tos');
}
Now in signupController tos function you can always check the session value and manipulate the data accordingly
public function tos()
{
$value = $request->session()->get('select_plan_token');
// to your manipulation or show the view.
}
Now if the user is registered and you don't need the session value you can delete by following:
public function registered()
{
$request->session()->forget('select_plan_token');
// Return welcome screen or dashboard..
}
This method will delete the data from session. You can manipulate this. You won't be able to use in tos function as you are refreshing the page and you want data to persist. So its better to have it removed when the final step or the nextstep is carried out. Hope this helps.
Note: This is just the reference please go through the docs for more information and implement accordingly.
I am trying to make an small app so I have choosen Fat Free Framework. I need to show some messages based on successful or error. Suppose if I want to add an user then if successfully added show message that user has been added successfully or if not show error message that user cannot be added. I cannot figure it out. Here is my UsersController code
public function index(){
$user = new User($this->db);
$this->f3->set('users',$user->all());
//there should be a way to decide if its error message or success and after display,
//it shouldn't be displayed again for the same task.
//or may be it should be check in view file, I don't know where is the correct place
// to do it
$this->f3->set('page_head','User List');
$this->f3->set('view','users/list.htm');
}
public function create(){
if($this->f3->exists('POST.create')){
$user = new User($this->db);
$user->add();
//set session here to show in view file after redirect to list page
$this->f3->reroute('/users');
} else{
$this->f3->set('page_head','Create User');
$this->f3->set('view','users/create.htm');
}
}
My flash messages controller looks like this: https://github.com/ikkez/f3-flash/blob/master/lib/flash.php
To set a message i do:
if ($this->resource->updateProperty(array('_id = ?', $params['id']), 'published', true)) {
\Flash::instance()->addMessage('Your post was published. Hurray!', 'success');
} else {
\Flash::instance()->addMessage('This Post ID was not found', 'danger');
}
$f3->reroute('/admin/post');
To render the messages i include this template in my layout https://github.com/ikkez/fabulog/blob/master/app/ui/templates/alert.html which calls a function that dumps and clears all messages, so they will only be displayed once. You can also use the SESSION in a template token like {{#SESSION.flash}} and use it for <repeat> in the template.
I have a method in CI which basically adds a user to a table - if any form validation occurs it reloads the view - if successful it reloads the view to show that the user was added successfully. As seen below:
public function loadPeopleView(){
//loads unit page view
$this->load->model('people_model');
$people['people'] = $this->people_model->getPeople();
$this->load->view("header");
$this->load->view("people page/people_view", $people);
$this->load->view("footer");
}
public function addPerson(){
$this->form_validation->set_rules('personName', 'personName', 'required|min_length[6]|max_length[150]|trim|xss_clean');
$this->form_validation->set_rules('personPet', 'personPet', 'required|trim|min_length[3]|max_length[30]|xss_clean');
if($this->form_validation->run()){
$this->load->model('');
$this->people_model->addPerson();
$this->loadPeopleView();
} else{
//if validation fails - returns the peopl view this display error messages
$this->loadPeopleView();
}
}
my issue is when someone adds a person the browser remains on:
localhost/peoplecontroller/addperson
if the user keeps refreshing the page - loads of people will continue to be added in - is there anyway I can put the page back to:
localhost/peoplecontroller/
without having to use a redirect as I still want any error messages from the form validation to appear
I am only giving you an example please arrange according save and return functionality
public function addPerson(){
$this->load->model('people_model'); // load model
// validation
$this->form_validation->set_rules('personName', 'personName', 'required|min_length[6]|max_length[150]|trim|xss_clean');
$this->form_validation->set_rules('personPet', 'personPet', 'required|trim|min_length[3]|max_length[30]|xss_clean');
// check validation not clear
if ($this->form_validation->run() == FALSE) {
//if validation fails - returns the peopl view this display error messages
// also set error dat back
// setting up send back values to view
$this->data['personName'] = $this->input->post('personName');
$this->data['personPet'] = $this->input->post('personPet');
// get this->data values as a variable in view like $personName
// load view
$this->load->view("header");
$this->load->view("people page/people_view", $this->data);
$this->load->view("footer");
}
else{ // after validation success
// do your saving db stuff and set success message in session flash and redirect to
$this->people_model->addPerson();
// get and show message flash in your view
$this->session->set_flashdata('message', 'Please check card details and try again');
redirect('results', 'refresh');
}
}
I wanted to create a dynamic signup.php. The algorithm is as follow:
Algorithm
when signup.php is requested by client, the code will attempt to check whether user send any data in $_POST.
if $_POST does not contains any data (means it's the first time user request for signup.php), a signup form will be return to the user, allowing user to enter all his/her details and again send back to signup.php through submit button.
if $_POST does contains data (means user has fill up the signup form and is now sending all the data back to signup.php), then the php code will attempt validate all those data and return result showing user has been successfully registered or error if failed to do so.
The problem I'm having right now is how am I going to check whether it's the first time user request for signup.php or not?
Use isset() to check if $_POST contains data.
http://php.net/isset
To answer your question, "how am I going to check whether it's the first time user request for signup.php or not?", honestly, probably for other users......
There are a few ways, cookies, storing request ips in a database, bleh, bleh, bleh. But...... None of them are guaranteed. The user can disable cookies, use a dynamic ip, etc. You could issue a unique hash and place it as a login.php?q=encValueForUniquePageRequest
but...... The architecture you laid out won't be practical.
Sorry :(
To check that request is POST:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//process new user
}
?>
Example:
<?php
Class signup_controller extends controller{
private $data = array();
private $model = array();
function __construct(Core $core){
parent::__construct($core);
/* load models - assign to model */
$this->model['page'] = $this->core->model->load('page_model', $this->core);
$this->model['auth'] = $this->core->model->load('auth_model', $this->core);
/* check script is installed - redirect */
if(empty($this->core->settings->installed)){
exit(header('Location: '.SITE_URL.'/setup'));
}
}
function index(){
/* do signup - assign error */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($this->model['auth']->create_user(1)===false){
$this->data['error'] = $this->model['auth']->auth->error;
}
}
/* not logged in */
if(empty($_SESSION['logged_in'])){
/* assign form keys */
$_SESSION['csrf'] = sha1(uniqid().(microtime(true)+1));
$_SESSION['userParam'] = sha1(uniqid().(microtime(true)+2));
$_SESSION['passParam'] = sha1(uniqid().(microtime(true)+3));
$_SESSION['emailParam'] = sha1(uniqid().(microtime(true)+4));
/* get partial views - assign to data */
$this->data['content_main'] = $this->core->template->loadPartial('partials/signup', null, $this->data);
$this->data['content_side'] = $this->core->template->loadPartial('about/content_side', null, $this->data);
/* layout view - assign to template */
$this->core->template->loadView('layouts/2col', 'content', $this->data);
}
/* signed in - redirect */
else{
exit(header('Location: ./user'));
}
}
}
?>