+ Start a Discussion
uzairuzair 

Making the User Object standard field Unique.

Hi all,

 

I have a situation where, the Standard Field 'Extension' of User Object needs to be Unique.

 

Is there any way I can make this field unique.

 

Any help regarding this would be highly appreciated.

 

Thanks in Advance,

Mohammed Uzair.

Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

Your trigger should like this :

 

trigger ExtesionTrigger on User (before insert , before update)
{
    Set<String> setExtension = new Set<String>();
    for(User u : trigger.new)
        {
            
            Boolean isNewExt = setExtension.add(u.Extension);
            //This will ensure that in bulk insert you are not inserting two users with same extension
            if(!isNewExt)
                u.addError('Dulicate Extension');
        }
        
    List<User> ul = [Select id from User where Extension in: setExtension];
    
    if(ul.size() > 0)
        {
            trigger.new.get(0).addError('Dulicate Extension');
        }
    

}

 I hope this will help you.



All Answers

Sonali BhardwajSonali Bhardwaj

I think we cannot make a standard field unique.

 

There is one alternative solution. Create a custom field on User, make that unique. Write a trigger on User to update that field with Extension. If there is a duplicate value in Extension, trigger will try to copy it to your custom field and will throw error.

 

Thanks,

Sonali

PatcsPatcs

Hi

I used Trigger for Making the field Unique

 

see the below code

 

trigger ExtesionTrigger on User (before insert)
{
list <User> u1 = new List <User>();
u1 = [select Extension from User];
if(Trigger.isInsert)   
{
For(integer i=0;i<u1.size();i++)
{
for(User u2 : Trigger.New)
{
if(u1[i].Extension == u2.Extension)
{
u2.Extension.addError('Trigger Error::This value already Exist');
}
}
}
}
}

 

I think it will be usefull for you

 

Thanks!

Shashikant SharmaShashikant Sharma

Your trigger should like this :

 

trigger ExtesionTrigger on User (before insert , before update)
{
    Set<String> setExtension = new Set<String>();
    for(User u : trigger.new)
        {
            
            Boolean isNewExt = setExtension.add(u.Extension);
            //This will ensure that in bulk insert you are not inserting two users with same extension
            if(!isNewExt)
                u.addError('Dulicate Extension');
        }
        
    List<User> ul = [Select id from User where Extension in: setExtension];
    
    if(ul.size() > 0)
        {
            trigger.new.get(0).addError('Dulicate Extension');
        }
    

}

 I hope this will help you.



This was selected as the best answer