Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

In writing a unit test, I have to insert a Journal_c record. Instead of using Ids for several lookup fields, I've run soql queries assuming that the record Ids maybe different from test to production. I am, however, receiving an error when trying to assign both the Product_c and Contact__c fields values via query. The error I receive is "Illegal assignment from LIST to Id. Any help would be appreciated.

            Journal__c gift = new Journal__c();
        gift.RecordType = [SELECT Id, Name FROM RecordType WHERE SObjectType = 'Journal__c' and Name = 'Class Registration'];
        gift.Amount_Applied__c = 500;
        gift.Product__c = [SELECT Id FROM Product__c WHERE Name = 'Gift Certificate']; **Error on this line**
        gift.Contact__c = [SELECT Id FROM Contact WHERE Name = 'Daniel Mortensen']; **Error on this line**
        gift.Journal_Type__c = 'Gift Card';
        gift.Gift_Certificate_Code__c = 'testcode';
        gift.Date__c = system.today();
        gift.Status__c = 'Registration';
        insert gift;

Oddly enough, the RecordType assignment doesn't error out.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

The simple fix is to append .Id to the end of the failing queries. The proper fix would be:

List<RecordType> recordTypes = [SELECT Id, Name FROM RecordType WHERE SObjectType = 'Journal__c' and Name = 'Class Registration'];
List<Product__c> products = [SELECT Id FROM Product__c WHERE Name = 'Gift Certificate'];
List<Contact> contacts = [SELECT Id FROM Contact WHERE Name = 'Daniel Mortensen'];

Journal__c gift = new Journal__c();

if(!recordTypes.isEmpty()) {
  gift.RecordTypeId = recordTypes.get(0).Id;
}

if(!products.isEmpty()) {
  gift.Product__c =  products.get(0).Id;
}

if(!contacts.isEmpty()) {
  gift.Contact__c = contacts.get(0).Id;
}

gift.Amount_Applied__c        = 500;
gift.Journal_Type__c          = 'Gift Card';
gift.Gift_Certificate_Code__c = 'testcode';
gift.Date__c                  = System.today();
gift.Status__c                = 'Registration';
insert gift;

Using this method your code won't error out if one of the queries does not return a result.

share|improve this answer
    
Thanks Phil. I'll accept the answer when it lets me (3 minutes it says). Do you know why the RecordType query doesn't require the .id appending? –  dannymorty Jan 16 '13 at 15:56
    
because the recordType property is an object, If you'd used recordTypeId, then that would of returned a similar error. –  superfell Jan 16 '13 at 16:00
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.