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.
Related
I have a DataObject class called AdminUpload that stores two variables: UploadDate (which is always going to bet set to the current date) and Total, which is an int.
The function updateUploads() is called and stores the current date and increments the Total by 1 each time its called.
<?php
class AdminUpload extends DataObject {
private static $db = array(
'UploadDate' => 'Date',
'Total' => 'int'
);
// Tell the datagrid what fields to show in the table
private static $summary_fields = array(
'ID' => 'ID',
'UploadDate' => 'Current Date',
'Total' => 'Version Number'
);
public function updateUploads(){
$uploadDate = SS_Datetime::now();
$this->UploadDate = $uploadDate;
$this->Total++;//increment the value currently stored in the database each time
$this->write();
}
}
What I want to to is, when someone uploads a new image in the admin view, then the updateCache() function is called during the onAfterWrite() process. I only want to maintain one entry in the database, though, so every time I upload an image, I want to have just one entry in the AdminUpload database table.
public function onAfterWrite(){
$updateGallery = parent::onAfterWrite();
$adminUploading = AdminUpload::get();
$adminUploading -> updateUploads();
return $updateGallery;
}
I've never tried to do a function call in SilverStripe like this--it seems simple enough but since I am not going to add a new entry to the database with each call to the updateUploads() function, that's where I'm stuck. Any tips would be helpful...
It is incorrect approach to create a whole table for just one record. If you were going to use theses two fields on a page, then adding them to that page (create a new page type) would be a better idea.
If you are talking about file uploads, then you can always query this information directly from database.
$uploadedFilesCount = File::get()->count();
$lastUploadedFileDate = File::get()->sort('CreatedDate', 'DESC')->first()->CreatedDate;
onAfterWrite is a hook and used from DataExtension. There are cases when hooks are called directly on DO and then on extensions.
Your extension code might look like this to handle 'onCreated' state:
class UploadsCounter extends DataExtension {
protected $isCreating = false;
public function onBeforeWrite() {
if (!$this->owner->isInDB()) {
$this->isCreating = true;
}
}
// called on validation or database error
public function onAfterSkippedWrite() {
$this->isCreating = false;
}
public function onAfterWrite() {
if (!$this->isCreating) return;
$this->isCreating = false;
$adminUploading = AdminUpload::get()->first();
if (!$adminUploading ) {
$adminUploading = new AdminUpload();
$adminUploading->write();
}
$adminUploading->updateUploads();
}
}
You should define UploadsCounter extension on the dataobject that you are going to count, for example:
mysite/_config/config.yml
File:
extensions:
- UploadsCounter
Here is my controller:
class CommonController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('common_model'); //load your model my model is "common model"
}
public function add_work(){
$names = $_POST['name'];
$works = $_POST['work'];
$allValues = array(); // array to contains inserted rows
foreach($names as $key => $name){
$name= "your specified name";
$insertdata = array();
$insertdata['work'] = $works[$key];
$insertdata['name'] = $name;
$this->common_model->insert($insertdata);
array_push($allValues,$insertdata);
//$insert = mysql_query("INSERT INTO work(name,work) values ( '$name','$work')");
}
foreach($allValues as $insertRow){
echo $insertRow['work'];
echo $insertRow['name'];//this shows data well. but how to pass data in view.php
}
//view code will add here to show data in browser
}
Basically I want to pass all data to view.php for printing or exporting purpose. How can I do so.
To load a view you should do like this.
$this->load->view("filename");
If you want to pass data to view, you should do like this.
$this->load->view("filename",$data);
$data should have all parameters which you want to print in view.
The syntax goes like this.
$this->load->view("filename","data to view","Returning views as data(true / false");
If third parameter is true, view will come as data. It will not go to browser as output.
Edit:
Change
$this->load->view('print_view',$insertdata);
to
$data['insertdata'] = $insertdata;
$this->load->view('print_view',$data);
For more info, check this link
How CI Classes Pass Information and Control to Each Other
Calling Views
We will see.how the controller calls a view and passes data to it:
First it creates an array of data ($data) to pass to the view; then it loads and calls the view in the same expression:
$this->load->view('testview', $data);
You can call libraries, models, plug-ins, or helpers from within any controller, and models and libraries can also call each other as well as plug-ins and helpers.
However, you can't call one controller from another, or call a controller from a
model or library. There are only two ways that a model or a library can refer back to a controller:
Firstly, it can return data. If the controller assigns a value like this:
$foo = $this->mymodel->myfunction();
and the function is set to return a value, then that value will be passed to the variable $foo inside the controller.
//sample
public function display()
{
$data['text_to_display'] = $this->text_to_display;
$data['text_color'] = $this->text_color;
$this->load->view('display_view',$data);
}
Adding Dynamic Data to the View
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 method. Here is an example using an array:
$data = array(
’title’ => ’some’,
’heading’ => ’another some’,
’message’ => ’and another some’
);
$this->load->view(’view’, $data);
And here’s an example using an object:
$data = new Someclass();
$this->load->view(’view’, $data);
Sending Multiple Dimensional array
if we pull data from your database it will typically be
in the form of a multi-dimensional array.
<?php
class foo extends CI_Controller {
public function index()
{
$data[’Books’] = array(’POEAA’, ’TDD’, ’Clean C’);
$data[’title’] = "Title";
$data[’heading’] = "Heading";
$this->load->view(’view’, $data);
}
}
in view
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
<h3>My Books List</h3>
<ul>
<?php foreach ($Books as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</body>
</html>
More Learning
NOTE:
There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather
than sending it to your browser.The default behavior is false, which sends it to your browser. Remember to
assign it to a variable if you want the data returned:
$string = $this->load->view(’view’, ’’, TRUE);
Above will not solve your problem directly but definetly help in understanding concepts.
Am trying to pass some data from one function to another when i set the data into session and print the session data i get the correct data, but whe trying to use the data in another function i get the word "Assets" i dont know where this word come from. Session library is auto loaded.Any help please.
These are my codes:
First function:
$client_id = $this->uri->segment(3);
$sess_array = array(
'cl_id' => $client_d,
'selected_client'=>TRUE,
);
$this->session->set_userdata('selected_client',$sess_array);
Second function:
$client_sess = $this->session->userdata('selected_client');
$client_id= $client_sess['cl_id'];
Try this i think this will give you some idea.
function one(){
$client_id = $this->uri->segment(3);
$sess_array = array(
'cl_id' => $client_d,
'selected_client'=>TRUE,
);
$this->two($sess_array);
}
function two($id){
$client_id= $id;
}
Here is what the Model looks like:
function getResponse($gettingresponse)
{
$enrollresponse=$gettingresponse['sendresponse'];
return $enrollresponse;
}
The Controller is as follows:
public function Register()
{
$this->load->view('firstview');
$this->load->view('secondview');
if($_POST) {
$gettingresponse=array(
'sendresponse'=>$_POST['source'],
'receiverresponse'=>$_POST['destination']
);
$registration_confirm=$this->systemModel->responselogin($gettingresponse);
$resposeflag=$this->systemModel->getEmail($gettingresponse);
$data['resposeflag']=$gettingresponsevalue;
if($registration_confirm){
$this->token($data);
}
}
$this->load->view('thirdview');
}
public function token($data=array())
{
$this->load->view('firstview');
$data['resposeflag'];
$this->load->view('token',$data);
$this->load->view('thirdview');
}
The following View shows the data that has been passed between the functions of the Controller.
<?php
echo form_input(array('name'=>'source','readonly'=>'true','value'=>$resposeflag));
?>
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 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.