• Brandon Nelson
  • NEWBIE
  • 14 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 13
    Questions
  • 13
    Replies
Hello! I have looked online for this and found 2 answers but neither truly make sense to me as to what the triggers are actually doing. I was wondering if someone could help me accomplish and understand an apex trigger. The requirement is that a case cannot be closed if it has an associated task that is still open. Thank you!!!!
i have requirement to create a case if case was not being created manually for that month for particular accounts. i have stored all account in custom object (where i am going to store the account which i want to apply above proceed. i am not sure what query i should write
 
global class BatchCaseRecord implements Database.Batchable<sObject> {
    global final string query;
    DateTime dt = DateTime.now();
    String monthName = dt.format('MMMMM');
    Integer year = Date.today().year();
    global Database.QueryLocator start(Database.BatchableContext bc) {
// what will be query to get the record which need to processed 
        string query = 'SELECT Account__c FROM CaseRecord_Account__c Limit 2000';

        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext bc, List<CaseRecord_Account__c> CNbatch) {
        List<Case> caserecords = new List<Case>();
        String rtype = [select id from recordtype where sobjecttype = 'Case' and name = 'CaseRecord'].id;
        for (CaseRecord_Account__c CN : CNbatch) {
            for (integer i = 0; i < AccountList.size; i++) {
                //        
                //what will be if codition to check if case is not created this month 
                case c1 = new case();

                c1.Month__c = monthName.left(3);
                c1.Year__c = String.valueOf(year);
                c1.Reason__c = 'Phone';
                c1.RecordTypeId = rtype;
                c1.Client_Account__c = CN.Account__c;
                caserecords.add(c1);
                if (!caserecords.isEmpty()) {
                    database.insert(caserecords, false);
                }
            }
        }
    }
//}
/// send the email to account user for those case is created


    global void finish(Database.BatchableContext bc) {
        AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id = :BC.getJobId()];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{
                a.CreatedBy.Email
        };
        mail.setToAddresses(toAddresses);
        mail.setSubject('Match Merge Batch ' + a.Status);
        mail.setPlainTextBody('records processed ' + a.TotalJobItems + 'with ' + a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{
                mail
        });
    }
}

 
I have a batch class that updated a custom object when a trigger runs. 

Sceniro: Someone adds a state to a multi select picklist. The trigger will grab all states, and throw the last state in the variable. I then grab the id of the record in another variable. I pass both of those variables over to a batch class and run a query on another custome object, and update the fields. 

Problem is, when I get to the update part, the first field (Flow_Kick_Off__c) gets the value of the variable, but the other field (Territory__c) does not..... I don't understand why one field is getting updated, but not the other. 

Here is the trigger:
trigger updateFacility on Territory__c (before insert, before update) {
    
    //Adding a state index is -1. Removing a state index is normal.
    
    String[] oldStates;
    String[] newStates;
    Integer countStates;
    Integer countOldStates;
    Integer countNewStates;
    String terrID;
    String terrState;
    
    if(Trigger.isUpdate) {
        for(Territory__c oldTerr : Trigger.old) {
            oldStates = oldTerr.states__c.split(';');
            countOldStates = oldStates.size();
            terrID = oldTerr.Id;
        }
        
    }
    
    else if(Trigger.isInsert) {
        
    }
    
    for(Territory__c newTerr : Trigger.new) {
        newStates = newTerr.states__c.split(';');
        countNewStates = newStates.size();
        
        if(countNewStates > countOldStates) {
            terrState = newStates[countNewStates-1];
            System.debug('TRIGGER ID = ' + terrID);
            System.debug('TRIGGER STATE = ' + terrState);
            FacilityUpdates db = new FacilityUpdates(terrState, terrID);
            database.executeBatch(db, 75);
        }
        
        else {
            
        }
        
    }
    
    
}

Here is the class: The only field that is not updating is (Territory__c)
global class FacilityUpdates implements Database.Batchable<sObject> {
    
    global String terrState;
    global String terrID;
    
    
    global FacilityUpdates(String myStates, String terID){
        terrState = myStates;
        terrID = terID;
        system.debug('STATE = ' + myStates);
        system.debug('ID = ' + terID);
    }
    
    public String query;
    
    global Database.querylocator start(Database.BatchableContext BC){
        
        //String newString = '\'';
        system.debug('INSIDE EXECUTE STATE = ' + terrState);
        
        query = 'Select id, Name, physical_State__c, Territory__c FROM Facility__c WHERE physical_State__c = :terrState';
        //query = 'Select id, Name, physical_State__c, Territory__c FROM Facility__c WHERE Territory__c = :terrId AND physical_State__c includes ' + states;
        
        
        system.debug(query);
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        List<Facility__c> accns = new List<Facility__c>();
        for(sObject s : scope)
        {
            Facility__c a = (Facility__c)s;
            a.Flow_Kickoff__c = terrID;
            a.Territory__c = terrID;
            accns.add(a);
        }
        update accns;
        
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }
    
}

 
I have Object 1 and Object 2. I have a field on Object 1 that looks at Object 2 and pulls that value from Object based on another field in Object 1. 

When someone updates the field on Object 2, I need it to update ALL records on Object 1. I'm trying to write a trigger to do this, but I keep running into TOO MANY STATEMENTS error. PLEASE HELP!
 
trigger UpdatedTerritoryByState on Territory_By_State__c (after update) {
    
    String tbsState;
    String tbsTerritory;
	String updatedTerritory;
    String facID;

	//Setting the Territory By State vars    
    for(Territory_By_State__c tbs : Trigger.new) {
        tbsState = tbs.State__c;
        tbsTerritory = tbs.Territory__c;
    }
    
    
    List<Facility__c> facilityToUpdate = new list<Facility__c>();
    List<Facility__c> updateFacility = [SELECT Facility__c.id, Facility__c.physical_state__c FROM Facility__c WHERE Facility__c.physical_State__c = :tbsState];
    for(Facility__c fac : updateFacility) {
        Facility__c f = new Facility__c();
        f.Id = fac.Id;
        f.Territory__c = tbsTerritory;
        facilityToUpdate.add(f);
    }
    
    update facilityToUpdate;
    

}

 
I have two object
1. Contacts__c
2. Sales_VP_By_Territory__c

On the Contacts__c object, I have two fields
1. Sales VP (Picklist / read only)
2. Territory (Picklist)

On the Sales_VP_By_Territory__c, I have two fields. This object is hidden from users
1. Sales VP
2. Territory

On the Contacts__c object, I would like the user to select the Territory. Once they select one and save the record, a Trigger will fire and store the current record Territory in a variable and then execute a SOQL query on the Sales_VP_By_Territory object and get the Sales_VP__c field value and store it in a variable. Then it will go back and populate the Contact__c records field Sales_VP__c.

Here is my code, but the issue is, it keeps telling me 
"GetSalesVP: data changed by trigger for field Sales VP: bad value for restricted picklist field: (Sales_VP_By_Territory__c:{Sales_VP__c=Brandon Nelson, Id=a0z3a000007e8LSAAY})"

If you notice in my SOQL query, I'm not pulling ID so why is it trying to insert it?
 
trigger GetSalesVP on Contact__c (before insert, before update) {
   	
    String territory;
    String getSalesVP;
    
    for(Contact__c c : Trigger.new) {
        territory = c.Territory__c;
        
	List<Sales_VP_By_Territory__c> getSalesVP = [SELECT Sales_VP__c FROM Sales_VP_By_Territory__c WHERE territory__c = :territory]; 
          
    c.Sales_VP__c = String.valueOf(getSalesVP);
        
    }  
}

 
I'm wondering if this is just a glitch in Salesforce and if anyone has any workaround. I currently have a Trigger on ContentDocumentLink that sends an email to the owner of a custom object record when a File or Note is created and attached to that record. The trigger also attaches file information and the body of the Note if it's a ContentNote being inserted. The trigger handles the logic in differentiating Notes from other file types. The problem is when the user hits the button to create a new Note in classic or in the Console, an empty, untitled, new note record is inserted instantly firing my trigger before the user has time to add content to the body. In Lightning it at least allows the user to fill out the header of the note before saving, but saves before the note body is filled out. Cancelling out of creating the note still leaves the blank note saved and attached to the record. Any help in understanding why the note saves before the user hits the save button would be appreciated.
APEX Noob here :)

So I found out that I can not use a field of TEXT format when using an EMAIL ALERT. What I did was created a field called "Email" and gave it an EMAIL format. I would like to update this field with the email address based on the name in another field.

Layout:
Case Object: I have a field named: Wealth Planner (This is a lookup field linked on the EMPLOYEES custom object)
Case Object: I have a field named: Email (I would like this field to populate the EMAIL address for Wealth Planner (above) on the EMPLOYEES object)

I just dont know enough APEX to do this yet. Any help????

I hope this make sense.....
I have a SOQL query wrote out, but I can't (Don't know how) to access it in VisualForce. Can someone please help me with the Apex page? I can return the main columns but I don't know how to return the sub query in the columns? 

APEX CLASS CODE
public with sharing class DisplayAttachments{ public List<Account> Records {get; set;} public DisplayAttachments(){ String userId = userinfo.getUserName(); Records = [select Id,Name,(Select Id,Name from Attachments) From Account Where CreatedBy.Name = iserId]; } }
VISUALFORCE PAGE
<apex:page controller="DisplayAttachments"> <apex:pageBlock title="My Attachments"> <apex:pageBlockTable value="{!Records}" var="Record"> <apex:column > <apex:facet name="header">Client ID</apex:facet> <apex:outputText value="{!Record.ID}"/> </apex:column> <apex:column > <apex:facet name="header">Client Name</apex:facet> <apex:outputText value="{!Record.Name}"/> </apex:column> <apex:column > <apex:facet name="header">Attachment ID</apex:facet> <apex:outputText value="{!Record.ID}"/> </apex:column> <apex:column > <apex:facet name="header">Attachment Name</apex:facet> <apex:outputText value="{!Record.Name}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </apex:page>