3

I have written following code to insert records on junction object.

public static List<PDCN__c> addSelectedPDCNs(List<String> selectedRecords, String groupId) {
        system.debug('Entering addSelectedPDCNs');
        system.debug('Selected Records are-->'+selectedRecords);
        system.debug('Group Id is-->'+groupId);

        List < PDCN__c > lstAddId = [SELECT Id from PDCN__c where Name IN: selectedRecords];
        system.debug('Record Ids Are-->'+lstAddId);

        List<PDCNGrpJunc__c> lstJunc = new List<PDCNGrpJunc__c>();

        for( PDCN__c  pdcn : lstAddId ) {
            system.debug('Inside For Loop-->'+pdcn);
            PDCNGrpJunc__c juncRec = new PDCNGrpJunc__c();
            juncRec.PDCN__c = pdcn;
            juncRec.PDCN_Group__c = groupId;
            lstJunc.add(juncRec);
        }
        //insert lstJunc;
        try{
            system.debug('Trying Insert');
            system.debug('');
            insert lstJunc;
                }
         catch(Exception e)
        {
            System.debug('Exception Occured='+e.getMessage());
        }

        return lstAddId;
    }

I am getting error in juncRec.PDCN__c = pdcn; line as :-

Illegal assignment from PDCN__c to Id

Why do I get this error? How do I fix it?

7

So the field juncRec.PDCN__c is a Lookup field, (Consider it as a text/ID field)

where as in your loop pdcn is an object/record.(Not a text field)

In your code

juncRec.PDCN__c = pdcn;

What you are trying to do is assign an Object to a Text/Id field and hence you get an error. You can solve this by using id juncRec.PDCN__c = pdcn.Id;

for( PDCN__c  pdcn : lstAddId ) {
            system.debug('Inside For Loop-->'+pdcn);
            PDCNGrpJunc__c juncRec = new PDCNGrpJunc__c();
            ***juncRec.PDCN__c = pdcn.Id;***
            juncRec.PDCN_Group__c = groupId;
            lstJunc.add(juncRec);
        }
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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