How to pass a variable to app in Zendesk - javascript

I'm experimenting with Zendesk apps but I'm having an issue passing variables / an array of json objects from my app into the view. I did the getting started tutorials and looked at the API but I can't seem to find an answer.
Here is what I have:
this.ajax('fetchExternalData', myURL).done(function(data) {
this.switchTo('requester', data);
});
but whenever I try to access data in the app, it says it's undefined (data is an array of objects here).
I even tried something like:
this.ajax('fetchExternalData', myURL).done(function(x) {
this.switchTo('requester', x);
});
Where x is just some plain text.
if I do:
this.ajax('fetchExternalData', myURL).done(function(data) {
data = data[0];
this.switchTo('requester', data);
});
I can access properties in data by their name (eg. {{CustomerName}}) but I still can't reference the data var itself.

According the Zendesk site :
this.switchTo('hello', {username: currentUser});
The first argument specifies the template to render, hello, which references the hello.hdbs file in the templates folder. The second argument specifies the data to pass to the template, expressed as a JavaScript object literal, {username: currentUser}. The current user's name is passed to the template to be displayed in the user interface.
So just try like that :
this.ajax('fetchExternalData', myURL).done(function(data) {
//this.switchTo('requester', data);
this.switchTo('requester', {data : data} );
});
I hope this will resolve your issue !

Related

Using Xrm.WebApi method in Web Resource opened in a new window

I have opened an HTML web resource in a new window using:
Xrm.Navigation.openWebResource(webResource, windowOptions, data);
This is an HTML web resource and it is loading the ClientObject in the head
<script type="text/javascript" src="../../../ClientGlobalContext.js.aspx" ></script>
then I have some JavaScript that is trying to retrieve a Contact
var contactId = "8553DA63-11C9-E711-A824-000D3AE0CB84";
var promise = Xrm.WebApi.retrieveRecord("contact", contactId, "$select=contactid,firstname,lastname");`
but this is failing. I've step-traced into the Xrm.WebApi method and found the error is when it attempts to resolve "contact" to a Set Name
Code from Global.ashx
getEntitySetName: function(logicalName) {
Mscrm.Utilities.addTelemetryLog("Xrm.Utility.getEntitySetName");
var $v_0 = window.ENTITY_SET_NAMES || window.top.ENTITY_SET_NAMES;
if (IsNull(this.$5H_1) && !isNullOrEmptyString($v_0))
this.$5H_1 = JSON.parse($v_0);
return this.$5H_1[logicalName.toLowerCase()]
},
For some reason the window.ENTITY_SET_NAMES object is null so an error (null reference) occurs
I've tried embedding my web resource into a CRM page and the code works correctly. The issue seems to be when the web resource is launched via Xrm.Navigation.openWebResource
Has anyone tried to use Xrm.WebApi in the context of an web resource opened with Xrm.Navigation.openWebResource? or does anyone know if there are additional steps required to retrieve data?
Update
ENTITY_SET_NAMES is initialised in main.aspx.
I tried embedding my custom Web Resource directly into a new Main Form section and the retrieveRecord method works.
It appears this is a problem only when running the Web Resource from a new page via Xrm.Navigation.openWebResource
Update 2 - Response to Aron
I tried using window.parent as suggested below
var contactId = "8553DA63-11C9-E711-A824-000D3AE0CB84";
var promise = parent.Xrm.WebApi.retrieveRecord("contact", contactId, "$select=contactid,firstname,lastname");`
and for good measure also tried window.parent.top
var contactId = "8553DA63-11C9-E711-A824-000D3AE0CB84";
var promise = parent.top.Xrm.WebApi.retrieveRecord("contact", contactId, "$select=contactid,firstname,lastname");`
but both resulted in the same error
Sounds like a product bug within ClientGlobalContext.js.aspx, as this should give you whole context to work with.
Probably you can utilize window.opener.Xrm in this scenario, since it worked for window.opener.Xrm.Page.getAttribute it should also work for Xrm.WebApi.
You can try to access variable from opener window like this:
window["ENTITY_SET_NAMES"] = window["ENTITY_SET_NAMES"] || window.opener.top.ENTITY_SET_NAMES;
My blog :)
To get this working I have implemented a hacky work-around.
I've been debugging the Xrm.WebApi method and it is failing on a line where it attempts to take the entityname and resolve it to the setname (plural). It does this by comparing the value passed into the retrieveRecord method and comparing it to a global variable ENTITY_SET_NAMES
In my example, it is trying to resolve contact to contacts
This variable is unfortunately not present and Xrm.WebApi throws an error
My work-around is to check for this variable, and if it is not present then create it! ENTITY_SET_NAMES is a JSON-parsable string which contains the logical name and set name for each entity.
window["ENTITY_SET_NAMES"] = window["ENTITY_SET_NAMES"] || JSON.stringify({
"account" : "accounts",
"contact" : "contacts"
});
Executing this line before any calls to Xrm.WebApi methods appears to work and I now get results
Here's the complete snippet:
window["ENTITY_SET_NAMES"] = window["ENTITY_SET_NAMES"] || JSON.stringify({
"account" : "accounts",
"contact" : "contacts"
});
var contactId = "8553DA63-11C9-E711-A824-000D3AE0CB84";
Xrm.WebApi.retrieveRecord(
"contact",
contactId,
"$select=contactid,firstname,lastname"
).then(
function success(result) {
console.log(result.firstname);
// perform operations on record retrieval
},
function (error) {
console.log(error.message);
// handle error conditions
}
);
As per this article, when referencing the main form from a Web Resource we have to reference the parent window. Though, it only references Xrm.Page and Xrm.Utility, it should also work with Xrm.WebApi...
An HTML web resource added to a form can’t use global objects defined by the JavaScript library loaded in the form. An HTML web resource may interact with the Xrm.Page or Xrm.Utility objects within the form by using parent.Xrm.Page or parent.Xrm.Utility, but global objects defined by form scripts won’t be accessible using the parent.
Please try parent.Xrm.WebApi.retrieveRecord("contact", contactId, "$select=contactid,firstname,lastname");
This article also demonstrates parent.Xrm.WebApi
If you are going to use bound actions & functions you'll also need to add a similar variable to map entities to their primary id fields.
window["ENTITY_PRIMARY_KEYS"] = ['{"account":"accountid", "contact":"contactid"}'];
Try using opener.Xrm to access the Xrm object in a standalone webresource opened from a form as described here in the parent.Xrm section: https://learn.microsoft.com/en-us/power-platform/important-changes-coming#some-client-apis-are-deprecated
"If the getContentWindow method doesn't work, you can use parent.Xrm to get to the Xrm object inside an HTML web resource. If the HTML web resource is opened in a new window, then you should use opener.Xrm instead."
var contactId = "8553DA63-11C9-E711-A824-000D3AE0CB84";
var promise = opener.Xrm.WebApi.retrieveRecord("contact", contactId, "$select=contactid,firstname,lastname");

node.js does not recognise the url in the unfluff module

Any help will be appreciated.
I need to extract data from websites and found that node-unfluff does the job (see https://github.com/ageitgey/node-unfluff). There is two ways to call this module.
First, from command line which works!
Second, from node js which doesn't work.
extractor = require('unfluff');
data = extractor('test.html');
console.log(data);
Output : {"title":"","lang":null,"tags":[],"image":null,"videos":[],"text":""}
The data returns an empty json object. It appears like it cannot read the test.html.
It seems like it doesn't recognise test.html. The example says, "my html data", is there a way to get html data ? Thanks.
From the docs of unfluff:
extractor(html, language)
html: The html you want to parse
language (optional): The document's two-letter language code. This
will be auto-detected as best as possible, but there might be cases
where you want to override it.
You are passing a filename, and it expects the actual HTML of the file to be passed in.
If you are doing this in a scripting context, I'd recommend doing
data = extractor(fs.readFileSync('test.html'));
however if you are doing this in the context of a server or some time when blocking will be an issue, you should do:
fs.readFile('test.html', function(err, html){
var data = extractor(html);
console.log(data);
));

pass multiple params in services in angularjs

I'm using angularjs with wildfly v8.2. I have a problem when try to pass multiple params in services in angularjs using get rest services. I've got this error : "Bad arguments passed to org.jboss.resteasy.spi.metadata.ResourceMethod#7a3ab29a" ( null, java.lang.Integer 1 ). How do i pass multiple parameter using get in angularjs. Anyone..
Below is my codes:
services.js
authListing: function (id, page, succFn) {
return $http.get(services.path + 'student/listing', {params: {page: page, id: id}}).success(succFn).error(cmnSvc.errorHandler);
}
rest.java //endpoint
#Path("/listing")
#GET
public Response listing(#QueryParam("id") String id, #QueryParam("page") int page) {
//Some method here
}
You are making the call with Angular correctly. However, I suspect you are passing in either a null or undefined argument based on the error message:
"Bad arguments passed to
org.jboss.resteasy.spi.metadata.ResourceMethod#7a3ab29a" ( null,
java.lang.Integer 1 )
My guess is that your endpoint isn't meant to take a null value for id and that is why it is puking.
You should be able to figure this out pretty quickly by simply opening up the developer tools in your browser, and inspecting the XHR request made to the server.
If it looks something like this: student/listing?id=undefined&page=1 then you know you have a problem.

How to access an HTML template argument passed from controller in a Javascript function

My app is using the play framework mvc setup. In the controller I am passing a parameter while rendering the template, like this:
public static void scenario(){
...
render(active_brands);
}
Now in my HTML page "scenario.html", I can access the parameter using the play framework tags like this:
#{list items:active_brands, as:'c'}
...
#{\list}
Or using JQuery inside an HTML table like this:
<td>${active_brands.get(1)}</td>
Just for reference, the passed in parameter is a List.
However, I am trying to access the parameter "active_brands" from a javascript function and I am not sure how to do that.
I thought using Jquery to access the variable would work and I tried to access the variable like this:
function update_brands(active_scenario_ids){
...
alert('Reached: '+ ${active_brands});
}
but that does not work. It seems to me that the HTML attribute is out of scope for the javascript function. Is that true?
It would be great if someone can help me with this. Thanks.
This works for me using Play 2.2.0:
Application.scala (controller):
def index = Action { implicit request =>
val message = "This is a test."
Ok(views.html.test(message))
}
test.scala.html (view template):
#(message: String)
<script type="text/javascript">
$(document).ready(function(){
console.log("#message");
});
</script>
Console output:
This is a test.
The root of the problem was that my template variable, which is accessible in client side HTML, was of type java.util.List, which is not accessible by client side code ie. javascript. However, it is recognized in the play tags because play tags are server side code written in client side. So the only solution I could find for reading Objects inside java collections is returning a JSON object.
Therefore I had to change my code such that instead of returning a Java List as a template variable, I retrieve the data as a JSON object through an ajax call.
$.ajax({
url: '/getBrands/',
type: 'POST',
data: {active_scenario_ids: active_scenario_ids},
dataType: "json",
success: function(data){
console.log(data);
},
error: function(req, status, error){
alert("R:"+req+"S:"+status+"E:"+error);
}
});
}

How to default construct JavaScript object from JSON Schema?

I've started using Newtonsoft.Json.Schema.JsonSchemaGenerator along with various property attributes over in my C# code to help keep my client script DRY. What I'd like to do is create a default initialized object client-side based on the schema from the server. This would be useful for, say, when the user clicks 'New Foo' to add a new entry into a table.
Obviously I can just code it up to iterate the .Properties and build up the new object, which is what I'm doing at the moment. However I'd prefer to avoid reinventing any wheels.
Are there any JS libraries for working with JSON schema that will do this, among other nifty things I've yet to realize I need?
1/29/2013 UPDATE
Some people have attempted to answer my question and have been off base, and as a result have received some negative feedback from the SO community. So let me attempt to clarify things. Here is the challenge:
In JS client script, you have an object that represents the JSON Schema of another object. Let's say, this came from the server via JSON.NET and is the representation of a C# class.
Now, in the JS client script, create one of these objects based upon the JSON Schema. Each field/property in the object must be default initialized according to the schema, including all contained objects!
BONUS: Bind this new object to the UI using MVVM (eg Knockout). Change some of the fields in response to user input.
Send this new object to the server. The server-side code will add it to a collection, database table, whatever. (Yes, the object will be sent as JSON using Ajax -- we can assume that)
No duplication! The only place where the class is defined is in the server-side code (C# in my example). This includes all metadata such as default values, description text, valid ranges, etc.
Yes there is (I tried it with NodeJS):
JSON Schema defaults
Link updated.
i think...you have to use two way binding with your HTML code...so, once your client side change you will get on your costume js file.
check here for knockout js.
Knock Out JS Link
and on C# code use : $("#urlhidden").val() OR Document.GetElemenyByID("#urlhidden").val().
here you will get array/list or textbox value
Use json with Ko
create new viewmodel for knockout js which you will get the idea about on above link.
and create a json call
like:
self.LoadMAS_Client = function () {
try {
var params = { "clientID": ClientId };
$.ajax({
type: "POST",
url: "http://" + ServerString + "/Services/LogisticsAppSuite-Services-Web-Services-MasClientService.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
// in response u will get the data.and use as per your requirement.
eg. self.SelectedClient(response.your value);
},
error: function (ErrorResponse) {
}
});
}
catch (error) {
}
};
================================New Update ==========================================
i think..one way you can do...get data on xml format at C# code and covert into json string...check below code // To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

Categories