Call action using Process.js - CRM - javascript

I have made custom workflow activity, registered it with Plugin Registration Tool and now i want to execute it using Action. Action wont have input/output parameters. Unique name is ad_opportunity. It will be executed from Custom Entity ad_productsamplerequest
I will call this action from JavaScript using Process.js.
I am not familiar with Process.js, so I have a problem to make Action call.
Here is the call I made, but it doesn't work. Am I missing something here:
Process.callAction("ad_opportunity",
[{
key: "Target",
type: Process.Type.EntityReference,
value: { id: Xrm.Page.data.entity.getId(), entityType: "ad_productsamplerequest" }
}],
function (params) {
//Success
},
function (e) {
// Error
alert(e);
}
);

Value mentioned in your code should be declared as EntityReference. Please refer below code for same
Process.callAction("mag_Retrieve",
[{
key: "Target",
type: Process.Type.EntityReference,
value: new Process.EntityReference("account", Xrm.Page.data.entity.getId())
},
{
key: "ColumnSet",
type: Process.Type.String,
value: "name, statuscode"
}],
function (params) {
// Success
},
function (e, t) {
// Error
});
Rest looks good

Related

PayPal Smart Buttons Error: "Expected order id to be passed"

i have a problem : I'm trying to figure out what it is since last friday, I can't find any good docs and no clues on the internet, I share some screenshots if anyone could help it would be awesome, by the way my problem is that when clicking on the paypal smart buttons that I integrated, i get in the console "expected an order id to be passed" unfortunately I can't find what is that order id thing
paypal.Buttons({
style: {
shape: 'rect',
color: 'gold',
layout: 'vertical',
label: 'pay',
},
// Sets up the transaction when a payment button is clicked
createOrder: function (data, actions) {
var cartArray = shoppingCart.listCart();
// Call your backend to create the Checkout Session
$.ajax({
data: {
id: cookie
},
type: "POST",
url: "create.php",
success: function (response) {
response = JSON.parse(response)
surname = []
surname = response.name.split(/(\s+)/).filter(e => e.trim().length > 0)
const Cart5 = [];
function Cart(description, name, unit_amount, quantity) {
this.description = description;
this.name = name;
this.unit_amount = {
value: unit_amount,
currency_code: 'EUR'
};
this.quantity = quantity;
this.category = 'PHYSICAL_GOODS';
}
cartArray.forEach(element => {
var item = new Cart(element.id, element.name, element.price, element.count);
Cart5.push(item);
})
JSON.stringify(Cart5);
orderid = makeid(12);
const paymentData = {
//authorization: 'AdhHUVsamn71V-Xs5JZVpzL4v6ElEKiYywV6PwF7rRwCwRQ-AZHMcLELmvQuWlS1pL19iiCbbZUIupTt',
intent: "CAPTURE",
env: "production",
application_context: {
brand_name: "Skunker",
locale: "fr-FR",
landing_page: "BILLING",
shipping_preference: "SET_PROVIDED_ADDRESS",
},
purchase_units: [{
reference_id: orderid,
custom_id: orderid,
description: 'Achat chez Skunker.Store',
invoice_id: orderid,
payer: {
email_address: response.email,
},
amount: {
currency_code: "EUR",
value: shoppingCart.totalCart() - (shoppingCart.totalCart() * sessionStorage.getItem('discount') / 100) + 6.15,
breakdown: {
item_total: {
currency_code: "EUR",
value: shoppingCart.totalCart()
},
tax_total: {
currency_code: "EUR",
value: 0.20
},
shipping: {
currency_code: "EUR",
value: 5.95
},
handling: {
currency_code: "EUR",
value: 0.00
},
insurance: {
currency_code: "EUR",
value: 0.0
},
shipping_discount: {
currency_code: "EUR",
value: 0.00
}
}
},
items: Cart5,
shipping: {
method: "La Poste - Colissimo",
address: {
name: {
given_name: surname[0],
surname: surname[1],
},
address_line_1: response.address,
admin_area_2: response.city,
postal_code: response.postalCode,
country_code: "FR"
},
phone_number: {
country_code: '33',
national_number: response.tel,
}
}
}]
}
return actions.order.create(paymentData);
}
})
},
// Finalize the transaction after payer approval
onApprove: function (data, actions) {
return actions.order.capture().then(function (orderData) {
// Full available details
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
// Show a success message within this page, e.g.
const element = document.getElementById('paypal-button-container');
element.innerHTML = '';
element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Successful capture! For dev/demo purposes:
$.ajax({
data: JSON.stringify(paymentData),
type: "POST",
url: "https://skunker.store/scripts/paid.php",
success: function (response) {}
})
// When ready to go live, remove the alert and show a success message within this page. For example:
// var element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
},
onError: function (err) {
console.log(err);
},
}).render('#payBtn');
And this is the error I get :
Error: Expected an order id to be passed
at https://www.sandbox.paypal.com/smart/buttons?style.label=pay&style.layout=vertical&style.color=gold&style.shape=rect&style.tagline=false&style.menuPlacement=below&components.0=buttons&locale.country=FR&locale.lang=fr&sdkMeta=eyJ1cmwiOiJodHRwczovL3d3dy5wYXlwYWwuY29tL3Nkay9qcz9jbGllbnQtaWQ9QVhTMWxLcXR2cjkzbDVkYlFPTE9nclJCYlNKMWt0cmNnYkpMZnJjRWEyckhING1ZYzVvWlQ1dmxpWUZDMnRobUFlcDVic1h4RmF1WEJ1cDMmY3VycmVuY3k9RVVSIiwiYXR0cnMiOnsiZGF0YS1zZGstaW50ZWdyYXRpb24tc291cmNlIjoiYnV0dG9uLWZhY3RvcnkiLCJkYXRhLXVpZCI6InVpZF9tdmh4dGh4aHhlYW13bHJzYXVna2dqeGRmcmpqenMifX0&clientID=AXS1lKqtvr93l5dbQOLOgrRBbSJ1ktrcgbJLfrcEa2rHH4mYc5oZT5vliYFC2thmAep5bsXxFauXBup3&sdkCorrelationID=f540177905bdc&storageID=uid_dbb0ba13c9_mtq6mzg6ndi&sessionID=uid_0e8f15ce50_mtq6ntq6nte&buttonSessionID=uid_1e5135ffcf_mtq6ntq6nte&env=sandbox&buttonSize=huge&fundingEligibility=eyJwYXlwYWwiOnsiZWxpZ2libGUiOnRydWUsInZhdWx0YWJsZSI6dHJ1ZX0sInBheWxhdGVyIjp7ImVsaWdpYmxlIjpmYWxzZSwibWVyY2hhbnRDb25maWdIYXNoIjoiZmQxNWMxYTBkNTFiYjBlMTRjODkxYTUzNDYwZTZiYWU1MDkyZmEzZCIsInByb2R1Y3RzIjp7InBheUluMyI6eyJlbGlnaWJsZSI6ZmFsc2UsInZhcmlhbnQiOm51bGx9LCJwYXlJbjQiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXJpYW50IjpudWxsfSwicGF5bGF0ZXIiOnsiZWxpZ2libGUiOmZhbHNlLCJ2YXJpYW50IjpudWxsfX19LCJjYXJkI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UiOmZhbHNlfSwicGF5dSI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJibGlrIjp7ImVsaWdpYmxlIjpmYWxzZX0sInRydXN0bHkiOnsiZWxpZ2libGUiOmZhbHNlfSwib3h4byI6eyJlbGlnaWJsZSI6ZmFsc2V9LCJtYXhpbWEiOnsiZWxpZ2libGUiOmZhbHNlfSwiYm9sZXRvIjp7ImVsaWdpYmxlIjpmYWxzZX0sIm1lcmNhZG9wYWdvIjp7ImVsaWdpYmxlIjpmYWxzZX19&platform=desktop&experiment.enableVenmo=false&experiment.disablePaylater=false&experiment.enableVenmoAppLabel=false&flow=purchase&currency=EUR&intent=capture&commit=true&vault=false&renderedButtons.0=paypal&renderedButtons.1=card&debug=false&applePaySupport=false&supportsPopups=true&supportedNativeBrowser=false&allowBillingPayments=true:1338:178001
I tried putting only the amount into the data and it still doesn't work, I also tried to add an order ID but it doesn't work
This is a bit of a mess, you're doing an ajax call to a "create.php" on your server, but for some reason not calling the PayPal API from there (with the Checkout-PHP-SDK or similar), but are instead using that response to then create an order from the client-side (which is what actions.order.create does)
This doesn't make any real sense. If you are using a server, you should have two routes: create.php and capture.php?id=XXXXXXXXXXXXXXX" (use a JSON body parameter to fetch rather than GET URL string, if desired) both of which communicate with the PayPal API themselves, to create and capture an order respectively. It does not make sense to combine your own server operations with JS SDK client-side methods.
So, you should switch over completely to this server pattern example: https://developer.paypal.com/demo/checkout/#/pattern/server , and in each of the respective routes that are called (create.php / capture.php or similar) you can either write your own HTTPS calls for the PayPal API, or use the Checkout-PHP-SDK to abstract them as desired, and return the JSON response to the fetch caller.
I do not recommend trying to get what you have to work, but the main reason it is not working is a failure to return a JavaScript Promise properly. You are invoking an asynchronous $.ajax and not returning anything after doing so, hence the error "Expected an order id to be passed" since you actually returned nothing (even though you think you did); in reality you just spun off an asynchronous $.ajax to do its own thing and that function's result is never fed back (nor would it be if you returned its result, since it uses a callback rather than promises).
The simplest way to get a promise when calling your own server routes is to use fetch instead of $.ajax, then you can just return the result of the fetch. It is theoretically possible to turn a $.ajax callback into a promise and return that, but I would not spend any time on this if I were you; the built-in browser fetch creates a promise for you and is preferred in modern JS.

Get data in json using javascript and datatables

I have a javascript as below, which can fetch the data from backed in json format. But How can i pass it to another function , i.e datatables to populate it
<script>
var returndata;
$.getJSON("/api/dashboard_data/", success);
function success(data) {
returndata = data;
window.alert(returndata);
return returndata;
// do something with data, which is an object
}
$(document).ready(function() {
$('#example').DataTable( {
data: returndata,
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
]
} );
} );
</script>
In above code in window.alert(returndata), i get the json data which has been returned from backed.
But the same variable "returndata" when i use it in function ready it is empty. How can i get it in ready function.
You are calling two asynchronous functions here. $.getJSON() and $(document).ready(). It looks that ready() is faster than getJSON() which means returndata is empty when you try to fill your data table.
Try this to make sure you have always the correct order:
<script>
$(document).ready(function() {
$.getJSON("/api/dashboard_data/", function(returndata) {
$('#example').DataTable( {
data: returndata,
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
]
});
});
});
</script>
Firstly, which jQuery plugin are you using for DataTables? Is it this one? The first thing I would do would be to put everything inside the $document.ready() as the documentation demonstrates. This ensures that all your code executes after the DOM is ready. Let me know what happens after that.
Also this part of the documentation could help if you are using the DataTables API. It could be as simple as a misspelling depending on what you're trying to do as quoted from the docs here:
The result from each is an instance of the DataTables API object which has the tables found by the selector in its context. It is important to note the difference between $( selector ).DataTable() and $( selector ).dataTable(). The former returns a DataTables API instance, while the latter returns a jQuery object.
I know this is not a good solution, just a hack. You can use window.setInterval or window.setTimeout function to check for data and execute the required function. Don't forget to clear the interval.
Follow the Datatables documentation: https://datatables.net/examples/server_side/simple.html
You'll have to do something like this:
$('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": _getData(),
"columns": [
{title: "Action"},
{title: "Input"},
{title: "State"},
{title: "Completed"},
{title: "Project"}
]
});
function _getData(data, callback) {
$.getJSON("/api/dashboard_data/", success);
function success(data) {
// you'll probably want to get recordsTotal & recordsFiltered from your server
callback({
recordsTotal: 57,
recordsFiltered: 57,
data: data
})
}
}
I haven't tested this code, but this should guide you in the right direction :)

Sencha touch store - phantom data

I created a model like
Ext.define('MyApp.model.ContainerDetailsModel', {
extend: 'Ext.data.Model',
alias: 'model.ContainerDetailsModel',
config: {
fields: [
{
name: 'id',
allowNull: false,
type: 'string'
},
{
name: 'container_types_id',
type: 'string'
}
]
}
});
and a store like this
Ext.define('MyApp.store.ContainerDetailsStore', {
extend: 'Ext.data.Store',
requires: [
'MyApp.model.ContainerDetailsModel'
],
config: {
model: 'MyApp.model.ContainerDetailsModel',
storeId: 'ContainerDetailsStore',
proxy: {
type: 'ajax',
enablePagingParams: false,
url: 'hereIsServiceUrl',
reader: {
type: 'json'
}
}
}
});
Now somewhere in application I tried to get one record like:
var detailsStore = Ext.getStore("ContainerDetailsStore");
detailsStore.load();
var detailsRecord = detailsStore.last();
But it gaves me undefined. The json returned by service is ok, it use it in different place as source for list. I already tried to change allowNull to true, but there is no null id in source. I tried set types to 'int' with the same result.
So I have tried
console.log(detailsStore);
Result is like this (just important values):
Class {
...
loaded: true,
data: Class {
...
all: Array[1] {
length: 1,
0: Class {
container_types_id: "1",
id: "726",
....
}
...
}
...
},
...
}
In the same place
console.log(detailsStore.data);
returns (as it should):
Class {
...
all: Array[1] {
length: 1,
0: Class {
container_types_id: "1",
id: "726",
....
}
...
}
but (next line)
console.log(detailsStore.data.all);
returns
[]
And it's empty array. When i try any methods from the store it says the store is empty.
I wrote console.log() lines one after another - so for sure it doesn't change between them (I try it also in different order or combinations).
My browser is Google Chrome 23.0.1271.97 m
I use Sencha from https://extjs.cachefly.net/touch/sencha-touch-2.0.1.1/sencha-touch-all-debug.js
How can I take a record from that store?
store.load() Loads data into the Store via the configured proxy. This uses the Proxy to make an asynchronous call to whatever storage backend the Proxy uses, automatically adding the retrieved instances into the Store and calling an optional callback if required. The method, however, returns before the datais fetched. Hence the callback function, to execute logic which manipulates the new data in the store.
Try,
detailsStore.load({
callback: function(records, operation, success) {
var detailsRecord = detailsStore.last();
},
scope: this
});

Error adding MixedCollection component to extjs form

I am trying to dynamically build a extjs form and when I try to add the dynamically built MixedCollection object to the form I get a TypeError: e.mixins.elementCt is undefined error.
<div id="form-#pageSpecificVar" class="grid-container even"></div>
<script>
Ext.define('HeaderForm', {
extend: 'Ext.form.Panel',
initComponent: function () {
var me = this;
Ext.applyIf(me, {
id: Ext.id(),
defaultType: 'textfield',
items: [{
xtype: 'container',
items: [{
xtype: 'textfield',
fieldLabel: 'Test'
}]
}]
});
me.callParent(arguments);
}
});
// Define our data model
Ext.define('HeaderModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'FieldA', type: 'int' }
]
});
var store = Ext.create('Ext.data.Store', {
model: 'HeaderModel',
proxy: {
type: 'ajax',
actionMethods: { create: 'POST', read: 'GET', update: 'POST', destroy: 'POST' },
url: '#Url.Content("~/Test/Header")',
timeout: 1200000,
listeners: {
load: function () {
}
}
}
});
store.load({
scope: this,
callback: function (records, operation, success) {
var form = new HeaderForm();
var formItems = new Ext.util.MixedCollection();
Ext.each(records[0].fields.items, function (item) {
console.log(item);
formItems.add(new Ext.form.DisplayField({
fieldLabel: 'Test'
}));
}, this);
console.log(formItems);
form.add(formItems);
form.loadRecord(records[0].data);
form.render('form-#pageSpecificVar');
}
});
</script>
Another thing I don't understand is, when I put the function inside the load listener, nothing happens. So I had to resort to using the callback event.
Update:
form.add method takes a component or component array, so instead of adding MixedCollection type I refer to formItems.items to add the array of displayfields components.
But for some reason the store listeners load is not getting triggered when store.load is executed, does anyone see a problem with that?
Nevermind this... I figured out... I placed the listener instead of the proxy instead of the store.
Q2
Also something weird is that during the callback method of store.load, the records is not return with the loaded values.
Nevermind this... I figured out... It was the json object I'm passing. Forgot to take it out of the error/data structure for form.
Thanks
MixedCollection isn't an accepted parameter for add, you need to use an array. This info is in the docs.

Entity in context in JayData is undefined

I wrote this code to use WebSQL with JayData in Chrome:
$data.Entity.extend("$org.types.Department",
{
Id: { type: "int", key: true, computed: true },
Name: { type: "string", required: true }
});
$data.EntityContext.extend("$org.types.OrgContext", {
Department: { type: $data.EntitySet, elementType: $org.types.Department }
});
$org.context = new $org.types.OrgContext({ name: "WebSQL", databaseName:"Organization",
dbCreation: $data.storageProviders.sqLite.DbCreationType.DropTableIfChanged
});
var department = new $org.types.Department({ Name: 'Department1' });
$org.context.Department.add(department);
$org.context.saveChanges();
but the problem is that, in $org.context.Department.add(department); line, "Department" is undefined.What should I do?
The problem was: the $data WebSQL provider name is: webSql, this way the example worked perfectly. Plus of course the onReady handler was needed.
You have to use the onReady function of the context. When you try to add the new Department entity to the entity set the context is not yet initialized. Use is like this:
$org.context.onReady(function(db){
var department = new $org.types.Department({ Name: 'Department1' });
db.Department.add(department);
db.saveChanges(function(){
...
});
});
It's recommended to always use the callback functions because everything is asynchronous and you don't know that the process is ready outside of the callback.

Categories

Resources