I have created a trigger in Salesforce and i am fetching the result by soql query and store the result in a map, but it show the following error:
Error: Compile Error: Invalid initializer type List found for
Map: expected a Map with the same key and value types, or a
valid SObject List at line 7 column 25
trigger insertUpdateOwnerToSalesRep on Account (after insert, before update) {
if (trigger.IsAfter && trigger.IsUpdate) {
List<User> lstUser =[select id,name from User where Id in:(Trigger.NewMap).keySet()];
//Map<Id,String> ac=new Map<Id,String>([]);
Map<ID, String> m = new Map<ID, String>([select id,name from User where Id in:(Trigger.NewMap).keySet()]);
for(Account ac:Trigger.New) {
System.debug('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\t'+ac.ownerid);
if (ac.owner!=null) {
User user=ac.owner;
System.debug('!!!!!!!!!!!!!!\t'+user);
//ac.Sales_Rep__c=ac.owner.userName;
}
}
}
}
Please help, Thanks in advance.
First, You try to select users by Id, but when you call Trigger.NewMap.keySet(), you will get set of account Ids, not user (because trigger on account object). Possibly, you want to get all users related to account, so use AccountId in 'where' condition. Also I'd like to note, that you don't use 'lstUser' variable after getting.
As for getting Map from select, you should use Map<Id, User> instead of Map<Id, String>:
Map<Id, User> m = new Map<Id, User>([SELECT Id, Name FROM User where AccountId in :(Trigger.NewMap).keySet()]);
Related
I am trying to enter unique values to the Contact object. Here is the code:
List<Contact> conList = new List<Contact> {
new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),
new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),
new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),
new Contact()};
// Caroline Roth already exists so I want this code to update her record, not insert another Caroline Roth record
Database.UpsertResult[] srList = Database.upsert(conList, Contact.Fields.Name, false);
Salesforce's documentation states
"The upsert statement matches the sObjects with existing records by comparing values of one field. If you don’t specify a field when calling this statement, the upsert statement uses the sObject’s ID to match the sObject with existing records in Salesforce. Alternatively, you can specify a field to use for matching. For custom objects, specify a custom field marked as external ID. For standard objects, you can specify any field that has the idLookup property set to true. For example, the Email field of Contact or User has the idLookup property set."
I have two questions:
1) how can we see which fields on the Contact object have their idLookup property set to true
2) why am I getting the error in the subject line when I execute the code?
1:
Map<String, Schema.SObjectField> contacFieldsMap = Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap();
for (Schema.SObjectField field : contacFieldsMap.values()) {
Schema.DescribeFieldResult fieldResult = field.getDescribe();
if (fieldResult.isIdLookup()) System.debug(fieldResult.getName() + ' IS idLookup');
}
2: System.debug(Contact.Name.getDescribe().isIdLookup()); // false
Thank you very much for helping.
Problem Statement
I have a Map containing Map a string key and Salesforce Account,
I want to insert the Account but for each account, I want to create a new Map
with the same string as key and Account Id as value.
Tried
What actually I did I iterate over the map get the value to insert into database and then if the record is successfully inserted I add value to the new map, "I am inserting the account in the For Loop which is a bad Practice may hit DML Limit"
Sudo Code
Account acc = new Account(Name ='Test');
Map<String,Id> accMapId = new Map<String,Id>();
Map<String,Account> accMap = new Map<String,Account>();
accMap.put('A13',acc);
for(String accIterate : accMap.keySet()){
Database.SaveResult rt = Database.insert(accMap.get(accIterate));
if(rt.isSuccess()){
accMapId.put(accIterate,rt.id);
}
}
Question:
How can I avoid to insert the Account Object within for Loop and Build my accMapId
Use myMap.values() to "flatten" the map into a List (in your case list of accounts), insert the whole list. Such flattening just keeps references so the original accounts in the map will be silently updated with the generated record Id.
Map<String, Account> accounts = new Map<String, Account>{
'A13' => new Account(Name ='Test'),
'B14' => new Account(Name = 'Another')
};
insert accounts.values(); // You can use Database.insert() if you want, it accepts a list too.
Map<String, Id> idsByKey = new Map<String, Id>();
for(String s : accounts.keyset()){
idsByKey.put(s, accounts.get(s).Id);
}
System.debug(idsByKey);
Background: I need access account records in the apex class where name contains %
For example, the query should return below accounts
abcd10%
cdcd40%abcd
10%volume
When I execute the below query I am getting results in the workbench
select id, name from Account where Name LIKE '%\%%'
the same query If I execute in Anonymous window/apex execute getting no results.
List accList = [select id,name from Account where Name LIKE '%\%%'];
system.debug('accList :::'+accList.size());
If we observe the below image, it is appending extra / in the query and giving wrong results.
Can you please help me how to resolve this?
16:00:21:002 SOQL_EXECUTE_BEGIN [1]|Aggregations:0|SELECT id, name FROM Account WHERE Name LIKE '%\%%'
You could use a bind variable or dynamic SOQL.
String searchText = '%\\%%';
List<Account> accs = [SELECT Id, Name
FROM Account
WHERE Name LIKE :searchText];
System.debug(accs.size());
System.debug(accs);
// Or in dynamic query (looks bit crazier because ' has to be escaped too)
List<Account> accs2 = Database.query('SELECT Id, Name FROM Account WHERE Name LIKE \'%\\%%\'');
System.debug(accs2);
We have two standard objects account(parent) and contact (child ). i want to write a trigger to populate the lastname field of contact with the name field of account
The trigger below performs the same task but soql query is from child to parent .
I want the trigger which performs the same work but using soql query ( relationship query ) from parent to child .
trigger trgSetLastName on Contact (after insert)
{
List<Contact> lstConUpdate = new List<Contact>();
List<Contact> lstContact = [select id,Account.Name from Contact where
id in: trigger.newmap.keyset()];
for(Contact con: lstContact)
{
con.LastName = con.Account.Name;
lstConUpdate.add(con);
}
if(lstConUpdate.size() > 0){
update lstConUpdate;
}
}
i want a trigger for this .help
Step 1.
Build a Set<id> of Account Ids:
for (Contact c : trigger.new){
acctIdSet.add(c.AccountId);
}
Step 2.
Select related Accounts into a Map<Id,Account> using:
[SELECT {fields}
FROM Account
WHERE Id IN :acctIdSet];
Step 3.
Loop through trigger.new and extract the corresponding Account from your Map.
Step 4.
Update the LastName value on contact with the value on your Account - assuming it exists.
Step 5.
Make your trigger fire before insert:
trigger trgSetLastName on Contact (before insert, before update)
Log.add(new Cx_Trans_Log__c(
Object__c = 'Activity',
Object_Id__c = newActivity.Name,
Owner2_Id__c = newActivity.Owner1_Id__c,
I am using the above code to create a new log record when an activity is changed in salesforce.com. The Owner2_Id__c that is created from newActivity.Owner1_Id__c doesn't give me the name of the Owner1_Id__c (this is a lookup(User) field). Is there a way to get the User name that is displayed in Owner1 to Owner2?
The right way to do it is to make one query. For this example, I'll assume by activities you mean Tasks:
Set<Id> userIds = new Set<Id>();
for (Task t : Trigger.new) {
userIds.add(t.OwnerId);
}
Map<Id, User> users = new Map<Id, User>([SELECT Name FROM User WHERE Id IN :userIds]);
// then you could plug something like this into your existing code
String userName = users.get(newActivity.Onwer1_Id__c).Name;