The test class is as follows:
I am trying to set the RecordType.Name in the test class but it gives me the message "System.NullPointerException: Attempt to de-reference a null object
class.TestAcctHierWarnDisplay.tstWarningDisplay1: line 45, column 3 External entry point". The record types exist.
I am not sure what I am missing.
Gets the exception at
myacct.RecordType.Name = 'Master Account';
You should set the record type by ID, not by name:
id idRT = [select Id from RecordType where SobjectType = 'Account' and DeveloperName = 'RTDevName].Id;
Account sAcct = new Account();
sAcct.RecordTypeId = idRT;
Also, note that I'm using developer name, this is the equivalent of the API name on object fields, the idea being that the actual name is a label and could be changed for frontend purposes.
FYI:
The reason you're getting an exception is because the account is not assigned a record type at this stage, so myacct.RecordType is null, which you're trying to dereference when accessing the Name field on it.
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
I am new to Salesforce Development, I have tested a similar query to this in a sandbox Org which worked, however when trying to update records in the live Org I am having some issues.
The issue and context is as follows:
I am trying to update the 'Record Type' field of certain Job records through Apex DML. I have opened the Developer Console and run a query:
SELECT Name, GW_Volunteers__Campaign__c, RecordtypeId FROM GW_Volunteers__Volunteer_Job__c WHERE GW_Volunteers__Campaign__c = '7010O000001P2XIQA0' and RecordTypeId = null LIMIT 5
This works fine and will show me the first 5 job records where there is no assigned record type, which is what I want to update.
The problem is when I am opening "execute anonymous" window and entering this code:
GW_Volunteers__Volunteer_Job__c [] bjobs = [
SELECT Name, GW_Volunteers__Campaign__c, RecordTypeId FROM GW_Volunteers__Volunteer_Job__c WHERE GW_Volunteers__Campaign__c = '7010O000001P2XIQA0' and RecordTypeId = null LIMIT 5];
bjobs.RecordTypeId='0120O000000LAY6QAO';
update bjobs;
I keep getting the following error:
Line: 3, Column: 11 Variable does not exist: RecordTypeId
Unless I have missed something very obvious, I cannot figure out why this is happening. Since it recognizes that variable in the query fine and a similar query (where I also updated the RecordTypeId) in the sandbox worked.
Thank you,
YH
The problem here is, you cannot assign bjobs.RecordTypeId='0120O000000LAY6QAO';. You know, bjobs is an array of GW_Volunteers__Volunteer_Job__c.
So, what you need to do is,
GW_Volunteers__Volunteer_Job__c [] bjobs = [
SELECT Name, GW_Volunteers__Campaign__c, RecordTypeId FROM GW_Volunteers__Volunteer_Job__c WHERE GW_Volunteers__Campaign__c = '7010O000001P2XIQA0' and RecordTypeId = null LIMIT 5];
for(GW_Volunteers__Volunteer_Job__c job : bjobs)
{
job.RecordTypeId='0120O000000LAY6QAO';
}
update bjobs;
Hope, this will work.
We are trying to move a task from one contact to another in a trigger. the task is created by ListEmail functionality.
We are getting an exception if re-assigning the WhoId. Exception:
Update failed. First exception on row 0 with id 00T1N00002TXv3jUAD; first error: FIELD_INTEGRITY_EXCEPTION, Related To ID: id value of incorrect type: 0XB1N000000XaCuWAK: [WhatId]
This is the sample code:
List<Task> task = [SELECT Id, RecordTypeId, WhoId, WhoCount, WhatCount, Subject, AccountId, TaskSubtype, AccountId__c, EmailListWhatID__c FROM Task where Id ='00T1N00002TXv3jUAD'];
system.debug('task = ' + task);
Task tk = task.get(0);
tk.WhoId = '0031N00001UvZDpQAN';
database.update(tk);
Given that the exception relates to the WhatId, I suspect that whatever the custom object type referred to by the prefix 0XB is, it does not have Allow Activities active on the object metadata.
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()]);
I'm going in circles on getting the id of NDB Datastore.
I have setup the webapp2.RequestHandler to catch the email and get the ID. Basically my goal is to delete an entity, but if I pass the email address to get the ID of the entity, I'm stump, because it gives me results I was just getting. I used ID instead of key_name.
I tried finding the ID by querying via email, but it seems like using query does not have a method attribute to find the id.
def get(self,email):
user = users.get_current_user()
if user:
user_key = ndb.Key('UserPrefs',user.email())
contacts = Contact.query(Contact.email==email,ancestor=user_key)
self.response.write(contacts.id) # there is no attribute such as Contact.id
I tried to find the ID by getting the key, but when I displayed the key, it showed me whatever value I have in the email variable
def get(self,email):
user = users.get_current_user()
if user:
user_key = ndb.Key('UserPrefs',user.email())
contact_key = ndb.Key('Contact',email,parent=user_key)
self.response.write(contact_key.id())
Real Question: So, given that I do not have the ID, how do I find the correct ID inside an entity if I saved my entities via id and not key_name?
Here are the mixture of codes that I'm trying out.
def get(self,email):
user = users.get_current_user()
if user:
user_key = ndb.Key('UserPrefs',user.email())
contact_key = ndb.Key('Contact',email,parent=user_key)
contacts = Contact.query(Contact.email==email,ancestor=user_key)
contact = contacts.get()
contact_key.delete()
# self.response.write(contact.name) # this works
self.response.write(contact_key.id()) # this does not work because I do not have the entity id, and I'd like to get it blindfolded. Is there a way?
Here is my Model for Contact.
class Contact(ndb.Model):
name = ndb.StringProperty()
phone = ndb.StringProperty()
email = ndb.StringProperty()
dateCreated = ndb.DateTimeProperty(auto_now_add=True)
dateUpdated = ndb.DateTimeProperty(auto_now=True)
The docs state:
The identifier may be either a key "name" string assigned by the application or an integer numeric ID generated automatically by the Datastore.
Since you are defining the name property on your Contact class, this is used as the identifier. (You don't want that because in real world different users can have same names)
So if you want NDB to generate numeric IDs for your entities, rename the name property to something else, e.g. username.
Update: let's go step by step:
Problem with the first example is that you are trying to get id on the Query. Query class has no id property defined on it. You should call get() on it:
# get() or fetch() should be called on query to return some data
contacts = Contact.query(Contact.email==email,ancestor=user_key).get()
self.response.write(contacts.id) # there is no attribute such as Contact.id
Problem with the second piece of code is that you are just initialising a Key and providing email as id - the second param of constructor is the id and you are providing email as value. Hence you are getting the email out. Also, there is no database operation here.
Note: the identifiers, which are id, key, urlsafe, or value (for the query) should be passed from the HTTP Request by webapp2.RequestHandler from a parsed url or HTTP POST, GET, PUT, or DELETE.
If you do not have any identifiers or values passed from an HTTP request, it could be difficult to access the specific entity (or the record). So, it is important to take note to pass a form of identifier or value to access the specific entity (or the record in database terms).
So, you can do the following to get the id:
Access by value:
def get(self,email):
user = users.get_current_user()
if user:
user_key = ndb.Key('UserPrefs',user.email())
contacts = Contact.query(Contact.email==email,ancestor=user_key)
contact = contacts.get()
id = contact.key.id() # this access the entity id directly because you have the data.
self.response.write(id)
Access by urlsafe:
def get(self,urlString):
user = users.get_current_user()
if user:
contact_key = ndb.Key(urlsafe=urlString) #urlString refers to the key of contact
contact = contact_key.get()
id = contact.key.id() # this access the entity id directly because you have the data.
self.response.write(id)
Access by HTTP POST Request:
def post(self):
user = users.get_current_user()
if user:
user_key = ndb.Key('UserPrefs',user.email())
email = self.request.get('email')
contacts = Contact.query(Contact.email==email,ancestor=user_key)
contact = contacts.get()
id = contact.key.id() # this access the entity id directly because you have the data.
self.response.write(id)