I have a page with URL http://arslan/admin/category/index/0/name/asc/10 in Codeigniter.
In this URL, the uri_segment start from 0. This (0) is the default search value, name and asc are the default sort field and order, and 10 is the pagination index.
Now if I move to an add page with URL (http://arslan/admin/category/add/)
similarly like above "add" is the current function.
Now if i want to go back through a link to back page... How can I divert the user back? I can't make the URL go back.
Can somebody help me please?
I am not sure if i understand the question correctly, if not please ignore my answer, but I think you want a link to "go back to previous page", similar to the back-button in a web browser.
If so you could use javascript to solve this by simply using this line:
Go back
I extend the session class by creating /application/libaries/MY_Session.php
class MY_Session extends CI_Session {
function __construct() {
parent::__construct();
$this->tracker();
}
function tracker() {
$this->CI->load->helper('url');
$tracker =& $this->userdata('_tracker');
if( !IS_AJAX ) {
$tracker[] = array(
'uri' => $this->CI->uri->uri_string(),
'ruri' => $this->CI->uri->ruri_string(),
'timestamp' => time()
);
}
$this->set_userdata( '_tracker', $tracker );
}
function last_page( $offset = 0, $key = 'uri' ) {
if( !( $history = $this->userdata('_tracker') ) ) {
return $this->config->item('base_url');
}
$history = array_reverse($history);
if( isset( $history[$offset][$key] ) ) {
return $history[$offset][$key];
} else {
return $this->config->item('base_url');
}
}
}
And then to retrieve the URL of the last page visited you call
$this->session->last_page();
And you can increase the offset and type of information returned etc too
$this->session->last_page(1); // page before last
$this->session->last_page(2); // 3 pages ago
The function doesn't add pages called using Ajax to the tracker but you can easily remove the if( !IS_AJAX ) bit to make it do so.
Edit:
If you run to the error Undefined constant IS_AJAX, assumed IS_AJAX
add the line below to /application/config/constants.php
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
There are two ways to solve your problem: First you could place a link that is using the javascript back-function onclick, like this ...
go back
... or you always save the current full page url into a cookie and use that for generating the back link - a helper could look like this (not tested) ...
/**
* save url to cookie
*/
if(!function_exists('urlhistory_save'))
{
function urlhistory_save()
{
$CI =& get_instance();
$CI->load->library('session');
$array = array(
'oldUrl' = $CI->session->userdata('newurl'),
'newurl' = $CI->uri->uri_string()
);
$CI->session->set_userdata($array);
}
}
/**
* get old url from cookie
*/
if(!function_exists('urlhistory_get'))
{
function urlhistory_get()
{
$CI =& get_instance();
$CI->load->library('session');
return $CI->session->userdata('oldurl');
}
}
In your controller you would use urlhistory_save() to save the current URL and in the view youd could use urlhistory_get() to retreive the old address like this:
<a href="<?php echo base_url().urlhistory_get(); ?>go back</a>
The most simplest way to redirect to your previous page , try this it work for me
redirect($this->agent->referrer());
you need to import user_agent library too $this->load->library('user_agent');
You can create a Session to go to back page as:
$this->session->set_userdata('ses_back_jobs','controller
name'.array_pop(explode('controller name',$this->input->server('REQUEST_URI'),2))); //Back page
Then if u want to redirect to some page use it:
redirect($this->session->userdata('ses_back_jobs'));
or use it to the anchor.
Related
I want to get member data from class that has been defined in other page.Suppose page 1 contains that class , how do i get that data in page 2.
Code looks something like this:
page 1
class gamecard {
function save_order($json_order){
if($payment_method=='Paypal') {
$vpcURL = $pp->buildCheckoutUrlTest($json_order);
}
return json_encode(array('order' => $order,
'errID' => $errID,
'errMess' => $errMess
));
}
}
page 2
print_r($vpcURL);
Thank you.
On page2
require 'page1.php';
$obj=new gamecard();
$obj->save_order('Pass your variable');
echo $obj->$vpcUrl;
I will ask you to make some modifications in the game card itself.
I would do something like this
class gamecard {
public $vpcURL;
function save_order($json_order){
if($payment_method=='Paypal')
$this->vpcURL = $pp->buildCheckoutUrlTest($json_order);
return json_encode(array('order' => $order, 'errID' => $errID,'errMess' => $errMess));
}
}
if you can reach the instance of gamecard on page2, you could write a getter/setter function for vpcURL. Set $vpcURL as member variable and get it via getter.
If you can't access the instance from page2, then you could do it over a static method
Well, one way is to include the gamecard class in page 2 and make a global variable of $vpcURL. then call upon that method from page 2.
I want a global array that I can access through controller functions, they can either add or delete any item with particular key. How do I do this? I have made my custom controller 'globals.php' and added it on autoload library.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$notification_array = array();
$config['notification'] = $notification_array;
?>
following function on controller should add new item to my array
function add_data(){
array_unshift($this->config->item('notification'), "sample-data");
}
after add_data adds to the global array, whenever following function is called from client, it should give the updated array to the client.
function send_json()
{
header('content-type: application/json');
$target = $this->config->item('notification');
echo json_encode($target);
}
But my client always gets empty array. How can I make this happen? Please help.
Hi take advantage of OOP, like this
// put MY_Controller.php under core directory
class MY_Controller extends CI_Controller{
public $global_array = array('key1'=>'Value one','key2'=>'Value2'):
public function __construct() {
parent::__construct();
}
}
//page controller
class Page extends MY_Controller{
public function __construct() {
parent::__construct();
}
function send_json()
{
header('content-type: application/json');
$target = $this->global_array['key1'];
echo json_encode($target);
}
}
One solution I came up is to use session, its easy to use and its "fast" you need to do some benchmarking.
As I commented on both answers above/below there is no way you get same data in different controllers just because with each request everything is "reset", and to get to different controller you need to at least reload tha page. (note, even AJAX call makes new request)
Note that sessions are limited by size, you have a limit of 4kb (CodeIgniter stores session as Cookie) but wait, there is way around, store them in DB (to allow this go to config file and turn it on $config['sess_use_database'] = TRUE; + create table you will find more here)
Well lets get to the answer itself, as I understand you tried extending all your controllers if no do it and place some code in that core/MY_Controller.php file
as follows:
private function _initJSONSession() { //this function should be run in MY_Controller construct() after succesful login, $this->_initJSONSession(); //ignore return values
$json_session_data = $this->session->userdata('json');
if (empty($json_session_data )) {
$json_session_data['json'] = array(); //your default array if no session json exists,
//you can also have an array inside if you like
$this->session->set_userdata($ses_data);
return TRUE; //returns TRUE so you know session is created
}
return FALSE; //returns FALSE so you know session is already created
}
you also need these few functions they are self explainatory, all of them are public so you are free to use them in any controller that is extended by MY_Controller.php, like this
$this->_existsSession('json');
public function _existsSession( $session_name ) {
$ses_data = $this->session->userdata( $session_name );
if (empty( $ses_data )) return FALSE;
return TRUE;
}
public function _clearSession($session_name) {
$this->session->unset_userdata($session_name);
}
public function _loadSession($session_name) {
return (($this->_existsSession( $session_name )) ? $this->session->userdata($session_name) : FALSE );
}
the most interesting function is _loadSession(), its kind of self explainatory it took me a while to fully understand session itself, well in a few words you need to get (load) data that are in session already, do something with it ([CRUD] like add new data, or delete some) and than put back (REWRITE) all data in the same session.
Lets go to the example:
keep in mind that session is like 2d array (I work with 4+5d arrays myself)
$session['session_name'] = 'value';
$session['json'] = array('id' => '1', 'name' => 'asok', 'some_array' => array('array_in_array' => array()), 'etcetera' => '...');
so to write new (rewrite) thing in session you use
{
$session_name = 'json';
$session_data[$session_name] = $this->_loadSession($session_name);
//manipulate with array as you wish here, keep in mind that your variable is
$session_data[$session_name]['id'] = '2'; // also keep in mind all session variables are (string) type even (boolean) TRUE translates to '1'
//or create new index
$session_data[$session_name]['new_index'] = FALSE; // this retypes to (string) '0'
//now put session in place
$this->session->set_userdata($session_data);
}
if you like to use your own function add_data() you need to do this
well you need to pass some data to it first add_data($arr = array(), $data = ''){}
eg: array_unshift( $arr, $data );
{
//your default array that is set to _initJSONSession() is just pure empty array();
$session_name = 'json';
$session_data[$session_name] = $this->_loadSession( $session_name );
// to demonstrate I use native PHP function instead of yours add_data()
array_unshift( $session_data[$session_name], 'sample-data' );
$this->session->set_userdata( $session_data );
unset( $session_data );
}
That is it.
You can add a "global" array per controller.
At the top of your controller:
public $notification_array = array();
Then to access it inside of different functions you would use:
$this->notification_array;
So if you want to add items to it, you could do:
$this->notification_array['notification'] = "Something";
$this->notification_array['another'] = "Something Else";
I just started learning codeigniter and i must say its pretty easy but I have a problem dealing with wrong urls, for example:
if I have an anchor tag like this
http://example.com/info/2
in the controller if I have
public function info( $x ) {
$data['body'] = "Personal_info";
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
the controller grabs the links
segment (3)
and then grab the details of the id from the database.
now for instance if a user manually edit the link on the browser and change the
segment(3)
to lets say 7 and there is no id in the database as 4.
how do I handle such a problem? I am a beginner so please pardon me
You could use empty method to check if there is data and if not redirect away from the page.
public function info( $x )
{
$details = $this->person_model->get_detail( $x );
if(empty($details))
redirect('other/url');
$data['body'] = "Personal_info";
$data['details'] = details;
$this->load->view('view', $data);
}
This way it doesn't throw errors and potentially attempt to display something that doesn't exist.
you can check if the passed id exists in database before trying to fetch related data, like:
$data_exists = $this->person_model->data_exists( $x );
if( $data_exists ) {
$data['details'] = $this->person_model->get_detail( $x );
$this->load->view('view', $data);
}
else {
//load some view for showing no such id exists in db
}
where data_exists() can be a function in model which returns TRUE or FALSE depending on existance of your id in database.
How can I detect if the user is on the homepage of my website with CakePhp?
May I use $this->webroot?
The goal is to do something only if the current page is the homepage.
Simply you can try this:
if ($this->request->here == '/') {
// some code
}
Also it is good to read this part of documentation:
You can use CakeRequest to introspect a variety of things about the
request. Beyond the detectors, you can also find out other information
from various properties and methods.
$this->request->webroot contains the webroot directory.
$this->request->base contains the base path.
$this->request->here contains the full address to the current request
$this->request->query contains the query string parameters.
You can find it by comparing the present page with webroot or base
if ($this->here == $this->webroot){ // this is home page }
OR
if ($this->here == $this->base.'/'){ // this is home page }
You can get it properly by checking against params like below:
if($this->params['controller']=='homes' && $this->params['action']=='index')
in this way you can check for any page of cakephp on view side
Assuming you are going to do something from the AppController, it's best to see if the current controller/action pair is the one you define as "homepage" (as Cake can route a user anywhere from the '/' route and you probably still want the logic to be triggered when the action is called directly with the full /controller/action URI and not just on /). In your AppController just add a check:
if ($this->name == 'Foo' && $this->action == 'bar') {
// Do your stuff here, like
echo 'Welcome home!';
}
That way it will trigger whenever the bar action is requested from the FooController. You can obviously also put this logic in the specific controller action itself (and that might make more sense since it's less overhead).
You can use $this->request->query['page'] to determine where you are,
if ( $this->request->query['page'] == '/' ){
//do something
}
Edit:
check $this->request object using echo debug($this->request), it contains many informations you can use. Here is a sample of what you get:
object(CakeRequest) {
params => array(
'plugin' => null,
'controller' => 'pages',
'action' => 'display',
'named' => array(),
'pass' => array(
(int) 0 => 'home'
)
)
data => array()
query => array()
url => false
base => ''
webroot => '/'
here => '/'
}
If your home page is home.ctp as mentionned by the cakePHP convention. In PagesController, you can change the display function to look like :
(added code starts at the comment /* Custom code start*/ )
public function display()
{
$path = func_get_args();
$count = count($path);
if (!$count) {
return $this->redirect('/');
}
$page = $subpage = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
/* Custom code start*/
if("home"==$page){
// your code here
}
/* Custom code end*/
$this->set(compact('page', 'subpage'));
try {
$this->render(implode('/', $path));
} catch (MissingTemplateException $e) {
if (Configure::read('debug')) {
throw $e;
}
throw new NotFoundException();
}
}
The way I achieved that was by using $this->params. If you use print_r($this->params);, you will see the content of that variable for you. It will return an array. You will see the difference of when you are versus when you are not in the home page. You will have to use one of the keys in $this->params to make your evaluations with an if statement. That was how I achieved it. Maybe you can find this approach useful too.
I am trying to submit a EDIT form which edits Users Academics Details,
These Details have unique id in DB and my Code in Short Looks like below :
class edit extends ci_controller
{
function user_academics($id = NULL)
{
if(isset($id) == FALSE) //if link is ./edit/user_academics
{
$id = NULL;
$link = site_url('profile');
show_error("Invalid Page Request! <a href='$link' Go to Profile </a>");
}
$user_id = $this->session->userdata('user_id');
$data['fill'] = $this->edit_model->get_user_academics($id);
if($user_id != $data['fill']['user_id']) // check if logged in user is accessing his record or others
{
$link = site_url('profile');
show_error("This is an Invalid Request ! <a href='$link'>Go to Profile </a>");
}
else // actual work starts here
{
$this->session->set_flashdata('ua_id',$id); // update_academics will get this data
$this->load->view('edit/edit_3_view',$data);
}
}
function update_academics()
{
$ua_id = $this->session->flashdata('ua_id'); // flash data used here .
if( !$ua_id )
{
show_error('Sorry, This request is not valid!');
}
$academics = array(
// All post values
);
$this->edit_model->update_user_academics($academics,$ua_id);
//print_r($academics);
redirect('profile');
}
}
Now the problem is
- If I open two different records to edit, then It will set only one Session Flash value.
- And No matter what I edit , the existing values of the last flash value gets updated.
Please Suggest me another way or Correct me if I am wrong in above code . Thanks
save that flashdata in array, like:
$myArr = array('value 1', 'value 1');
//set it
$this->session->set_flashdata('some_name', $myArr);
And in view:
$dataArrs = $this->session->flashdata('some_name');
//loop thru $dataArrs to show the flashdata
Flash data is simply like variable which is available only in next request, you can bypass this behavior by using two different keys with record id in it, so that when you use flash data for showing message you can access key with particular record id.