+ Start a Discussion
Kiran Jain 15Kiran Jain 15 

Duplicate Value Found: SetupOwnerId Duplicates Value On Record With Id in custom Setting

hy experts,
I have a custom setting in which a custom field UserName__c.I want to store userName in custom setting field when any user is insert. but simply when i set username from trigger and tried to insert custom setting I got below error.
Duplicate Value Found: SetupOwnerId Duplicates Value On Record With Id
I have goggled many time but not got any specific answer.
can someone tell me what mistake I made. below is my trigger referance.
 
if(trigger.isAfter && trigger.isInsert){
        list<test_Setting__c> lstSetting = new list<test_Setting__c>();
        for(user u : trigger.new){
            test_Setting__c testSetting = new test_Setting__c();
            testSetting.UserName__c = u.userName;
            lstSetting.add(testSetting);
         } 
        if(lstSetting.size() > 0){
            insert lstSetting; 
        }
       
    }
Thanks In Advance


 
ravi soniravi soni
hI Kiran,
I have also faced the same problam 2 days ago. and I did some changes. you can be followed them and find your solution.
Actually this problam comes when a record  already created in custom setting and setupOwnerId must be unique.

so now you need unique setupOwnerId. so simply you can set setupOwnerId with userId when you are doing set UserName__c,
get ref. from below trigger.
if(trigger.isAfter && trigger.isInsert){
        list<test_Setting__c> lstSetting = new list<test_Setting__c>();
        for(user u : trigger.new){
            test_Setting__c testSetting = new test_Setting__c();
            testSetting.UserName__c = u.userName;
            testSetting.SetupOwnerId = u.Id;
            lstSetting.add(testSetting);
         } 
        if(lstSetting.size() > 0){
            insert lstSetting; 
        }
       
    }
try above trigger and  let us know what is your status. this solution is helpful or not.
don't forget to mark it as best answer.
Thank you