Creating a Salesforce Apex Trigger to update a lookup field in the Contacts object - apex-code

I have created a trigger that will auto-create a contact when a specific Account record type is created or updated. The problem is that I am not sure how to populate the Contact 'Account Name' lookup field. This field is a lookup to the Account object. My code is below. Any help on how to integrate this missing component would be greatly appreciated.
trigger autoCreateContact on Account (after update, after insert)
{
List newContact = new List();
for (Account oAccount : trigger.new)
{
if (oAccount.RecordTypeid == '012F0000001MCfgIAG')
{
List<Contact> cCheck = [SELECT ID From Contact WHERE LastName=:oAccount.Name];
if(cCheck.isEmpty()==True)
{
System.debug(oAccount);
Contact oContact = new Contact();
oContact.LastName = oAccount.Name;
oContact.phone = oAccount.Phone;
oContact.email = oAccount.Email__c;
oContact.Owner = oAccount.Owner;
newContact.add(oContact);
}
}
if(newContact.isEmpty() == false)
{
Database.insert(newContact);
}
}
}

nice trigger I'm pretty sure you just need to add one line which is a reference to the account.id.
So if I were you I would add the link:
oContact.AccountID = oAccount.id;

NOTE: its not a good practice to have a SOQL inside the for loop.

Related

Automatically map a Contact to an Account

I want to add a field to Accounts which shows the email domain for that account e.g. #BT.com. I then have a spreadsheet which lists all the Accounts and their email domains. What I want to do is when a new Contact is added to Dynamics that it checks the spreadsheet for the same email domain (obviously without the contacts name in the email) and then assigned the Contact to the Account linked to that domain. Any idea how I would do this. Thanks
Probably best chance would be to develop CRM plugin. Register your plugin to be invoked when on after contact is created or updated (so called post-event phase). And in your plugin update the parentaccountid property of the contact entity to point to account of your choice.
Code-wise it goes something like (disclaimer: not tested):
// IPluginExecutionContext context = null;
// IOrganizationService organizationService = null;
var contact = (Entity)context.InputParameters["Target"];
var email = organizationService.Retrieve("contact", contact.Id, new ColumnSet("emailaddress1")).GetAttributeValue<string>("emailaddress1");
string host;
try
{
var address = new MailAddress(email);
host = address.Host;
}
catch
{
return;
}
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
contact["parentaccountid"] = entities[0].ToEntityReference();
}
organizationService.Update(contact);
I took Ondrej's code and cleaned it up a bit, re-factored for pre-operation. I also updated the logic to only match active account records and moved the query inside the try/catch. I am unfamiliar with the MailAddress object, I personally would just use string mapping logic.
var target = (Entity)context.InputParameters["Target"];
try
{
string host = new MailAddress(target.emailaddress1).Host;
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
query.Criteria.AddCondition("statecode", ConditionOperator.Equals, 0); //Active records only
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
target["parentaccountid"] = entities[0].ToEntityReference();
}
}
catch
{
//Log error
}

eror when retrieve createdby field in crm using plugin

I try to retrieve the createdby field when I create a cases with a plugin, but the first retrieval fails, and the second and subsequent retrieval are successful. And then when I logged out and login with other user the first retrieval fails (retrieve result is the user before i change the user), and the second and subsequent retrieval are successful.
here is the code i write :
public void Execute(IServiceProvider serviceProv)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProv.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory servicefac = (IOrganizationServiceFactory)serviceProv.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = servicefac.CreateOrganizationService(context.UserId);
ITracingService trace = (ITracingService)serviceProv.GetService(typeof(ITracingService));
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "incident")
return;
QueryExpression qe = new QueryExpression("incident");
string[] cols1 = { "createdby" };
qe.ColumnSet = new ColumnSet(true);
EntityCollection ec = service.RetrieveMultiple(qe);
foreach (Entity act in ec.Entities)
{
created = act. GetAttributeValue<EntityReference>("createdby").Name;
}
if (created == "CRM SNA")
{
created = string.Empty;
}
else
{
//here is the autonumber code
created = string.Empty;
}
}
}
What I want to make is an autonumber plugin, when cases are created by "CRM SNA" then the autonumber must not run, when cases are created by other users the autonumber will run.
How to make the first retrieve successful? and did not retrieve the user before?
thanks.
I assume your plugin runs in the Pre-Create step. CreatedBy and CreatedOn are not available in this step (probably because the record is not saved yet).
If you are just trying to get the user that executed the action that fired the plugin, use context.InitiatingUserId. You could also look into the documentation for the WhoAmI request.
Hope that helps!

Can Dynamics Crm PartyList store an emailaddress

I have fields in activity form for email. It contains "to, cc and bcc" fields that are all fields of the type PartyList
The question is: Can I only store entity values like contact or account or can I also just store a email address which is not associated to any contact or account in the system?
Here is a picture explaining what I'm trying to achieve
As per this article it appears that the answer is yes via the addressUsed field.
Entity email = _sdk.Retrieve("email", emailId, new ColumnSet("to"));
EntityCollection to = email.GetAttributeValue<EntityCollection>("to");
if (to != null)
{
to.Entities.ToList().ForEach(party =>
{
EntityReference partyId = party.GetAttributeValue<EntityReference>("partyid");
bool isDeleted = party.GetAttributeValue<bool>("ispartydeleted");
string addressUsed = party.GetAttributeValue<string>("addressused");
// Do something...
});
}

Associate user when created with an existing Account

I have a code that checks an inquery database a for user,
If the user does not exist, then the code will create a new user in Contact,
Here is only part of the code:
newcontact = [SELECT Id, FirstName FROM Contact WHERE Contact.Email =inquery.email__c];
if(newcontact.size() == 0) {
Account[] aa = [SELECT Id FROM Account WHERE Name = :inquery.Institution__c];
contact = new Contact();
contact.FirstName = inquery.First_Name__c;
contact.LastName = inquery.Last_Name__c;
contact.Email = inquery.email__c;
contact.AccountId = aa.Id;
try {
insert contact; // inserts the new record into the database
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error creating new contact'));
return null;
}
I am trying to associate that user with an existing Account?
But the following line gives me an error:
contact.AccountId = aa.Id;
Which is
Initial term of field expression must be a concrete SObject: LIST<Account> at line
And aa.size() returns 1, as it should,
Because the account exists,
Can someone please tell me what wrong?
Thanks
This line contact.AccountId = aa.get(0).Id; will fail if your query returns 0 rows. Make sure to wrap your code within a if (aa.size() > 0) clause to ensure proper execution in all cases.
Ok I fixed it, as follows:
contact.AccountId = aa.get(0).Id;
Best

Can I update the owner id of a Contact using LINQ?

I'm using CRM 2011, and attempting to update the OwnerId of contact using this code:
var crmContext = new CustomCrmContext(service);
var contact = crmContext.Contact.FirstOrDefault(c=>c.Id == id);
contact.OwnerId.Id= newOwnerId;
crmContext.UpdateObject(contact);
crmContext.SaveChanges();
I don't get any errors, however, the ownerId never updates in the database. I am able to update other attributes, but I'm just wondering if maybe the OwnerId is special and you have to use OrganizationRequest("Assign")? If so, where is this documented so I know what other attributes I cannot update?
The owner of a record cannot be modified with an update. You have to send a AssignRequest instead.
// Create the Request Object and Set the Request Object's Properties
var request = new AssignRequest
{
Assignee = new EntityReference(SystemUser.EntityLogicalName, _newOwnerId),
Target = new EntityReference(Account.EntityLogicalName, _accountId)
};
// Execute the Request
_service.Execute(request);

Resources