Dynamics CRM get selected entity's attribute value - javascript

I need to get an attribute value ("val_index") of an entity which is selected in lookup.
function onLookupChange(){
var entityName, entityId, entityLabel, lookupFieldObject;
lookupFieldObject = Xrm.Page.data.entity.attributes.get('my_attribute');
if (lookupFieldObject.getValue() != null) {
entityId = lookupFieldObject.getValue()[0].id;
entityName = lookupFieldObject.getValue()[0].entityType;
entityLabel = lookupFieldObject.getValue()[0].name;
}
// here I need to get an attribute value of a selected entity. Attribute's name is "val_index"
}
How can I do that?

Use the SDK.REST.js library which ships with the CRM SDK to do this. Include this as a script in your form entity and you can reference the functions to make REST calls.
An example call might look like this:
// Assume we are working with the account entity.
// This call is asynchronous.
SDK.REST.retrieveRecord(entityId, "Account", "val_index", null,
// Success.
function (result) {
var value = result.val_index;
// Do something.
},
// Error retrieving the value.
function (error) {
// Notify the user...
});

Related

two way data binding in angularjs

i am creating a web app with the help of angularjs,
on one of my button click i am calling a web service through angularjs
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public void getuprec(string id)
{
List<object> selectrecd = new List<object>();
SqlCommand cmd = new SqlCommand("select * from erp_admin.CompanySonVinUnitVenueRpt where comsonvinid in (select id from companysonvinunitvenue where id='"+id+"')",con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
selectrecd.Add(new
{
attendee1 = dr["comattendee1"].ToString(),
attendee2 = dr["comattendee2"].ToString(),
totalmale = dr["attendeetotalmale"].ToString(),
totalfemale = dr["attendeetotalfemale"].ToString(),
unit1 = dr["unitattendee1"].ToString(),
unitd1 = dr["unitattendee1desig"].ToString(),
unit2 = dr["unitattendee2"].ToString(),
unitd2 = dr["unitattendee2desig"].ToString(),
unit3 = dr["unitattendee3"].ToString(),
unitd3 = dr["unitattendee3desig"].ToString(),
unit4 = dr["unitattendee4"].ToString(),
unitd4 = dr["unitattendee4desig"].ToString(),
unit5 = dr["unitattendee5"].ToString(),
unitd5 = dr["unitattendee5desig"].ToString(),
remarks = dr["remarks"].ToString()
});
}
con.Close();
var json = js.Serialize(selectrecd);
Context.Response.Write("{" + '"' + "selectrecd" + '"' + ":" + json + "}");
}
this is my webservice which is working fine (i tested) and my angularjs file
$scope.updatefunction = function (param) {
$http.get('/frmattendencerptqed.asmx/getuprec', {
params: {
id: $scope.updateparam.comsonvinid
}
})
.then()
{
}
}
this is my angularjs
this is my input field
<input type="text" ng-model="remarks" style="width:100%;" />
now i need to take the previous value from my database and bind the value on my textbox, and if user edit the textbox then the value must be updated on button click
how i need to do this
this is my input field
<input type="text" ng-model="remarks" style="width:100%;" />
now i need to take the previous value from my database and bind the
value on my textbox, and if user edit the textbox then the value must
be updated on button click
Which one remarks property ?
In your webservice you returns a json object which contains a array of structured objects which each one may contain a remark property.
Can you post the resulted json of webservice call in order to give us more details ?
About how to retrieve and bind the data in your angular js controller, here is my answer.
From https://docs.angularjs.org/api/ng/service/$http
you can retrieve response from data property in returned object.
data – {string|Object} – The response body transformed with the
transform functions.
So you can do something like that:
$scope.updatefunction = function (param) {
$http.get('/frmattendencerptqed.asmx/getuprec', {
params: {
id: $scope.updateparam.comsonvinid
}
})
.then(
// handling if ok
function(response){
$scope.remarks=response.data.selectrecd[indexYourWish].remarks
},
function(errResponse){
// handling if error
return $q.reject(errResponse);
}
);
}
As explains previously, I refer to an array to retrieve the information in response.data with an index you should define or not use at all index if you don't return a array.
remarks should be a variable in the scope of your controller.
The more relevant syntax to use for controller depends on how you declare things in Angular (Personally, I avoid $scope.xxx syntax).
Post more of your JS code if you want a more precise answer.
It's just how angularjs normally works, the two way databinding follow this tutorial:
http://www.w3schools.com/angular/angular_databinding.asp
you'll see that what you only need is to call the update function from your controller and pass it the variable you bind to the input.
Of course this variable assigned to $scope or to this in the controller (there are two ways).

Subclass of parse.com object in javascript properties after query

I'm using parse.com as the backend to my project and am creating a web page using javascript.
I'm extending PFObject as follow:
var Match = Parse.Object.extend("Match");
On the match object i have a couple properties, let say the first one is "player1"
My question is how can i make it so that when i try to get a property of my match object it succeeds
ie:
var matchQuery = new Parse.Query("Match");
matchQuery.find({
success: function (results) {
_.each(results, function (element, index, list) {
//
var test = element.player1 <<<< here player1 is undefined
})
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
Thanks for any tips!
Setting values on the backbone object works like regular JS. The value is retained for as long as the object is in memory, but no longer.
match.memoryOnlyAttribute = "I'll be gone soon";
If match is released and then queried again, memoryOnlyAttribute will be null, as you have observed.
To get a value for a property that persists, it must first be a property on the object. This is typically done in the data browser with the "+ Col" button. (It can also be done in code if your CLP permits).
With that done, the object can only be assigned persistent property values via the set() method...
var Match = Parse.Object.extend("Match");
var match = new Match();
match.set("player1", /* an object here that is of the right type */);
match.save();
Once the object is retrieved, the property in the parse data can be retrieved with the get() method...
matchQuery.first().then(function(matchResult) {
var player1 = match.get("player1");
// player1 will have a value
});

CRM Error Object doesn't support property or method 'getValue'

I'm starting to write a simple javascript on CRM Contact page to retrieve the parent account ID.
I set the script as an onChange event on the parent account field (parentcustomerid) and set it to "pass execution context as parameter".
This is my code:
function PopulateAccountType(ParentAccount) {
if (ParentAccount != null) {
var Account = new Array();
var Account = Xrm.Page.getAttribute("parentcustomerid").getValue();
{
var AccountId = Account[0].id;
}
}
}
Not sure why I keep getting error on the OnChange event Object doesn't support property or method 'getValue'.
I've been using 'getValue' function successfully but is it different when the value is an ID?
Thanks for your help, greatly appreciate.
-elisabeth
Try this Code and Uncheck Execution Parameter Check Box.
function PopulateAccountType()
{
var lookup = Xrm.Page.getAttribute("parentcustomerid").getValue();
if(looup!=null)
{
var Account = lookup[0].id;
alert(Account);
}

Meteor Users collection and Deps.autorun problems

I'm still struggling to understand how to access Meteor.users as a foreign key from another collection query. I understand that only the current user is published by default so I have a publication on the server as
Meteor.publish('itemOwner', function(userId) {
check(userId, String);
var user = Meteor.users.find({id: userId});
return user;
// return Meteor.users.find({id: userId}, {
// fields: {'profile': 1} });
});
I then have a Deps.autorun on the client..
Deps.autorun(function () {
var itemOwnerId = Session.get("itemOwnerID");
if (itemOwnerId) {
debugger
var ID = Session.get("itemOwnerID");
Meteor.subscribe('itemOwner', Session.get("itemOwnerID"));
}
});
I set the session ID on a modal form load, and display it in the template by calling the ownerProfile helper (or try to)
Template.showQuoteModalInner.helpers({
getQuote: function () {
// Get the quote ID from the session var
var quote = Session.get("quoteID");
if(quote) {
debugger;
var ID = quote.user._id;
Session.set("itemOwnerID", quote.user._id);
return quote;
}
},
ownerProfile: function() {
debugger;
var quote = Session.get("quoteID");
if(quote) {
var ID = quote.user._id;
var theUser = Meteor.users.find({_id: quote.user._id});
return theUser;
};
}
});
Now, I can trace the user ID at each stage and see it getting correctly passed to the autorun and the helpers. If I stop the program at the debugger in the ownerProfile helper and in the console put in Meteor.user.fetch({_id: "the id here"}).fetch() I get the correct user back.. but, in the handler itself the Meteor.users.find returns null??? What am I missing?
Two possibilities I noticed.
First, you are missing an underscore in the find in your publish function.
.find({id: userId}) should be .find({_id: userId}).
But this probably isn't the issue if you are seeing the user (other than the logged in user) in the console.
Second, if you are not seeing the user from your Template.showQuoteModalInner.ownerProfile helper, it is probably because you are returning a find() instead of a findOne().
find() returns a cursor whereas findOne() returns the record. Try findOne() if you want to display that single user's attributes.

AngularJS and Restangular, trying to convert update method to API

I'm trying to convert my basic crud operations into an API that multiple components of my application can use.
I have successfully converted all methods, except the update one because it calls for each property on the object to be declared before the put request can be executed.
controller
$scope.update = function(testimonial, id) {
var data = {
name: testimonial.name,
message: testimonial.message
};
dataService.update(uri, data, $scope.id).then(function(response) {
console.log('Successfully updated!');
},
function(error) {
console.log('Error updating.');
});
}
dataService
dataService.update = function(uri, data, id) {
var rest = Restangular.one(uri, id);
angular.forEach(data, function(value, key) {
// needs to be in the format below
// rest.key = data.key
});
// needs to output something like this, depending on what the data is passed
// rest.name = data.name;
// rest.message = data.message;
return rest.put();
}
I tried to describe the problem in the codes comments, but to reiterate I cannot figure out how to generate something like rest.name = data.name; without specifying the name property because the update function shouldn't need to know the object properties.
Here is what the update method looked like before I started trying to make it usable by any of my components (this works)
Testimonial.update = function(testimonial, id) {
var rest = Restangular.one('testimonials', id);
rest.name = testimonial.name;
rest.message = testimonial.message;
return rest.put();
}
How can I recreate this without any specific properties parameters hard-coded in?
Also, my project has included lo-dash, if that helps, I don't know where to start with this problem. Thanks a ton for any advice!
Try like
angular.extend(rest,testimonial)
https://docs.angularjs.org/api/ng/function/angular.extend

Categories

Resources