New object not appearing in Parse data browser - javascript

I want a new userCategory object to be created when a user signs up in my iOS app. I figured the best way to do this would be to call a Parse cloud code function once signup is successful that triggers the creation of the object. When I check Parse's databrowser however, the new user is created, but a new userCategory associated with the user isn't.
objective-c code:
// Sent to the delegate when a PFUser is signed up.
- (void)signUpViewController:(PFSignUpViewController *)signUpController didSignUpUser:(PFUser *)user {
[self dismissViewControllerAnimated:YES completion:NULL];
[PFCloud callFunctionInBackground:#"userCategoryCreate"
withParameters:#{}
block:^(NSNumber *ratings, NSError *error) {
if (!error) {
//userCategory created
}
}];
}
Cloud Code:
Parse.Cloud.define("userCategoryCreate", function(request, response) {
// Simple syntax to create a new subclass of Parse.Object.
var UserCategory = Parse.Object.extend("UserCategory");
// Create a new instance of that class.
var userCategory = new UserCategory();
response.success("userCategory succesfully created!");
});

You should do something similar to:
// Simple syntax to create a new subclass of Parse.Object.
var UserCategory = Parse.Object.extend("UserCategory");
// Create a new instance of that class.
var userCategory = new UserCategory();
// set necessary fields for the new entry row ( if needed )
userCategory.set("categoryName","categoryFoo1");
...
..
.
// Then save the object
userCategory.save().then(function(savedObj){
response.success("userCategory succesfully created!");
},function(saveError){
response.error("Unable to create this object");
});
Hope it helps

Related

Sharepoint 2013 - User profiles JSOM

I have this part of code which should get me for example the "title" of the current user in Sharepoint, but everytime it gives me error: Common Language Runtime detected an invalid program.
<script type="text/javascript">
var personProperties;
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
function getUserProperties() {
// Replace the placeholder value with the target user's credentials.
// var targetUser = "domainName\\userName";
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
personProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(personProperties);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
// Get a property directly from the PersonProperties object.
var messageText = personProperties.get_userProfileProperties()['Title'];
alert(messageText);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
alert(args.get_message());
}
</script>
Do you have any ideas why it is happening?
Thank you for any suggestions.
Tom
You can make use of SP.SOD.executeFunc to load the files in the correct manner.
Try the below code:
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
// Make sure PeopleManager is available
SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', function() {
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
personProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(personProperties);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
// Get a property directly from the PersonProperties object.
var messageText = personProperties.get_userProfileProperties()['Title'];
alert(messageText);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
alert(args.get_message());
}
});
});

How to Parse values from some posts to a object id in a different class

I'm trying to make a connection of two classes in Parse.com via Pointer.
I have one class which is called magazia and I put some rows inside.
Also I have a class which is called "Events" which has a magaziaid column which is Pointer to class magazia.
I want to make a post in Events with a specific objectId of the other class ("magaziaid") from a form.
So I have this code for now:
function saveJobApp(objParseFile) {
var jobApplication = new Parse.Object("events");
var name = document.getElementById('name').value;
var description = document.getElementById('description').value;
var magaziid = "2xOhgyX0BU";
jobApplication.set("image", objParseFile);
jobApplication.set("name", name);
jobApplication.set("description", description);
jobApplication.set("magaziaid", this.magaziid.id); //breakpoint
jobApplication.save(null, {
success: function(gameScore) {
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
//var objectId = jobApplication.getObjectId();
// objectId = document.getElementById("objID").innerHTML;
// console.log(objectId);
}
$('#submitId').on("click", function(e) {
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
console.log("Done");
parseFile.save().then(
function() {
saveJobApp(parseFile);
},
function(error) {
alert("error");
}
);
});
});
That i'm trying to put the objectId copied from the "magazia" class, but i get an error, "Failed to create object with error code: Undefined"
What is my mistake here?
How can i pass the object id of a row from "magazia" class and put it on the pointer of the class "events" ???
Thanks in advance!
Update 1. in //breakpoint i have also tried those different codes
jobApplication.set("magaziaid", {__type: "Pointer", className: "events", objectId: magaziid});
and this one
jobApplication.set("magaziaid", magaziid);
Your pointer value should be a magazia object and not an id. Do the following and it should work.
var magaziaObject = new Parse.Object("magazia");
// add anything you want to magaziaObject
// like magaziaObject.id, magaziaObject.name, etc.
// and then save the magaziaObject in your events (jobApplication) object
jobApplication.set("magaziaid", magaziaObject);

Cannot create a pointer to an unsaved ParseObject

I am having troubles referring to a "User" object from inside a query. I have the following code:
Parse.Cloud.define("getTabsBadges", function(request, response) {
var UserObject = Parse.Object.extend('User');
var user = new UserObject();
user.id = request.params.userId;
// Count all the locked messages sent to the user
var receivedMessagesQuery = new Parse.Query('Message');
receivedMessagesQuery.equalTo('status', 'L');
receivedMessagesQuery.equalTo('toUser', user); // THIS LINE GENERATES THE ERROR
receivedMessagesQuery.count({
// more code here
});
});
I call the function using CURL but I always get the following error:
{"code":141,"error":"Error: Cannot create a pointer to an unsaved
ParseObject\n at n.value (Parse.js:14:4389)\n at n
(Parse.js:16:1219)\n at r.default (Parse.js:16:2422)\n at e.a.value
(Parse.js:15:1931)\n at main.js:9:25"}
I am using the exactly same code in another project, the only difference is that instead of counting objects I find them and its works correctly. I have also verified that the tables have a column type of Pointer<_User> in both projects. What's causing the problem?
The error message Cannot create a pointer to an unsaved means that you are trying to use an object which does not exist in the Parse DB.
With var user = new UserObject();, you're creating a new user object. You cannot use it in a query until you save it to Parse.
Instead of creating a new User object and setting it's objectId, do a query for the User object. See code below:
Parse.Cloud.define("getTabsBadges", function(request, response) {
var UserObject = Parse.Object.extend('User');
var query = new Parse.Query(UserObject);
query.get(request.params.userId, {
success: function(user) {
// Count all the locked messages sent to the user
var receivedMessagesQuery = new Parse.Query('Message');
receivedMessagesQuery.equalTo('status', 'L');
receivedMessagesQuery.equalTo('toUser', user); // THIS LINE GENERATES THE ERROR
receivedMessagesQuery.count({
// more code here
});
},
error: function(error) {
// error fetching your user object
}
});
});
Your request.params.userId may be undefined or null, which causes this error.
Your query constraints cannot compare the Parse Object that is created without data (createWithoutData()) using undefined or null as its objectId.

JSON stringify and then parse works unexpectedly for the object with local variable

Why JSON stringify and then parse is not working for this object. Is it works bad for objects with local variables?
function Task(description) {
var _description = description;
this.getDescription = function() {
return _description;
}
}
var task = new Task('wash car');
console.log(task.getDescription());
var json = JSON.stringify(task);
console.log(JSON.parse(json).getDescription());
JSON can't stringify functions (and it's not supposed to be able to).
But technically when you need to Stringify an object you should not need the functions. You can just pass the object as is within your application.
EDIT:
If what you need is the object to be stored locally then saving the functions along with it would not be a good idea anyway. What you can do is store the properties of the object and create a new instance when you retrieve it.
It isn't possible to stringify an instance of a constructor and for it to still be an instance of the constructor after turning it back into an object.
Instead, you would need to give the Task instance a method that outputs a json string that you can store, then when you want it to be an instance of Task again, you can create a new instance.
function Task(description) {
var _description = description;
this.getDescription = function() {
return _description + '(possibly modified?)';
}
this.stringify = function () {
return JSON.stringify({
description: this.getDescription(),
_description: _description
});
}
}
var task = new Task('wash car');
console.log(task.getDescription()); // 'wash car (possibly modified?)'
var json = task.stringify();
console.log(json); // {"description": "wash car (possibly modified?)", "_description": "wash car"}
var taskAgain = new Task(JSON.parse(json)._description);
console.log(taskAgain.getDescription()); // 'wash car (possibly modified?)'
I added the " (possibly modified?)" to demonstrate why it is important to pass both the result of getDescription and the string stored in _description. if getDescription never changes the description, there is no need to have getDescription in the first place which greatly simplifies this whole process.
function Task(description) {
this.description = description;
}
var task = new Task('wash car');
console.log(task.description); // wash car
var json = JSON.stringify(task);
console.log(json); // {"description": "wash car"}
console.log(JSON.parse(json).description); // wash car
var taskAgain = new Task(JSON.parse(json).description);
console.log(task.description); // wash car

Obtain Data from two parse classes based on column in one table

I have to Parse Classes in my data browser, 'Details' and 'Content'. The 'Details' class has the following --> 'objectId', 'uuid' and 'proximity'. The 'Content' class has 'objectId', 'descId' and 'offer'.
I have created a web UI using the Javascript SDK so when the user enters the uuid, proximity and offer, uuid and proximity get stored in the 'Details' class, on success I then get the objectId of the newly created object. I then store that objectId in the 'Content' class under descId and the offer that was inputted by the user.
My problem is I have a html table that I need to populate, so I need to pull the data from both classes. The uuid and proximity from 'Details' and the offer from 'Content' so I need to do this in one query. This is my reason for storing the 'Details' objectId in the 'Content' class as a type of foreign key.
I am stuck at this cross roads and have tried include etc but I am just trying things and I'm not sure what I need to do. If anyone can help, perhaps show me a sample, I'd greatly appreciate it
Here is my js save code:
//Creating Beacon Content Parse Object
var iBeaconContent = Parse.Object.extend("Content");
var beaconContent = new iBeaconContent();
//Creating Object to save to iBeacon Description Table
var iBeaconDescription = Parse.Object.extend("Details");
var beaconDescription = new iBeaconDescription();
beaconDescription.set("uuid", tdUuid.children("input[type=text]").val().toString());
beaconDescription.set("proximity", parseInt(tdProximity.children($('prox')).val().toString()));
beaconDescription.save(null, {
success: function(beaconDescriptionObject) {
var query = new Parse.Query("Details");
query.equalTo("uuid", tdUuid.children("input[type=text]").val().toString());
query.find({
success: function(results) {
objectId = results[0].id;
beaconContent.set("descId", objectId);
beaconContent.set("offer", tdOffer.children("input[type=text]").val().toString());
beaconContent.save(null, {
success: function(object) {
document.location.reload(true);
}, error: function(beaconContent, error) {
}
});
}
});
},
error: function(error) {
}
});
NEW JAVASCRIPT
var BeaconDetail = Parse.Object.extend("Details");
var BeaconContent = Parse.Object.extend("Content");
var innerQuery = new Parse.Query(BeaconDetail);
innerQuery.exists("descId");
var query = Parse.Query(BeaconDetail);
query.matchesQuery("objectId", innerQuery);
query.find({
success:function(beaconContent){
alert("Success----lenght: " + beaconContent.length);
}
})
Sound like you need to use a compound query or relationship query. Here are some links
https://docs.parseplatform.org/js/guide/#relational-queries
https://docs.parseplatform.org/js/guide/#compound-queries
https://parse.com/questions/compound-relational-queries
An example of a query from two classes is as follows
It would also be good to see the code, would help give a more relative answer.
CODE
var lotsOfWins = new Parse.Query("Player");
lotsOfWins.greaterThan("wins", 150);
var fewWins = new Parse.Query("Player");
fewWins.lessThan("wins", 5);
var mainQuery = Parse.Query.or(lotsOfWins, fewWins);
mainQuery.find({
success: function(results) {
// results contains a list of players that either have won a lot of games or won only a few games.
},
error: function(error) {
// There was an error.
}
});
If I understand correctly, your Content class contains a pointer to your Details class in the descId property, and you want to be able to query based on some Details fields and return both objects?
NOTE: I must point out that descId is a very poorly named property that will just cause confusion. If it is a pointer, just give it a name like desc, leave off the Id suffix.
Anyway, if that is what you want:
var query = new Parse.Query("Content");
var uuid = tdUuid.children("input[type=text]").val().toString();
var proximity = parseInt(tdProximity.children($('prox')).val().toString());
// consider logging those two variable to confirm they're what you want
// query properties of a pointer
query.equalTo("descId.uuid", uuid);
query.equalTo("descId.proximity", proximity);
// include the pointer in the output
query.include("descId");
query.find({
success: function(beaconContent) {
alert("Success -- length: " + beaconContent.length);
// sample output of first result:
var content = beaconContent[0];
var detail = content.get("descId");
console.log("uuid", detail.get("uuid"));
console.log("proximity", detail.get("proximity"));
console.log("offer", content.get("offer"));
}
});

Categories

Resources