Hi all, I'm getting an Error Campaigns Filed is Mandatory in new Leads from 2021. when i am trying to create a new lead - salesforce

QueryResult result1 = connection.query("select id, Name from Campaign where id='" + campaignId +
"'");
LeadDetails lead = new LeadDetails();
lead.setFirstName(leadDeatils.getFirstName());
lead.setLastName(leadDeatils.getLastName());
lead.setSalutation("Mrs.");
lead.setIndus("sasadd");
Campaign campaign = (Campaign)result1.getRecords()[0];
lead.setCampaign(campaign);
SaveResult[] sr = connection.create(new SObject[] { lead });
I am new bee here. please help me out. thank you.

What is it, integration that sends Leads to SF using SOAP API?
You will have to contact Administrators / Developers in charge of that Salesforce org. There's no standard lookup from Lead to Campaign so there's nothing to be made mandatory from 2021. Here's list of standard fields.. And here's the entity relationship diagram showing that Leads (and Contacts) are linked to Campaign via many-to-many helper table called CampaignMember. (bottom left).
Whatever error you're getting - it's probably new custom field/validation rule/some other thing the SF admins in your organisation did without notifying integration team.
P.S. If you have campaign id and there's custom Campaign__c field on lead or something -you don't have to query it? You probably could just call lead.setCampaign(campaignId ); or something like that?

Added Campaign Member to get fixed
CampaignMember campaignMember = new CampaignMember();
campaignMember.setCampaignId(campaignId);
campaignMember.setLeadId(leadId);
SaveResult[] result = connection.create(new SObject[] { campaignMember });
if (result.length == 1 && result[0].isSuccess()) {
System.out.println("LeadAssignment.setCampaignMember() : " + result);
// lead.setAttachments(attachResult.getClass());;
} else {
System.out.println("LeadAssignment.setCampaignMember() : Campaign member added on lead " + leadId);
}

Related

Creating a Multi-Contact Event with Apex in Salesforce

I am attempting to use Apex to create a multi-contact event.
I have already enabled Allow Users to Relate Multiple Contacts to Tasks and Events in the activity settings in the scratch org.
I am following the guide and the example at the bottom of these docs but I am constantly getting an error when pushing to the scratch org:
// ...
event.setEventWhoIds(attendeeContactIds);
// ...
Method does not exist or incorrect signature: void setEventWhoIds(List<String>) from the type Event.
I also tried to write directly to the field with:
event.EventWhoIds = attendeeContactIds;
With that, I get the error, that the field is not writable.
attendeeContactIds is a List of Strings representing Contact IDs.
What could I be missing? 🤔🙇🏻‍♂️
It's bit stupid, it's readonly in apex. It's exposed so integrations can quickly create event and essentially a related list together in one all-or-nothing transaction. See also https://salesforce.stackexchange.com/questions/238094/eventwhoids-is-not-writeable-in-apex-class-but-working-on-jsforce
Try something like that?
Savepoint sp = Database.setSavepoint();
event e = new Event(
StartDateTime = System.now(),
EndDateTime = System.now().addHours(1)
);
insert e;
List<EventRelation> invitations = new List<EventRelation>();
for(Contact c : [SELECT Id FROM Contact LIMIT 5]){
invitations.add(new EventRelation(
EventId = e.Id,
RelationId = c.Id,
IsInvitee = true
));
}
insert invitations;
Database.rollback(sp); // unless you really want to send it out

Angular 6 - How to Join DB object with Subscribe

I am working by my own on a app with Angular 6 / Flask. I am currently facing an issue and i am not able to find anything whivh is suitting it on the web. Here is my issue :
I have 3 Model : Project, Consultant and Client. To simplify, a Project have the id of a Consultant and a Client, and also two dates. What i want to do is to :
Get the list of all my projects
Iterate on this list to handle each project
Get the Consultant from its id
Get the Client from its id
Set an object with the Consultant, the Client and the two dates
Add this project to a list
Display the list
In fact, my purpose here is to be able to display information of the Consultant and the Client of each project so i need to get the object and not just their id. So i tried to do something from what i found :
ngOnInit() {
this.projectsListSubs = this.projectsApi
.getProjects()
.flatMap(params => {
params.forEach(elem => {
this.project.start_date = elem.start_date;
this.project.end_date = elem.end_date;
return [this.consultantsApi.getConsultant(elem.consultant_id),this.clientsApi.getClient(elem.client_id)]
}
this.dataSource = new MatTableDataSource(this.dataList);
})
.subscribe(params => {
this.project.consultant = params[0].firstName + " " + params[0].lastName;
this.project.client = params[1].name;
this.dataList.push(this.project);
});
}
Of course, it doesn't work. I think this code is garbage and I am not able to find a proper way to manage this case. Could you please help me on this ?
Thanks in advance.

Apex trigger which provides targets on sub campaign generates the error on parent campaign

I have a problem with one trigger. I was trying to set up the solution which will give me the possibility to assign flexible targets for campaigns. I was trying to solve it via formula field but it occurred to be too complex and I was advised it needs to be the apex trigger. I created the custom setting of list type, so then I could query it in the apex trigger. I created the "Apex_Calculator__c" field which combined values from two fields (Event Region [located on the parent campaign level] and Started Campaign [located on the sub-campaign level]). The value from the "Apex_Calculator__c" field was about to bring the same values as in the custom setting.
My knowledge of Apex triggers is limited, so I asked for the help on the internet. I received the help and the trigger was bringing target values in the sub campaign. However, the problem occurred on the parent campaign level. As far as I wanted to change the Event Region (which as I mentioned is part of the "Apex_Calculator__c" formula field), I started to receive the error message:
*
PopulateTarget: execution of BeforeUpdate caused by:
System.NullPointerException: Attempt to de-reference a null object:
Trigger.PopulateTarget: line 18, column 1
*
trigger PopulateTarget on Campaign (before insert, before update)
{
Map <String, Id> recordTypes = new Map <String, Id> ();
for (RecordType recordType : [SELECT Id, DeveloperName FROM RecordType WHERE sObjectType = 'Campaign'])
{
if (recordType.DeveloperName == 'Conference')
{
recordTypes.put(recordType.DeveloperName, recordType.Id);
}
}
for(Campaign campaign : Trigger.new)
{
// Make sure that the campaign record type is not in the map (in the map we keep the ones that we want to exclude)
if (recordTypes.get(campaign.RecordTypeId) == null && String.isNotBlank(campaign.Apex_Calculator__c) == true)
{
String target = DSTargets__c.getInstance(campaign.Apex_Calculator__c).Target__c;
campaign.DS_Target_Multiplier__c = Target;
}
}
}
I feel really lost what is wrong in here. Could anyone help me with this error?
Looks like you don't have DSTargets custom settings for some campaign.Apex_Calculator__c values.
Try this:
// Make sure that the campaign record type is not in the map (in the map we keep the ones that we want to exclude)
if (recordTypes.get(campaign.RecordTypeId) == null && String.isNotBlank(campaign.Apex_Calculator__c) == true)
{
if (DSTargets__c.getInstance(campaign.Apex_Calculator__c) == null)
{
System.debug('### A DSTargets named \'' + campaign.Apex_Calculator__c + '\' doesn't exist');
continue;
}
String target = DSTargets__c.getInstance(campaign.Apex_Calculator__c).Target__c;
campaign.DS_Target_Multiplier__c = Target;
}

Update Multi-Picklist on updating custom object

I have custom object KeywordAccountAssociation__c. This object has three fields
Account__c - Master-Detail(Account)
Keyword__c - Master-Detail(Keyword)
Compositecp__c - Text(255) (External ID) (Unique Case Sensitive)
I have a custom field in Account
DD_Segment__c - multi-picklist
Now I want to update (Insert is fine too) values of DD_Segment__c whenever KeywordAccountAssociation__c is updated. I could write trigger for this but I don't know how? I am new to Salesforce Development and my background is ruby (so getting accustomed to apex is bit difficult for me).
KeywordAccountAssociation__c has multiple rows of Account__c which has same account_id and those account_id are related to a record of custom object Keyword__c. I want to get all keywords related to one account and update in its (account's) multi-picklist. How can I achieve this? If you have doubts about this please do ask. Thanks!
One issue is related to learning to work with triggers in general, which can be started with Salesforce Apex Developer Documents on Triggers
but to answer your actual question, you would essentially need to build a trigger against your custom object that would update the related account. It might look something like this:
trigger keywordAccountUpdate on KeywordAccountAssociation__c (after insert, after update){
set<id> = new set<id>();
for (KeywordAccountAssociation__c a : Trigger.new)
accountIds.put(a.Account__c);
map<id,Account> accountMap = new map<id,Account>([select id, DD_Segment__c from Account where id in :accountIds]);
for (KeywordAccountAssociation__c kaa : Trigger.new){
if (AccountMap.containskey(kaa.Account__c)){
Account thisAccount = AccountMap.get(kaa.Account__c);
String s = thisAccount.DD_Segment__c + ';new value'; // Always add value
if ((thisAccount.DD_Segment__c).contains('second value')
s += ';second value';
AccountsToUpdate.add(new Account(id=thisAccount.id, DD_Segment__c = s));
}
}
}
Please keep in mind that I don't have the structure to test this trigger, I just free handded it, so YMMV.

Salesforce Custom Object Relationship Creation

I want to create two objects and link them via a parent child relationship in C# using the Metadata API.
I can create objects and 'custom' fields for the objects via the metadata, but the service just ignores the field def for the relationship.
By snipet for the fields are as follows:
CustomField[] fields = new CustomField[] { new CustomField()
{
type = FieldType.Text,
label = "FirstName",
length = 50,
lengthSpecified = true,
fullName = "LJUTestObject__c.FirstName__c"
},
new CustomField()
{
type = FieldType.Text,
label = "LastName",
length = 50,
lengthSpecified = true,
fullName = "LJUTestObject__c.Lastname__c"
},
new CustomField()
{
type = FieldType.Text,
label = "Postcode",
length = 50,
lengthSpecified = true,
fullName = "LJUTestChildObject__c.Postcode__c"
},
new CustomField()
{
type = FieldType.MasterDetail,
relationshipLabel = "PostcodeLookup",
relationshipName = "LJUTestObject__c.LJUTestObject_Id__c",
relationshipOrder = 0,
relationshipOrderSpecified = true,
fullName = "LJUTestChildObject__c.Lookup__r"
}
};
The parent object looks like:
LJUTestObject
ID,
FirstName, Text(50)
LastName, Text(50)
The child objext looks like:
LJUTestChildObject
ID,
Postcode, Text(50)
I want to link the parent to the child so one "LJUTestObject", can have many "LJUTestChildObjects".
What values do I need for FieldType, RelationshipName, and RelationshipOrder to make this happen?
TL;DR:
Use this as a template for accomplishing what you want:
var cf = new CustomField();
cf.fullName = "ChildCustomObject__c.ParentCustomField__c";
cf.type = FieldType.MasterDetail;
cf.typeSpecified = true;
cf.label = "Parent Or Whatever You Want This To Be Called In The UI";
cf.referenceTo = "ParentCustomObject__c";
cf.relationshipName = "ParentOrWhateverYouWantThisToBeCalledInternally";
cf.relationshipLabel = "This is an optional label";
var aUpsertResponse = smc.upsertMetadata(metadataSession, null, null, new Metadata[] { cf });
The key difference:
The natural temptation is to put the CustomField instances into the fields array of a CustomObject, and pass that CustomObject to the Salesforce Metadata API. And this does work for most data fields, but it seems that it does not work for relationship fields.
Instead, pass the CustomField directly to the Salesforce Metadata API, not wrapped in a CustomObject.
Those muted errors:
Turns out that errors are occurring, and the Salesforce Metadata API knows about them, but doesn't bother telling you about them when they occur for CustomFields nested inside a CustomObject.
By passing the CustomField directly to the Metadata API (not wrapped in a CustomObject), the call to upsertMetadata will still return without an exception being thrown (as it was already doing for you), but this time, if something goes wrong, upsertResponse[0].success will be false instead of true, and upsertResponse[0].errors will give you more information.
Other gotchas
Must specify referenceTo, and if it doesn't match the name of an existing built-in or custom object, the error message will be the same as if you had not specified referenceTo at all.
fullName should end in __c not __r. __r is for relationship names, but remember that fullName is specifying the field name, not the relationship name.
relationshipName - I got it working by not including __r on the end, and not including the custom object name at the start. I haven't tested to be sure other ways don't work, but be aware that at the very least, you don't need to have those extra components in the relationshipName.
Remember generally that anything with label in its name is probably for display to users in the UI, and thus can have spaces in it to be nicely formatted the way users expect.
Salesforce... really???
(mini rant warning)
The Salesforce Metadata API is unintuitive and poorly documented. That's why you got stuck on such a simple thing. That's why no-one knew the answer to your question. That's why, four years later, I got stuck on the same thing. Creating relationships is one of the main things you would want to do with the Salesforce Metadata API, and yet it has been this difficult to figure out, for this long. C'mon Salesforce, we know you're a sales company more than a tech company, but you earn trazillions of dollars and are happy to show it off - invest a little more in a better API experience for the developers who invest in learning your platform.
I've not created these through the meta data API like this myself, but I'd suggest that:
relationshipName = "LJUTestObject__c.LJUTestObject_Id__c
Should be:
relationshipName = "LJUTestObject__c.Id
as Id is a standard field, the __c suffix is only used for custom fields (not standard fields on custom objects). Also, it may be that the relationship full name should end in __c not __r, but try the change above first and see how you go.
SELECT
Id,
OwnerId,
WhatId,
Reminder_Date_Time__c,
WhoId,
Record_Type_Name__c,
Task_Type__c,
Assigned_Date__c,
Task_Status__c,
ActivityDate,
Subject,
Attended_By__c,
Is_Assigned__c
FROM Task
WHERE
(NOT Task_Status__c LIKE 'Open') AND
ActivityDate >= 2017-12-13 AND
(NOT Service__r.Service_State__c LIKE 'Karnataka')

Resources