Error while executing showtoast in salesforce lightning - salesforce

Below code throws an error while executing toastEvent.setParams statement. Not sure what I have missed or is it deprecated in spring'19 ?
loadContacts : function(cmp) {
var action = cmp.get("c.getContacts");
action.setCallback(this, function(response){
var state = response.getState();
if (state === 'SUCCESS') {
cmp.set('v.contacts', response.getReturnValue());
cmp.set('v.contactList', response.getReturnValue());
this.updateTotal(cmp);
}
console.log('Here');
var toastEvent = $A.get("e.force:showToast");
if (state === 'SUCCESS') {
toastEvent.setParams({
"title" : 'Success!',
"message" : 'Your contacts have been loaded successfully.'
});
}
else {
toastEvent.setParams({
"title" : "Error!",
"message" : "Something has gone wrong."
});
}
toastEvent.fire();
});
$A.enqueueAction(action);
},
Here is the screenshot of the error:

You can use lightning:notificationsLibrary. In your aura component, add:
<lightning:notificationsLibrary aura:id="notifLib"/>
And change your helper method to:
loadContacts : function(cmp) {
var action = cmp.get("c.getContacts");
action.setCallback(this, function(response){
var state = response.getState();
if (state === 'SUCCESS') {
cmp.set('v.contacts', response.getReturnValue());
cmp.set('v.contactList', response.getReturnValue());
this.updateTotal(cmp);
}
console.log('Here');
var toastEvent = $A.get("e.force:showToast");
if (state === 'SUCCESS') {
cmp.find('notifLib').showToast({
"title" : 'Success!',
"message" : 'Your contacts have been loaded successfully.'
"variant": 'success',
"mode": 'sticky'
});
}
else {
cmp.find('notifLib').showToast({
"title" : "Error!",
"message" : "Something has gone wrong."
"variant": 'error',
"mode": 'sticky'
});
}
});
$A.enqueueAction(action);
},

From the docs:
This event is handled by the one.app container. It’s supported in Lightning Experience, Salesforce app, and Lightning communities.
That error will pop up when you attempt to grab $A.get("e.force:showToast") outside of the one.app container context (e.g., if you have your component in a Lightning App for testing instead of dragging it on to a record page in the builder). $A.get("e.force:showToast") comes back as undefined, and calling setParams on undefined throws the error.
Try dragging your component onto a record detail page or a community, or create a tab from the Lighting component. If you need to use the component outside of the one.app context, you'll need to implement the show/hide toast logic yourself.

Related

Callback not working in request npm

I have some problems with the callback when I'm using Request npm.
My project is an API for the users developed by Sailsjs, on the other hand I'm using reactjs for the front-end, and I'm using Request npm to communicate with the API.
I have some issues with the callback.
My code :
handleClick(event) {
var apiBaseUrl = "http://localhost:1337/user";
if (
this.state.first_name.length > 0 &&
this.state.last_name.length > 0 &&
this.state.email.length > 0 &&
this.state.password.length > 0
) {
request.post({url : apiBaseUrl + "/store", form :{
first_name: this.state.first_name,
last_name: this.state.last_name,
email: this.state.email,
password: this.state.password
}}, function(response) {
console.log(response);
if (response.data.code === 200) {
var loginscreen = [];
loginscreen.push(
<Login
parentContext={this}
appContext={this.props.appContext}
key = {rand}
/>
);
var loginmessage = "Not Registered yet.Go to registration";
this.props.parentContext.setState({
loginscreen: loginscreen,
loginmessage: loginmessage,
buttonLabel: "Register",
isLogin: true
});
} else {
console.log("some error ocurred", response.data.code);
}
});
} else {
alert("Input field value is missing");
}
}
The post request is doing well, when I'm checking the database I found the user saved and the response in networking onglet in chrome is good, but when I do console.log(response) it's always null. I don't know if my callback isn't right, or if it's something else.
form
http response
variables in response
Error
Back-end
// Store user
store: function(req, res) {
var params = _.extend(req.query || {}, req.params || {}, req.body || {});
console.log(params);
UserService.store(params, function(err, user) {
if (err) return res.json();
if (!user) return res.json();
return res.send({
"code": 200,
"success": "user registered sucessfully"
});
});
},
Can you help me to fix this problem?
Actually, the problem is on your callback, the callback takes two arguments , it should be like this :
function(error, response) {.....}
the error is the first argument and the response is the second, you are getting null because there is no error ! and the response was treated as the error object.

Parse push notification with ionic

I am trying to set up a push notification with parse to handle received notifications.
I used phonegap-parse-plugin plugin and was able to set it up correctly.
My problem with it is that I cannot handle the received notifications. I would like to redirect a user to a the page for the notification based on the notification json params.
So, I decided to switch to parse-push-plugin, but my problem with it is that I cannot even get it to show the alert registered box; it cannot even find the ParsePushPlugin method.
I followed the tutorial which is simple enough and added this to my app.js file
ParsePushPlugin.register(
{ appId:"xxx", clientKey:"xxx", eventKey:"myEventKey" }, //will trigger receivePN[pnObj.myEventKey]
function() {
alert('successfully registered device!');
},
function(e) {
alert('error registering device: ' + e);
});
ParsePushPlugin.on('receivePN', function(pn){
alert('yo i got this push notification:' + JSON.stringify(pn));
});
The alert success just failed to show so I guess it is not working or I am not doing the right thing.
Use phonegap-plugin-push. It is easy to implement and use.
Config :
var push = PushNotification.init({
"android": {
"senderID": "Your-sender-ID",
"forceShow": true, // To show notifications on screen as well
"iconColor": "#403782",
"badge": "true",
"clearBadge": "true" // To clear app badge
},
"ios": {
"alert": "true",
"badge": "true",
"clearBadge": "true",
"sound": "true",
"forceShow": "true"
},
"windows": {}
});
Device Registration :
push.on('registration', function(data) {
localStorage.setItem('pushToken', data.registrationId); // Save registration ID
});
Handle Notifications
push.on('notification', function(data) {
console.log(data);
// Handle all requests here
if (data.additionalData.$state == "mystate") {
$state.go('app.conversations');
}
})

Express + Angular update route: Error: Cannot PUT

I'm trying to update a schema using form, however, both on app.put and app.post (which I've seen as a possible solution) i get
PUT https://myapp-demo.herokuapp.com/api/events/5523da4d97c5000300f6e713 404 (Not Found)
and error from ajax callback
Error: Cannot PUT /api/events/5523da4d97c5000300f6e713
on clientside, I make this request:
$scope.saveEvent = function(id) {
$http.put('../api/events/' + id, $scope.formData)
.success(function (data) {
$scope.events = data;
})
.error(function(data) {
console.log('Error: ' + data);
})
};
In express routes, I do this:
app.put('../api/events/:id', function (req, res){
var user = req.user;
var id = req.params.id;
var update = {
$set: {
title: req.body.title,
description: req.body.description,
}
};
Event.findByIdAndUpdate(id, update, function (err, event) {
if(!event) {
res.statusCode = 404;
return res.send({ error: 'Not found' });
}
console.log("event updated");
Event.find(function(err, events) {
if (err){
res.send(err)
};
res.json(events);
});
});
});
I tried to pass event._id differently, by using req.params.id and passing id with form like req.body.id, it all leads to the same result. I've also read about creating hidden input for helping method-override to override form methods. However, having this didn't help.
<input type="hidden" name="_method" value="put">
<md-button class="md-raised md-primary" ng-click="saveEvent(eventId)">Save</md-button>
UPDATE
Indeed, the initial proble was in my put route. I've found a new problem now. When I try to update it again, I get
Error: Object {error: "Not found"}
It happens even after I refresh page or restart server.
The following is invalid:
app.put('../api/events/:id'...
It needs to be in reference to the namespace, or in your case the root:
app.put('/api/events/:id'...

Turn request success into error based on response data

I am relatively new to Angular js and trying to use promises along with services and got reference http://plnkr.co/edit/b4HPbX2olM745EfHVcc6?p=preview. But in my application I am getting response as {"Response":"exception while loading Reports List","error":"Exception getting all records.","status":"failure"}. When I get response like this, I need to show an alert message with the message in "error" (i.e., Exception getting all records) and set $scope.data to [] in my controller.What are the changes I need to make to services and controller to handle this. Any help is much appreciated.
In services :
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
In Controller,
DashboardsDataService.getNetSpendOverTimeData()
.then(function(data) {
$scope.data = data;
});
The following is my original request to Java action class:
var originalRequest = $.ajax({
async : false,
url : "/dash2/dashd2ajax.do",
type : "POST",
data : {
action : 'getNetSpendOverTime',
customerId : selectedAccTd,
carriersId : selectedCarriers,
fromDate : fromDate,
toDate : toDate,
modes : selectedModes,
services : selectedServices,
dateType : selectedDateType,
lanesList : selectedLaneList
},
dataType : "json"
});
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
If what you're asking is "how do I turn request success into a failure based on result data", then take a look at the following example:
return $q.when(originalRequest).then(function (res) {
if (res.ResultSet.error) {
return $q.reject(res.ResultSet.error);
} else {
return res.ResultSet.Response;
}
});
Using $q.reject() turned your data into a real "promise failure", so in your controller, you can use the normal promise API:
doSomethingAsynchronous().then(function (data) {
$scope.data = data;
}, function (error) {
$scope.data = [];
alert(error);
});

Show json returned message in a div after each ajax response , extjs4 grid

I have a gridpanel , a Model, an autosync Store with an ajax proxy with read and update functions and a RowEditing plugin in extjs4 .
Consider the following json:
{ "success": true,"Message":"Grid Data Successfully updated.", "users": {"uname":"jdoe","fname":"John","lname":"Doe","SSN":125874,"mail":"jdoe#example.org"},{"uname":"jsmith","fname":"Jack","lname":"Smith","SSN":987456,"mail":"smith#example.com"}}
I want to know if there is a way to render the value of "Message" to an HTML div tag (my_div for example) after receiving each response?
You can use the DOM Helper, see the sencha api : http://docs.sencha.com/ext-js/4-0/#!/api/Ext.DomHelper
Ext.onReady(function(){
Ext.DomHelper.insertHtml('beforeBegin', Ext.getDom('test'), "Prepend this string");
});​
Above code will get the HTML element with ID test and it will insert the string Prepend this string beforeBegin of the content of this div.
See the fiddle to play around: http://jsfiddle.net/PddU4/Prepend this string
EDIT 2012-02-16:
You need to listen to your proxies success and failure: (you could also implement a listener when loading your store or on update)
listeners: {
success: function( response, options ){
console.log(response);
},
failure: function( response, options ){
console.log(response);
},
}
EDIT BASED ON YOUR COMMENT:
First make sure you configured properly your successProperty and messageProperty in your reader. Then implement the listener where you want it to be, update, remove, add, exception etc. :
(configure the listener within your proxy object)
listeners : {
update : function(thisStore, record, operation ) {
console.log('Update happened');
console.log(record);
console.log(operation);
},
save : function() {
console.log('Save happened');
},
exception : function(dataproxy, type, action, options,response, arg) {
console.log('Error happened');
console.log(response);
doJSON(result.responseText);
},
remove : function() {
console.log("Record removed");
}
}
When you console.log(response), you will see the response object. This would be your actual JSON so you need to parse it (as in doJSON() method):
function doJSON(stringData) {
try {
var jsonData = Ext.util.JSON.decode(stringData);
Ext.MessageBox.alert('Success', 'Your server msg:<br />jsonData.date = ' + jsonData.message);
}
catch (err) {
Ext.MessageBox.alert('ERROR', 'Could not decode ' + stringData);
}
}
Please check out this AJAX tutorial: http://www.sencha.com/learn/legacy/Manual:Core:Ext.Ajax

Resources