Fire Event on Background Change - javascript

Just the background:
(not really related to the question)
I am using SharePoint and creating a Sharepoint Hosted App.
I have some fields which provide a peoplepicker with which I can select Users out of a user pool. The functioninality is provide by the SharePoint internal scripts.
If I input a name of a user via jquery nothing happens. It has no built-in change handler I guess.
What I have done is a separat script which just resolve the user names on my jquery input via trigger("change") and then the SharePoint internal Scripts doing the job. This "job" is asynchronous and then if the data arrives from the backend the SharePoint Scripts apply the data to the Peoplepicker fields.
But this functions also doesn't support jQuery's trigger because I cannot alter the functions as they're pre-defined...
So want I want to do is to monitor when the text inside the Peoplepicker fields has been changed but I am a little bit lost now.
Question:
I have tried it with the following code (which doesn't work):
$('.peoplePickerDiv').bind("DOMSubtreeModified", function () {
alert("HAS BEEN CHANGED!");
});
Is there another way to react on lets say background editing of input fields in my DOM?

For People Picker control manipulation SPClientPeoplePicker object (clientpeoplepicker.js) is intended, which provides methods for getting information from the picker or to perform other operation.
SPClientPeoplePicker class exposes the following events:
OnControlValidateClientScript - triggers after a server error is set or cleared
OnUserResolvedClientScript - triggers once the resolved user is added or removed in client
OnValueChangedClientScript - triggers after text input or users change in client
OnValueChangedClientScript event probably suits your scenario, here is an example on how to attach it:
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerId];
picker.OnValueChangedClientScript = function (elementId, userInfo) {
if(userInfo.length > 0){ // once the value is resolved it could be retrieved via `userInfo` object
console.log(userInfo[0]);
}
console.log('value changed');
};
References
Use the client-side People Picker control in SharePoint-hosted SharePoint Add-ins

Related

Refresh form (Ctrl+F5) doesn't fire Retrieve Plugin in CRM 2011

I need to update entity1 based on creation of entity2 (math calculation)
while the form of entity1 is open.
When I refresh the entity1 form, the field has the old value until I close and open the entity1 form (the caching issue).
I found out that it doesn't fire the Retrieve Plugin. Is there a way to overcome this issue just by refreshing the form?
First and foremost: latest CRM has Xrm.Page.data.refresh() to update form data "automagically" (not to mention the fact that fields self-refresh when changed via plugins).
If upgrading is not an option, I'd setup a "watcher" function like this:
// attach to Form Load event
function keepYourFieldInSync() {
setInterval(function(){
var current = Xrm.Page.getAttribute("yourField");
// Not shown here, basically get the updated value from server
var fetched = fetch_yourField_value_from_OData_or_SOAP();
if(fetched != current){
Xrm.Page.getAttribute("yourField").setValue(fetched);
// if users aren't allowed to set the field by hand, I'd also include this
// and customize the field to be readonly
Xrm.Page.getAttribute("yourField").setSubmitMode("never");
}
}, 1000); // keep it above 500 to avoid killing the browser
}
I use a "trick" like this to recognize status changes in Quotes (another user would activate it while this user was working on the draft) and it works quite well.

Emptying the from field in the email entity in CRM 2013 using Javascript

So im trying to empty the from field on the email entity whenever i load the page. I am trying to do so using a javascript. My code is as follows.
function emptyField(fieldName) {
var personType = Xrm.Page.getAttribute(fieldName).DataValue = [];
}
I have also tried with
function emptyField(fieldName) {
var personType = Xrm.Page.getAttribute(fieldName).DataValue = null;
}
None of these methods seem to work however. Can anyone tell me what i can do?
OOB functionality goes like this:
function emptyField(fieldName) {
Xrm.Page.getAttribute(fieldName).setValue(null);
}
Double-check the notes in the MSDN page:
Updating an attribute using setValue will not cause the OnChange event handlers to run. If you want the OnChange event handlers to run you must use fireOnChange in addition to setValue.
When Microsoft Dynamics CRM for tablets is not connected to the server setValue will not work.
You cannot set the value of composite attributes. More information: Write scripts for composite attributes.
Alex's answer will work. But it doesn't save the empty value to field. If you want to save it just add this code :
function setValue(toSet) {
Xrm.Page.data.entity.attributes.get('myField').setValue(toSet);
Xrm.Page.getAttribute('myField').setSubmitMode('always');
Xrm.Page.data.entity.save();
}

How getCalendarById(id) work if the setting is made public and all ids are accessible in an organization

I am using google app script for calender events,
According to document: https://developers.google.com/apps-script/reference/calendar/calendar-app#getCalendarById%28String%29
returned value is the calendar with the given ID, or null if the calendar does not exist or the user cannot access it
say in an orgainzation windows.com the setting is made where all ids in the org are accessible,
var cal = CalendarApp.getCalendarById('mac#windows.com');
Logger.log(cal);
It gives null if I run the function and when I manually subscribe the mac#windows.com to the calender of the authorized script runner then it works fine,
Is there a way where we can get the id of the organization subscribe while running the script, for dynamic input of id.
Calender setting in the org google business app is : Share this calender with everyone in the organization windows.com as default.
I had the same issue in a recent project and discovered that the user must be explicitly subscribed to the calendar for the GetCalendarById function to work reliably. I used the following code to handle this, it attempts to subscribe the user if getCalendarById fails to return it on the first try.
I also set the calendar to hidden & un-selected, so subscribing the user does not clutter their standard calendar view.
var calendar = CalendarApp.getCalendarById(calendar_id);
if(calendar == null){
//user may not have access, auto-subscribe them.
calendar = CalendarApp.subscribeToCalendar(calendar_id,{hidden:true,selected:false});
}
See the calendarApp reference, https://developers.google.com/apps-script/reference/calendar/calendar-app#subscribeToCalendar(String,Object)

Task "Regarding" field not populating from subgrid in CRM 2013

I am using CRM 2013 on-premise with UR1 installed
I have a custom entity with a subgrid on it looking at related "tasks" which looks like this:
Whenever I create a task from the subgrid using the "+" button in the top right hand corner of the subgrid; the "Regarding" field of the newly created task remains blank. When it should be populated by a lookup to the record it was created from.
I have javascript on the task entity which checks the "Regarding" field to check what kind of entity it was created from (if it was created from one) and gets certain field values from the calling entity to populate fields on the task.
Since the "Regarding" field is never filled the Javascript never fires - and the fields do not populate.
When the record is saved, if the regarding field is blank (I have not manually filled it in) - it will eventually be populated by the correct record about 10 - 15 seconds later if you refresh the page. Then the correct fields will be populated and the user is able to edit the option set values and save again. This is not ideal for the user as they would like it to be one fluid action.
Is there any way around this problem?
EDIT for future browsers of this question:
Found a partial work around. If you use an "Activity" subgrid rather than a "Task" subgrid the field will populate. This has a drawback though as you cannot edit the "Activity" subgrid's view to show "Task" specific fields.
Ran into this same issue. The way I got around it was to add a look-up to the custom entity on the form (we put this on a hidden tab). When the Task gets created from the custom entity the look-up will be populated. You can then use that look-up to grab the values that you need to populate, including the regarding field. Not the most elegant, but it works.
I also ran into this problem and went with a pure JS approach to resolving. On load of the task form, call populateRegarding().
This works because even though the regarding lookup doesn't populate by default, the query string parameters include _CreateFromType and _CreateFromId values.
This works in 2015, didn't test on earlier versions. Note that it is unsupported.
function populateRegarding() {
var regarding = Xrm.Page.getAttribute("regardingobjectid"),
createFromType = Xrm.Page.context.getQueryStringParameters()._CreateFromType,
createFromId = Xrm.Page.context.getQueryStringParameters()._CreateFromId;
if (!createFromId || !createFromType ||
!regarding || regarding.getValue() !== null) {
return;
}
var entityLogicalName = getEntityLogicalNameFromObjectTypeCode(createFromType);
regarding.setValue([{
id: createFromId,
entityType: entityLogicalName,
name: "Hardcoded Name" // TODO: retrieve name dynamically
}]);
}
// This method uses an undocumented object and is therefore unsupported.
// You could implement a supported version of this function by querying for
// metadata, but that would be very expensive.
function getEntityLogicalNameFromObjectTypeCode(otc) {
var map = Mscrm.EntityPropUtil.EntityTypeName2CodeMap,
logicalName;
otc = Number(otc); // convert string to number
for (logicalName in map) {
if (!map.hasOwnProperty(logicalName)) { continue; }
if (map[logicalName] === otc) {
return logicalName;
}
}
}

NetSuite - Fields are not being set in the sales order after I set context to 'scheduled'

Hope you can assist.
I am currently trying to conduct one of the most simplest tasks via a user event script - that is to set a new value in the 'discount rate' field on the sales order. My script works fine when testing it on the client, but when the scheduled script is triggered, the field fails to set/update.
The following code is within a 'beforesubmit' operation. Can you spot what I have done wrong?
function beforeSubmit_discountVAT(type){
if(nlapiGetContext().getExecutionContext() !='scheduled')
return;
var getDiscountVal = nlapiGetFieldValue('discountrate');
var correctDiscount = getDiscountVal / 1.2;
nlapiSetFieldValue('discountrate', correctDiscount);
}
In short - All i want to do is deduct the discount value by 20%. Can you use 'nlapiSetFieldValue' when a user event script is triggered from a scheduled script?
Thanks in advance.
AWB
When editing an existing record, nlapiSetFieldValue cannot be used in a Before Load event on fields that are stored with the record. From the function's JSDocs:
Sets the value of a given body field. This API can be used in user event beforeLoad scripts to initialize field on new records or non-stored fields.
nlapiSetFieldValue can thus only be used reliably in Before Load on new records or non-stored fields.
Realizing this is a month old so you've probably found a solution, I would move your code to the Before Submit event. I tested this using a Scheduled Script:
var customer = nlapiLoadRecord('customer', '31294');
nlapiSubmitRecord(customer);
and User Event on the Customer record, Before Submit event:
if (nlapiGetContext().getExecutionContext() === 'scheduled') {
nlapiSetFieldValue('url', 'http://www.google.com/', false);
}
This works as expected for me in a 2013.1 Sandbox environment.
Using nlapiSubmitField in After Submit as mentioned in the other answer is an unnecessarily long operation that will use extra governance units. Not a huge deal if that's the only thing your script is doing, but if you ever expand the script or add looping, it can add up quickly in terms of performance and governance usage.
Also, it may not be necessary, but you should ensure that getDiscountVal is a Number by doing:
var getDiscountVal = parseInt(nlapiGetFieldValue('discountrate'), 10);
If it comes back as a String then your division operation may give a strange result which may also cause nlapiSetFieldValue to fail or set the field to an odd value.
two suggestions
Make sure that your script is being executed by adding a few nlapiLogExecution statements
Instead of doing it in beforesubmit, change this field in aftersubmit function using nlapiSubmitField
"Can you use 'nlapiSetFieldValue' when a user event script is triggered from a scheduled script?"
Yeah Absolutely yes.Context is also correct its scheduled.
Please make sure that you are submitting the record nlapiSubmitRecord(recordObj) at the end.
If you are not comfortable with nlapiSubmitRecord() you can obviously use nlapiSubmitField()
If still you get stuck up then please paste the complete code so that we could assist you.
Cheers!!!

Categories