function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chris MarzellaChris Marzella 

Why I am getting Illegal assignment from contact to id?

trigger CreateCase on Account (after insert) {
    for(Account hw : Trigger.new){
        
        List<Contact> contact = [SELECT Id FROM Contact LIMIT 1];
        
        Case c = new Case();
        c.AccountId = hw.Id;
        c.ContactId = contact[0];
        c.Status = 'New';
        c.Origin = 'Web';
        
        insert c;
    }
}
Best Answer chosen by Chris Marzella
William TranWilliam Tran
try this:   c.ContactId = contact[0].id;

Thx

All Answers

William TranWilliam Tran
try this:   c.ContactId = contact[0].id;

Thx
This was selected as the best answer
James LoghryJames Loghry
Because you're trying to convert contact[0], which is the Contact or an sObject into a primitive Id field.  Instead, you should be referencing the Id field of the contact, such as contact[0].Id.

Furthermore, your trigger is performing an insert of a contact for each new account.  This means that you may try to issue 200 DML statements if you bulk load Accounts, where you really only need a single DML statement.  You really should bulkify your trigger.  You can read more about bulkification here: https://developer.salesforce.com/blogs/developer-relations/2015/01/apex-best-practices-15-apex-commandments.html
Chris MarzellaChris Marzella
Thanks William that cleared up the error. James I am just starting to learn Apex so this is a little new. I will check out the link you provided.