I am passing an array of WP objects (ie, WP_User) from Wordpress site to a popup window using $_SESSION variable.
When popup is open, I var_dump($_SESSION['variable']['WP_Users']) and everything looks good.
However, when I am trying to access $_SESSION['variable']['WP_users'][0]->data->parameter, all values are NULL.
Aside from that, error_log says:
"main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "WP_User" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in /ABSPATH/popup_template.php line 52"
As I understand, my popup has no definitions of WP classes, such as WP_User etc., therefore I am unable to manipulate WP objects.
Any ideas on how to tackle this? (keep in mind I am not using (un)serialize() at all)
So solution was actually pretty straightforward: I had to do what error_log asked.
In parent window I had to serialize array of Wordpress objects before shoving them into the SESSION var like so:
$_SESSION['variable'] = serialize( $array_of_WP_objects );
To my popup template I had to add definition of WP_User from wp_includes folder, and then unserialize my array back to $array_of_WP_objects like so
require_once( '../../../../wp-includes/class-wp-user.php' );
$array_of_WP_objects = unserialize( $_SESSION['variable'] );
Worked like a charm.
Related
I am trying to access the content of custom fields in the user object.
Some have advocated the user of user_load. But according to Drupal, that deprecated.
in Drupal 8.x, will be removed before Drupal 9.0. Use
\Drupal\user\Entity\User::load().
So I've attempted to use Entity::load. It loads the object and in my IDE, I can see the values... but I can't seem to load a local variable with the value. Here is code that isn't working.
public function arguments($arg1) {
$userProfile = \Drupal\user\Entity\User::load($arg1);
$display_username = $userProfile->getAccountName();
$current_user = user_load($user_id);
$lastname = $userProfile->values["field_user_last_name"]["x-default"][0]["value"];
That string came from the path I saw in the object returned. However, as one can see in the screen shot from the IDE, the value comes back NULL.
I'm sure it is something simple that I'm not seeing. (missing the good old days of non-OOP!)
The $userProfile is an object so data should be called via methods.
The list of all methods can be found in Drupal documentation.
Long story short, all Drupal entities use the same methods to return field value.
The get('field_name') method returns the field object and getValue() returns the value of field.
In your case that would be:
$field_value = $userProfile->get('field_user_last_name')->getValue()[0]["value"];
By using so called magic methods the code will look even cleaner and you can simply get the value as:
$field_value = $userProfile->field_user_last_name->value;
Please note that magic methods can not be always used while standard methods can be.
I've been researching a bit but I cannot find any way of doing this...
I need to pass an instance of a complex PHP class (formed by properties, functions, arrays, etc.) between different pages. The variable of the object is called $Model; I've been trying to use the GET method and "serialize" / "unserialize", but I cannot retrieve the object in the new page...
I'm trying to pass the object as follows:
echo 'Pass Model Object';
Then, I'm trying to retrieve it like this:
if(isset($_GET['modelobject'])) //$_GET when used in a link!
{
$ModelObjPost = unserialize($_GET['modelobject']); //$_GET when used in a link!
echo "POST: Model Object retrieved<br>";
var_dump($ModelObjPost);
}
There could be some kind of problem with certain characters in the serialization (I'm not sure, though), as the link that should send the object sometimes gets printed as (and it is also recognized as a URL):
r";s:3:"new";b:0;}i:2;(... MORE STUFF ...)s:9:"dbModelId";s:1:"1";}">Pass Model Object
Should I try a completely different approach, or this method should work, but there is just something I'm doing wrong?
Thanks in advance for your time!
Warning: I would discourage serializing a class and placing the result in an end-user readable location. This probably reveals far more about your application than you should be disclosing publicly.
Let's clear up some terminology right up front. I assume you know this, but just to be clear... A class is both the code that defines the behavior you want for an object and data (properties). An instance is when you use the new keyword on a class to create a usable object using that class definition.
By the very nature of how PHP works (typically), all instances are unloaded and deleted after a page loads. It cannot survive in memory to be used on a second page.
Typically you would create a file that contains the class definition you're trying to pass between pages, and create a new instance of the class on each page.
If you're trying to keep state between pages, you should look at using sessions. If you choose to use sessions, and want to keep an instance of your class inside your session, keep in mind what I said above - it will be deleted and recreated between the pages. You will need to make sure your class is set up to reload everything it needs to operate. PHP provides for a "magic" method to do this: __wakeup() in this method, you will need to restore the object back to the same state it was in on the previous page load.
Other ways to pass data between pages (or page loads) would be arrays for HTTP GET or POST.
$data = array( 1,2,3,4, 'a' => 'abcd' );
$query = http_build_query(array('aParam' => $data));
$url = 'somepage.php?data=' . $query;
Forms may be created to pass arrays of data by utilizing array notation in the form field names
<form action="somepage.php" method="post">
<input name="option[a][]" value="option a,0">
<input name="option[a][]" value="option a,1">
<input name="option[b][]" value="option b,0" />
<input name="option[b][]" value="option b,1" />
<input name="option[]" value="option 0" />
</form>
Access this data like this:
<?php
echo $option['a'][0];
echo $option['a'][1];
echo $option['b'][0];
// etc
Your two best options in this case would be to either:
Use a $_SESSION variable. You could save the object as $_SESSION['Model'] and access that on each page that you need to use it. Be sure to call session_start(); on each of those pages to resume the session.
Use urlencode(serialize($Model)) in the URL and use urldecode() on the next page to make sure that you don't have encoding issues in the URL. json_encode() and json_decode() would also be a good option for object to string serialization.
My php code creates a "School" object which is (among other functions) able to return several forms which are being ,on submit, handled by php.
Thru one of these forms i'm able to add a "SchoolClass" object to a array in the "School" object but it seems that the "School" object is recreated at some point after i add the "SchoolClass" object. This re-creation makes the array of "SchoolClass" disappear.
The functions that returns the forms are static, but the functions where "SchoolClass" objects are added to the array are not static; ("School::ShowStudentForm() and School->RegisterSchoolClass($class)")
Both the class definition and the php-script which handles the form after submit is in the same file(index.php). I had the idea that keeping both the class code and the form handling code in the same file would do the trick, but it did not make a change.
Question 1: how do i maintain the "School" object for as long as i need it?
Question 2: is it ok to create a class with only static methods and write the data directly to a file or database to avoid the whole problem or just skip the whole object approach and just use "normal" functions?
Yes, this problem is probably encounterd before and therefore also answered before but i have not been able to find a answer which i understand.
OK....i figured it out.
I can use the $_SESSION variable to store it.
Now i do like this in the start of the page:
$school = null;
if(!isset($_SESSION["school"]))
{
$school = new School;
$_SESSION["school"] = $school;
echo "New school <br>";
} else {
$school = $_SESSION["school"];
}
I have a product export and I try to export all objects using my custom plugins. I'm using below method to load all objects
$list = new Pimcore_Model_Object_Bodproduct();
$list->setOrder ( "ASC" );
$list->setOrderKey ( "o_id" );
// Load all filtered objects - products
$list->load ();
Then i'm using foreach loop to access the objects.
It's working fine. But the problem is it's taking lot of time to export. Is there any other solutions for this .. I mean instead of load() function, is there any other method is available?
You can use $list->loadIdList() to fetch only object IDs - which should be faster. Then you can call Object::getById($id) within loop to provide progress bar (assuming your script is launched in console).
In fact this is what load() is doing internally, please see Object\Listing\Resource class
Another option is to split load to many "pages" by calling $list->getItems($offset, $itemCountPerPage).
In Pimcore object listing, you can traverse each object in list without calling a load method. In your case, just remove "$list->load ();" and see it will work with less time.
I have instantiated a class in my index.php file. But then I use jQuery Ajax to call some PHP files, but they can't use my object that I created in the index.php file.
How can I make it work? Because I donĀ“t want to create new objects, because the one I created holds all the property values I want to use.
Use the session to save the object for the next page load.
// Create a new object
$object = new stdClass();
$object->value = 'something';
$object->other_value = 'something else';
// Start the session
session_start();
// Save the object in the user's session
$_SESSION['object'] = $object;
Then in the next page that loads from AJAX
// Start the session saved from last time
session_start();
// Get the object out
$object = $_SESSION['object'];
// Prints "something"
print $object->value;
By using the PHP sessions you can save data across many pages for a certain user. For example, maybe each user has a shopping cart object that contains a list of items they want to buy. Since you are storing that data in THAT USERS session only - each user can have their own shopping cart object that is saved on each page!
Another option if you dont want to use sessions is to serialize your object and send it through a $_POST value in your AJAX call. Not the most elegant way to do it, but a good alternative if you don't want to use sessions.
See Object Serialization in the documentation for more informations.
mm, you should store in session, $_SESSION["someobj"] = $myobj;, and ensure that when you call the Ajax PHP file this includes the class necessary files which defines the class of $myobj and any contained object in it.
Could you be more specific? I can try.
This is how I create an object then assign it to a session variable:
include(whateverfilethathastheclassorincludeit.php)
$theObject = new TheObjectClass();
//do something with the object or not
$_SESSION['myobject'] = $theObject;
This is how I access the object's members in my Ajax call PHP file:
include(whateverfilethathastheclassorincludeit.php)
$theObject = $_SESSION['myobject'];
//do something with the object
If you don't want to move your object that is in your index.php, have your ajax make a request to index.php but add some extra parameters (post/get) that let your index.php know to process it as an ajax request and not return your normal web page html output.
You have not provided code, but what I guess is that you need to make your instantiated object global for other scripts to see it, example:
$myobject = new myobject();
Now I want to use this object elsewhere, probably under some function or class, or any place where it is not getting recognized, so I will make this global with the global keyword and it will be available there as well:
global $myobject;
Once you have the object, you can put it into the session and then utilize it in the Ajax script file.
As others have suggested, $_SESSION is the standard way to do it, in fact, that was one of the reasons, that sessions where invented to solve. Other options, i.e. serializing the object rely on the client side to hold the object and then return it untampered. Depending on the data in the object, it is not a good solution, as a) the object may include information that should not be available on the client side for security reasons and b) you will have to verify the object after receiving it.
That said, and if you still want to use the object on the client side, then JSON is an option for serializing object data, see JSON functions in PHP.
Based on most of the answers here, referring to storing the object in $_SESSION, is it more efficient to store only the individual properties that need to be accessed in AJAX as opposed to the whole object, or does it not matter?
E.g.
$_SESSION['object'] = $object;
vs
$_SESSION['property1'] = $object->property1;
$_SESSION['property2'] = $object->property2;
I know the OP is asking about accessing the entire object, but I guess my question pertains to if it's just a matter of only accessing certain properties of an object, and not needing to access methods of a class to alter the object once it's in AJAX.