I'm working on a client script, but when I do a simple getValue() on the customer field and log.debug, I get repeating output lines and I'm not sure why. Is this normal?
Output
This my fieldChanged code:
function fieldChanged(context) {
var newRec = context.currentRecord;
if(newRec.fieldId = 'entity') {
var custId = newRec.getValue ({
fieldId: 'entity'
});
log.debug({
title: 'id: ' + custId
});
}
}
Change the line below:
if(newRec.fieldId = 'entity')
To something like
if(context.fieldId === 'entity')
You're getting repeating output lines because whenever a field is changed, you're not doing a check on the current fieldId in the context object instead checking the context.currentRecord.fieldId which I'm not sure what evaluates to.
Check this out for more info: fieldChanged(scriptContext)
Related
My dataLayer currently looks like this:
dataLayer.push({
event: "someEvent",
hs-form-guid: "someHubspotId",
email: {
submittedEmail#domain.com: { //This array is named after the real submitted email
success: true,
email: "submittedEmail#domain.com",
emailShouldResubscribe: false,
emailFree: false,
emailSuggestion: null
}
}
})
I want to return the email value but I'm struggling with the nested array because I cannot return it by name because its name changes every time.
I've created a dataLayer variable 'email.0.email' named Email but is always 'undefined'. Also tried with 'email[0].email' or 'email.[0].email' with no luck.
Also created a second custom JS variable 'function () { return {{Email}}[0]}' but returns undefined too.
Any ideas? What am I doing wrong?
Thanks.
I created a Custom JavaScript Variable and here is the code
function(){
var emailDlv = {{DLV-email}};
var keys = Object.keys(emailDlv)[0];
return emailDlv[keys]
}
Here is the variable in GTM preview
I'm looking into some old code and I am seeing something I cannot figure out. The code is a controller action that returns a dynamic object:
return new
{
Result = true,
Count = data.Count(),
Students = data.Select(s => string.Format("{0}, {1}", s.LastName, s.FirstName))
};
However, the resulting JSON in the browser is not coming back as I would expect:
{
"$id":"1",
"Result":true,
"Count":1,
"Students":
{
"$id":"2",
"$values":["USER, ACTIVE"]
}
}
What I would expect, and what I normally get any other time I do this sort of thing, is more like this:
{
"Result":true,
"Count":1,
"Students":
{
["USER, ACTIVE"]
}
}
I have no idea where the $id and $values properties are coming from. I haven't seen this happen before with .Net, so I'm not sure what is causing this. It's not the dynamic object return that's causing the problem because I switched it to a named type just to test it out and it still does the same thing.
You need add this line of code to Global.asax to avoid append $id
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling
= Newtonsoft.Json.PreserveReferencesHandling.None;
You need to have a .ToList() at the end of the students.
{
Result = true,
Count = data.Count(),
Students = data.Select(s => string.Format("{0}, {1}", s.LastName, s.FirstName)).ToList()
};
I'm working with Fullcalendar and I'm trying to get resources as function
resources: function(callback){
var manageEvent = new ManageEvent();
var request = manageEvent.getEmployees();
request.always(function (param) {
//location.reload();
var list = [];
var emp;
for (var elem in param) {
emp = param[elem];
list.push({
'id': emp['cp_collaboratore'],
'title': emp['cognome_col']
});
}
var t = JSON.stringify(list);
callback(t);
});
request.catch(function (param) {
alert('errore');
});
},
I checked the variable 't' through log and it shows the following result:
[{"id":"1","title":"name_1"},{"id":"2","title":"name_2"},{"id":"3","title":"name_3"},{"id":"5","title":"name_4"},{"id":"9","title":"name_5"}]
but it don't works and shows the following error message:
Uncaught TypeError: resourceInputs.map is not a function
at ResourceManager.setResources
You just need to write
callback(list);
t in your code is a string, because you converted your list array into a string using JSON.stringify(). But fullCalendar expects an actual array, not a string. It can't run functions or read individual properties from a string.
You can remove the line var t = JSON.stringify(list); completely, it's not needed.
Generally the only reason you'd use stringify() is if you wanted to log the value to your console for debugging, or convert the array into JSON if you wanted to send it somewhere else using AJAX. It makes no sense to pass arrays and objects around inside JavaScript as serialised strings, when you can just use the objects themselves.
I'm trying to populate a KendoUI grid with JSON data where the server returns the total number of rows along with the data, but I'm having some trouble getting serverPaging to work properly. I create and assign the dataSource of the grid as follows:
var oDS = new kendo.data.DataSource({
schema: {
data: "data",
total: "total"
},
data: self.grdTableData,
serverPaging: true,
pageSise: 50,
total: joOutput["TotalRecords"]
});
grdTableResults.setDataSource(oDS);
and the first page shows the first 50 of 939 records but there is only ever 1 page (the navigation arrows never respond to anything) and I see NaN - NaN of 939 items and the rotating circle of dots in the centre of the grid that never goes away.
One thing that is different in all the examples I've looked at is that my $.ajax call and the the processing of the JSON data in .done doesn't use "transport: read" but I'm thinking how I send the data and get it back shouldn't matter (or does it because every page request is a new server read?). But I don't think I'm doing enough to handle the server paging properly even though it seems I'm setting data source values similar to those set in the example at http://jsfiddle.net/rusev/Lnkug/. Then there's the "take" and "skip" values that I'm not sure about, but I do have "startIndex" and "rowsPerPage" that I'm sending to the server that can be used there. I assume the grid can tell me what page I'm on show I can set my "startIndex" appropriately and if I have an Items per Page" drop down I can reset my "rowsPerPage" value?
Anyway, sorry for all the newbie questions. Any help and suggestions is genuinely appreciated. Thanks!
transport: read
You should be able to use "transport: read" even if you have custom logic by setting the value to a function. I have created a JS Fiddle to demonstrate this functionality.
dataSource: {
serverPaging: true,
schema: {
data: "data",
total: "total"
},
pageSize: 10,
transport: {
read: function(options) {
var data = getData(options.data.page);
options.success(data);
}
},
update: function() {}
}
Your read function contains a parameter that contains the following paging properties: page, pageSize, skip, take. Keep in mind that all transport operations need to be functions if one operation contains a function.
startIndex and rowsPerPage
If your server accepts these parameters, you should be able to submit them in the read function. Create a new ajax call that post customized data
var ajaxPostData = { startIndex: options.data.skip, rowsPerPage: options.data.pageSize }
This is the code for server side wrapper that I'm using to implement server paging with kendo grid:
#(Html.Kendo().Grid<IJRayka.Core.Utility.ViewModels.ProductDto>()
.Name("productList")
.Columns(columns =>
{
columns.Bound(prod => prod.Name);
columns.Bound(ord => ord.Brand);
columns.Bound(ord => ord.UnitPackageOption);
columns.Bound(ord => ord.CategoryName);
columns.Bound(ord => ord.Description);
})
.Pageable(pager => pager.PageSizes(true))
.Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))
.PrefixUrlParameters(false)
.DataSource(ds => ds.Ajax()
.Model(m => m.Id(ord => ord.ID))
.PageSize(5)
.Read(read => read
.Action("FilterProductsJson", "ProductManagement")
.Data("getFilters"))
)
)
Where getFilters is a javascript function that passes my custom filter parameters to the grid when it wants to get data from url/service:
function getFilters() {
return {
brand: $("#Brand").val(),
name: $("#Name").val(),
category: $("#CategoryName").val()
};
}
In addition you should implement your controller's action method using kendo's DataSourceRequest class like below, or otherwise it won't work the way you want:
public JsonResult FilterProductsJson([DataSourceRequest()] DataSourceRequest request,
// three additional paramerters for my custom filtering
string brand, string name, string category)
{
int top = request.PageSize;
int skip = (request.Page - 1) * top;
if(brand != null)
brand = brand.Trim();
if(name != null)
name = name.Trim();
if(category != null)
category = category.Trim();
var searchResult = new ManageProductBiz().GetPagedFilteredProducts(brand, name, category, top, skip);
// remove cyclic references:
searchResult.Items.ForEach(prd => prd.Category.Products = null);
return Json(new DataSourceResult { Data = searchResult.Items, Total = searchResult.TotalCount }, JsonRequestBehavior.AllowGet);
}
I am iterating over a moment-range daterange and trying to insert documents. I am getting the following error:
Exception while simulating the effect of invoking '/carpool_events/insert'
Error
Error: Sorting not supported on Javascript code
at Error (<anonymous>)
at Object.LocalCollection._f._cmp (http://localhost:3000/packages/minimongo/selector.js? 5b3e1c2b868ef8b73a51dbbe7d08529ed9fb9951:251:13)
at Object.LocalCollection._f._cmp (http://localhost:3000/packages/minimongo/selector.js? 5b3e1c2b868ef8b73a51dbbe7d08529ed9fb9951:226:36)
at LocalCollection._f._cmp (http://localhost:3000/packages/minimongo/selector.js?5b3e1c2b868ef8b73a51dbbe7d08529ed9fb9951:218:33)
at _func (eval at <anonymous> (http://localhost:3000/packages/minimongo/sort.js?08a501a50f0b2ebf1d24e2b7a7f8232b48af9057:63:8), <anonymous>:1:51)
at Function.LocalCollection._insertInSortedList (http://localhost:3000/packages/minimongo/minimongo.js?7f5131f0f3d86c8269a6e6db0e2467e28eff6422:616:9)
at Function.LocalCollection._insertInResults (http://localhost:3000/packages/minimongo/minimongo.js?7f5131f0f3d86c8269a6e6db0e2467e28eff6422:534:31)
at LocalCollection.insert (http://localhost:3000/packages/minimongo/minimongo.js?7f5131f0f3d86c8269a6e6db0e2467e28eff6422:362:25)
at m.(anonymous function) (http://localhost:3000/packages/mongo-livedata/collection.js?3ef9efcb8726ddf54f58384b2d8f226aaec8fd53:415:36)
at http://localhost:3000/packages/livedata/livedata_connection.js?77dd74d90c37b6e24c9c66fe688e9ca2c2bce679:569:25
This is my loop with the insert. I have tested the loop by just writing to console.log instead of inserting and the loop works fine
'click button.save-addEventDialogue': function(e, tmpl) {
var start = Session.get("showAddEventDialogue_dateRangeStart");
var end = Session.get("showAddEventDialogue_dateRangeEnd");
var dateRange = moment().range(moment(start),moment(end));
var dateLoopIncrement = moment().range(moment(start),moment(start).add('days',1));
console.log(dateRange);
console.log(dateLoopIncrement);
// Loop through the date range
dateRange.by(dateLoopIncrement, function(moment) {
// Do something with `moment`
var dateToSave = dateRange.start;
// Insert the record
Carpool_Events.insert({
owner: Meteor.user().profile.name,
owner_id: Meteor.userId(),
original_owner: Meteor.user().profile.name,
original_owner_id: Meteor.userId(),
declined: 0,
date: dateToSave.toDate()
});
dateToSave.add('days',1);
});
// Clear the Session
Session.set("showAddEventDialogue_dateRangeStart","");
Session.set("showAddEventDialogue_dateRangeEnd","");
// Close the dialogue
Session.set("showAddEventDialogue", false);
}
What is the right way to do this? Thanks.
The error message Sorting not supported on Javascript code is a result of inserting a JavaScript function (!) into a collection -- for example, by doing something like Carpool_Events.insert({x: function () { ... }}); JavaScript functions should not normally go into collections.
Somewhere in your code there is probably a typo where you are not calling a function (for example, writing Meteor.userId on the client instead of Meteor.userId().) My guess would be that in the process of making your code run on the server, you coincidentally fixed or avoided this.
I wasn't able to visually find the problem in your code -- if I'm wrong, to make more progress it would be helpful to have a reproduction.
It looks like the issue occurs when doing a bulk inserts (inserts in a loop) from the client. What I ended up doing was using a Meteor.methods to execute the insert on the server side. This seemed to workaround whatever the issue of doing this on the client is.
I also realized that I don't need to iterate over the dates using moment-range. Instead i just use moment to get the difference in days and iterate over that.
JS code in the client:
'click button.save-addEventDialogue': function (e, tmpl) {
var start = moment(Session.get("showAddEventDialogue_dateRangeStart"));
var end = moment(Session.get("showAddEventDialogue_dateRangeEnd"));
var days = end.diff(start, 'days');
var count = 0;
var dateToSave = moment(start);
// Loop through the date range
for (count; count <= days; count++) {
Meteor.call('bulkInsertCarpoolEvent', Meteor.user(), dateToSave.toDate());
dateToSave.add('days', 1);
};
// Clear the Session
Session.set("showAddEventDialogue_dateRangeStart", "");
Session.set("showAddEventDialogue_dateRangeEnd", "");
// Close the dialogue
Session.set("showAddEventDialogue", false);
}
On the server:
Meteor.startup(function () {
Meteor.methods({
bulkInsertCarpoolEvent: function (user, date) {
return Carpool_Events.insert({
owner: user.profile.name,
owner_id: this.userId,
original_owner: user.profile.name,
original_owner_id: this.userId,
declined: 0,
date: date
});
}
});
});