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

hello friends, i want to create and update a record in object when user is created or update. Iam unable to update. Please look at my code and help

Iam unable to create look Relationship on user object as it doesnot  allow. I have created a Relationship on User database object.

1. Create a User lookup field on the Heroku User Database object.
- I have created it

2. Whenever the User is inserted create a copy of the user in Heroku User Database object and also update when the user is updated.
- when user is inserted its creating a copy but Iam unable to update when user is updated. Please look at my code

trigger UpdateHerokuUser on User (after insert, after update) {
    set<id> setid = new set<id>();
    set<id> updatedset = new set<id>();
    map<string ,id> mapid = new map<string,id>();
    list<Heroku_User_Database__c> hudlist = new list<Heroku_User_Database__c>();
    if(Trigger.isInsert && Trigger.isAfter){
        for(user u :{
         list<user> usr =[select id, name, Email,Username from user where id IN: setid];
        for(user u : usr){
        Heroku_User_Database__c hu = new Heroku_User_Database__c();;
        hu.Email__c= u.Email;
        hu.Username__c = u.Username ;   

       insert hudlist;
    if(Trigger.isUpdate && Trigger.isAfter){
      for(user u :{

Bryan Leaman 6Bryan Leaman 6

What do you mean you're "unable to update" ?
I don't see that you're doing anything with "updatedset" after adding updated user Ids to it. Are you needing help constructin list of Heroku_User_Database__c records so you can issue an update to it?  

If so, I think you could do something like the following (untested logic!) in the "if(Trigger.isUpdate && Trigger.isAfter) { ... } " block of code:

List<Heroku_User_Database__c> updateHud = new List<Heroku_User_Database__c>();

for (Heroku_User_Database__c hud : [
    select Id, Name, Email__c, User__c, Username__c
    from Heroku_User_Database__c
    where User__c in :updatedset
] ) {
    User u = Trigger.newMap.get(hud.User__c);
    if (u!=null) {   // u shold never be null, but better safe than sorry!
       updateHud.add(new Heroku_User_Database__c(
            Id=hud.Id, Name=u.Name, Email__c=u.Email, Username__c=u.Username