• Che SFDC
  • NEWBIE
  • 160 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 23
    Questions
  • 31
    Replies
Dear all, I`m new to apex and I need help with issue below. I have a "New Case" custom button on Opportunity record which allows me to create Case. When clicked on "New Case" button, I can select record type and page gets redirected to standard page or visualforce page using redirect class below. Code works fine but I`m unable to auto-populate fields when record type with standard page is selected. Fields are not getting auto populated the way it happens with standard functionality. For example, I`m not able to auto-populate Opportunity Name, Stage or Close Date while creating new case record. Can someone please help? Any help is much appreciated. Thank you!

Redirect VF page
<apex:page standardController="Case" extensions="Redirect" action="{!Redirect}">

</apex:page>

Redirect class
 
public with sharing class Redirect{

    private Id id;


 private ApexPages.StandardController controller;
 public String retURL {get; set;}
 public String saveNewURL {get; set;}
 public String rType {get; set;}
 public String cancelURL {get; set;}
 public String ent {get; set;}
 public String confirmationToken {get; set;}


 public Redirect(ApexPages.StandardController controller) {

  this.controller = controller;
  retURL = ApexPages.currentPage().getParameters().get('retURL');
  rType = ApexPages.currentPage().getParameters().get('RecordType');
  cancelURL = ApexPages.currentPage().getParameters().get('cancelURL');
  ent = ApexPages.currentPage().getParameters().get('ent');
  confirmationToken = ApexPages.currentPage().getParameters().get('_CONFIRMATIONTOKEN');
  saveNewURL = ApexPages.currentPage().getParameters().get('save_new_url');
 }

 
 public PageReference redirect(){
  
  PageReference returnURL;
  // Redirect if Record Type corresponds to custom VisualForce page
  if(rType == '0121b0000009t60') {
   returnURL = new PageReference('/apex/vfcasepage');
  }
  else {
   returnURL = new PageReference('/500/e?nooverride=1');
  }

  returnURL.getParameters().put('retURL', retURL);
  returnURL.getParameters().put('RecordType', rType);
  returnURL.getParameters().put('cancelURL', cancelURL);
  returnURL.getParameters().put('ent', ent);
  returnURL.getParameters().put('_CONFIRMATIONTOKEN', confirmationToken);
  returnURL.getParameters().put('save_new_url', saveNewURL);
    returnURL.getParameters().put('nooverride', '1');
  returnURL.setRedirect(true);
  return returnURL;

 }

 public PageReference cancel() {
          PageReference pr = new PageReference('/500/o');
          pr.setRedirect(true);
          return pr;
     }


}


 
All, I was wondering if someone can help me. Below is my trigger which is very simple. It will take Feed item from Account page and will repost it to Chatter group. Trigger works fine for Post and Link, but when I`m trying to attach exisitng File from content library and share it, it generates below error.

Field_Integrity_Exception, ContentFileName is required field for feed post of type ContentPost. Content File Name: [ContentFileName]

Can someone pls suggest a workaround?
trigger autoPostFromAccToGroup on FeedItem (before insert) {

List <FeedItem> Feedlist = New List <FeedItem> ();

 Map <id,Account> AccMaps = New Map <id, Account> () ;
Set <Id> idsets = New Set <Id> ();

      For (Feeditem fe : Trigger.New) {
          String idStr = fe.Parentid;
           if(idStr.startsWith('001')){
                     idsets.add(idStr);    
           
      
      }
    }
    
       List <Account> accs = [SELECT ID, Owner.Name, RecordTypeid, Name FROM Account WHERE id IN :idsets ];
       
           for (Account  acc : accs) {
                   
            AccMaps.put(acc.id,acc);      

    
        
        
                   for (Feeditem f : Trigger.New) {
                   
                   if (AccMaps.get(f.parentid).Recordtypeid == '012300000000uth') {  
                   
            FeedItem FI = New FeedItem ();
            FI.ParentId = '0F91b0000008ThRCAU' ; 
            FI.TYPE = F.TYPE; 
            Fi.IsRichText = True;
            FI.Body = F.Body;
            Fi.LINKURL = F.LINKURL;
            Fi.TITLE = F.TITLE;
            Fi.ContentFileName = F.ContentFileName;
            Fi.ContentData = F.ContentData ;
            Fi.ContentDescription= F.ContentDescription;
           Fi.CreatedByid = UserInfo.getUserId() ;


            Feedlist.add(FI);

        
        }
        }
        }
         insert Feedlist;  
        
}

 
All, below is my trigger which increases sharing access when a new Account Team Member is entered on an account. Trigger works fine but this trigger does not run when new Account Team Member is created. It only works when account is updated (which I understand because I have created a trigger on Account object). From what I understand, triggers cannot be created on Account Team Member. Is there a workaround?
 
trigger teamsharing on Account (before update) {
    
          List<AccountShare> shares = new List<AccountShare>();
        Set <ID> accids = New Set <ID> ();
         For ( Account A: Trigger.New) {
            accids.add(A.id);
    }

       List <AccountTeamMember> ATMs = [SELECT AccountId, TeamMemberRole, UserId, AccountAccessLevel FROM AccountTeamMember WHERE AccountId in: accids];
    
    For (AccountTeamMember AT : ATMs ) {

    
                     AccountShare aShare = new AccountShare();
          aShare.AccountId              = AT.AccountId;
          aShare.UserOrGroupId          = AT.UserId;
          aShare.AccountAccessLevel     = 'Edit';
          aShare.ContactAccessLevel     = 'Edit';
          aShare.OpportunityAccessLevel = 'Edit';
          shares.add(aShare);
    
        
    }
    Insert Shares;
}

 
All, need help with a trigger. This trigger copies record from Contacts standard object to Strategic Contacts custom object. I want this code to copy all Contacts in account and create Strategic Contacts. For example, if account has 4 contacts, then 4 strategic contacts should be created. Code is currently inserting only 1 record. Can someone pls help?
 
trigger StrategicContactAutoCr on Account (after update) {

      List<Dev_che_123__Strategic_Contacts__c> STToInsert = new List<Dev_che_123__Strategic_Contacts__c>();
    
    Map <Id,Contact> ContactMaps = New Map <Id,Contact> ();
    Set <Id> accids = New Set <ID> ();
    for (Account acc: Trigger.New ) {
        if (acc.Strategic_Account__c != null ) {
            accids.add(acc.id);
				    system.debug('total strt accs' + accids);
            
        }
        
    }  
    
    List <Contact> Con = [SELECT AccountID, FirstName, LastName FROM Contact WHERE AccountID IN :accids ];
    system.debug('total Con List' + Con);

    For (Contact C : Con ) {
        If (C.AccountID != null) {
            ContactMaps.put(C.AccountID, c);
                system.debug('total Con List after Put Id and Contact in Map' + Con);
               
                
            }
            
        }
    
          
    
    for (Account acct: Trigger.New ) {
        if (acct.Strategic_Account__c != False ) {
            
            
                Dev_che_123__Strategic_Contacts__c SC = new Dev_che_123__Strategic_Contacts__c ();
  				SC.Dev_che_123__Account__c = acct.id;
				SC.Dev_che_123__First_Name__c = ContactMaps.get(acct.Id).FirstName;
				SC.Dev_che_123__Last_Name__c = ContactMaps.get(acct.Id).LastName;
				STToInsert.add(sc);
            
        }
        		
    }
    
        insert STToInsert;

       
    }

 
Dear All,
Here is my trigger. I want to update "Deactivated on" text field everytime Opportunty "Active" field changes to False. Trigger works fine but the issue is that it runs everytime Inactive user record is updated. I only want this trigger to run when user changes from True to False. Can someone please help?
 
trigger DeactivateDate on User (before update) {

String deastat = 'User license is deactivated on ';


User us = [select Name from user where id=:userinfo.getuserid()];
string username = us.Name;


            for (User u : Trigger.new) {
            
                DateTime dt = u.LastModifieddate;
                String formattedDt = dt.format('MM-dd-yyyy @ hh:mm:ss');

            if (u.IsActive == False){
            u.Deactivated_On__c = deastat + formattedDt   + ' by ' +  username;

            }
            
            } 
            

}

 
Dear all, I need help with pop up window. Requirement is that everytime Opportunity Close Date is changed on edit page, pop should appear with a notificaton and then allow users to save the record. I`m new to VF and Apex. Can someone please help me with VF code or Jscript that works?

Any help is appreciated. Thanks!
Dear all,
Below is my visualforce page. City is a dependent field which works with Country. Everytime I change the stage and save the page, city field gets reset when I advance to next stage. For some reason, City field is not retaining values on next stage. For example, if I select country as USA in "Prospecting" stage and save the page with "New York" as city. In next stage which is "Needs Analysis", City field automatically resets to blank. Can someone please help with a controller or a visualforce workaround?


 
<apex:page standardController="Opportunity" sidebar="false">
  <apex:sectionHeader title="Edit Opportunity" 
                      subtitle="{!opportunity.name}"/>
  <apex:form >
    <apex:pageBlock title="Edit Opportunity" id="thePageBlock" 
                    mode="edit">
      <apex:pageMessages />
      <apex:pageBlockButtons >
        <apex:commandButton value="Save" action="{!save}"/>
        <apex:commandButton value="Cancel" action="{!cancel}"/>
      </apex:pageBlockButtons>
      <apex:actionRegion >
        <apex:pageBlockSection title="Basic Information" 
                               columns="1">
          <apex:inputField value="{!opportunity.name}"/>
          <apex:pageBlockSectionItem >
            <apex:outputLabel value="Stage"/>
            <apex:outputPanel >
              <apex:inputField value="{!opportunity.stageName}">
                <apex:actionSupport event="onchange" 
                                    rerender="thePageBlock"
                                    status="status"/>
              </apex:inputField>
              <apex:actionStatus startText="applying value..." 
                                 id="status"/>
            </apex:outputPanel>
          </apex:pageBlockSectionItem>
          <apex:inputField value="{!opportunity.amount}"/>
          <apex:inputField value="{!opportunity.closedate}"/>
        </apex:pageBlockSection>
      </apex:actionRegion>
      
      <apex:pageBlockSection title="Closed Lost Information" 
            columns="1" 
            rendered="{!opportunity.stageName == 'Prospecting'}">
        <apex:inputField value="{!opportunity.Country__c}"  
              required="true"/>
        <apex:inputField value="{!opportunity.City__c}"/>
      </apex:pageBlockSection>
      
      <apex:pageBlockSection title="Closed Lost Information" 
            columns="1" 
            rendered="{!opportunity.stageName == 'Needs Analysis'}">
        <apex:inputField value="{!opportunity.Country__c}"  
              required="true"/>
        <apex:inputField value="{!opportunity.City__c}"/>
      </apex:pageBlockSection>
      
    </apex:pageBlock>
  </apex:form>
</apex:page>

 
Dear all, I`m new to apex and I would like to understand how can I add multiple validation rules to this extension. Our org has multiple validation rules and we would like to populate that on VF page. Can someone pls give me an example of how I can use multiple Try/Catch statements in dosave() method below. Whatever I`m trying is failing. Please help!!!

Thanks!
 
public with sharing class ExampleTP {

    String oppId;
    String ownerId;
    private final Opportunity Oppty;
 
    public ExampleTP (ApexPages.StandardController stdController) {
        oppId = stdController.getId();
        Oppty = (Opportunity) stdController.getRecord();
        ownerId = oppty.OwnerId;
        if(oppty.StageName == null)
          oppty.StageName = 'Identified Opportunity';
        if(oppty.Probability == null)
            oppty.Probability = 0;
    }



public transient Map<String, Decimal> probabilityStageNameMap;

public PageReference changeStageName() {

if (probabilityStageNameMap == null) {
 probabilityStageNameMap = new Map<String, Decimal>();
for (OpportunityStage oppStage : [Select MasterLabel, DefaultProbability
                                    From OpportunityStage]) {
 probabilityStageNameMap.put(oppStage.MasterLabel, oppStage.DefaultProbability);
   }
  }

 if (probabilityStageNameMap.containsKey(Oppty.StageName)) {
   Oppty.Probability = probabilityStageNameMap.get(Oppty.StageName);
 
 }

  return null;
 }
 
  public PageReference doSave()
  {
  Try
   {
      if (Oppty.LeadSource == 'Marketing Campaign' && Oppty.CampaignId == null )
  
  {
    upsert oppty;
     return new PageReference('/' + 'apex/TPDynamicOppNEWLayout?oppId= + Oppty.Id'); 
        }
        }
catch(Exception e)
        {
            Apexpages.addMessage(new Apexpages.message(ApexPages.Severity.Error,'Campaign is required'));
            }
            return null;
  }
        


}

 
Dear All, I`m new to Apex and I`m stuck with this issue. I have a standardcontroller and below extension. What I want to do is override the standard Save button with save() method so that it redirects me to the Opportunity view page. Save works fine but it doesnt throw any error. It directly save the page. Can someone pls help? 
Thanks!
 
public with sharing class myclass {

    String oppId;
    String ownerId;
    private Opportunity Oppty;
 
    public myclass(ApexPages.StandardController stdController) {
        oppId = stdController.getId();
        Oppty = (Opportunity) stdController.getRecord();
        ownerId = oppty.OwnerId;
        oppty.StageName = 'Identified Opportunity';
         oppty.Probability = 0;
    }



public transient Map<String, Decimal> probabilityStageNameMap;

public PageReference changeStageName() {

if (probabilityStageNameMap == null) {
 probabilityStageNameMap = new Map<String, Decimal>();
for (OpportunityStage oppStage : [Select MasterLabel, DefaultProbability
                                    From OpportunityStage]) {
 probabilityStageNameMap.put(oppStage.MasterLabel, oppStage.DefaultProbability);
   }
  }

 if (probabilityStageNameMap.containsKey(Oppty.StageName)) {
   Oppty.Probability = probabilityStageNameMap.get(Oppty.StageName);
 
 }

  return null;
 }
 
  public PageReference doSave()
  {
  
      if (Oppty.LeadSource == 'Marketing Campaign' && Oppty.CampaignId == null )
      {
        system.debug('I m in'); 
        oppty.addError('Please select the Marketing Campaign which influenced this opportunity.');
          //ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Error !!!'));    
      }
      
      if(oppty.Program_Length_in_months__c == 0){
          oppty.addError('The Contract Length Cant be "0".');
      }
      
      if(oppty.StageName != 'Awarded Business' &&  oppty.Probability > 99){
          oppty.addError('Probability of pipeline Opportunity cannot be 100%');
      }
      
      if(oppty.IsClosed != True  &&  oppty.Probability == 0){
          oppty.addError('The Probability of an Active opportunity cant be 0%');
      }
      
      
     upsert oppty;
     pagereference page=new pagereference('/apex/TPDynamicOppNEWLayout?id=' + oppty.id);
      return null;
  }
  
     public PageReference Save()
  {
  
      if (Oppty.LeadSource == 'Marketing Campaign' && Oppty.CampaignId == null )
      {
        system.debug('I m in'); 
        oppty.addError('Please select the Marketing Campaign which influenced this opportunity.');
          //ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Error !!!'));    
      }
      
      if(oppty.Program_Length_in_months__c == 0){
          oppty.addError('The Contract Length Cant be "0".');
      }
      
      if(oppty.StageName != 'Awarded Business' &&  oppty.Probability > 99){
          oppty.addError('Probability of pipeline Opportunity cannot be 100%');
      }
      
      if(oppty.IsClosed != True  &&  oppty.Probability == 0){
          oppty.addError('The Probability of an Active opportunity cant be 0%');
      }
      
      
     upsert oppty;
     pagereference page2 =new pagereference('/' + oppty.id);
      return page2 ;
  }
  
}

 

Dear all, I`m new to Apex programming and I need help with test class. Below is my apex class and i`m not getting any test coverage on this class.  Can someone please help me with test code to get me started? Thanks in advance.

 

public with sharing class Example {

    String oppId;
    String ownerId;
    private final Opportunity Oppty;
 
    public Example (ApexPages.StandardController stdController) {
        oppId = stdController.getId();
        Oppty = (Opportunity) stdController.getRecord();
        ownerId = oppty.OwnerId;
        oppty.StageName = 'Identified Opportunity';
         oppty.Probability = 0;
    }



public transient Map<String, Decimal> probabilityStageNameMap;

public PageReference changeStageName() {

if (probabilityStageNameMap == null) {
 probabilityStageNameMap = new Map<String, Decimal>();
for (OpportunityStage oppStage : [Select MasterLabel, DefaultProbability
                                    From OpportunityStage]) {
 probabilityStageNameMap.put(oppStage.MasterLabel, oppStage.DefaultProbability);
   }
  }

 if (probabilityStageNameMap.containsKey(Oppty.StageName)) {
   Oppty.Probability = probabilityStageNameMap.get(Oppty.StageName);
 
 }

  return null;
 }
 
           public PageReference dosave()
  {
    insert oppty;
    return new PageReference('/' + 'apex/OppNEWLayout?id= + oppty.id'); 
    }


}
 


 

Dear all:
I`m working on dynamic VF page which will show fields based on stages selected. Page works fine but the issue is with Probability field. While selecting Stage, Probability field does not show up value % associated at each level (like it generates for standard SF Opportunity page). Can one of you SF gurus please help in fixing this? Thanks!



 

<apex:page standardController="Opportunity" sidebar="false">


    <apex:sectionHeader title="Edit Opportunity" subtitle="{!opportunity.name}"/>
    <apex:form >
        <apex:pageBlock title="Edit Opportunity" id="thePageBlock" mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>                
            </apex:pageBlockButtons>
            <apex:actionRegion >
                <apex:pageBlockSection title="Basic Information" columns="1">
                    <apex:inputField value="{!opportunity.name}"/>
                    <apex:pageBlockSectionItem >
                        <apex:outputLabel value="Stage"/>
                        <apex:outputPanel >
                            <apex:inputField value="{!opportunity.stageName}">
                                <apex:actionSupport event="onchange" rerender="thePageBlock"
                                                    status="status"/>
                            </apex:inputField>
                            <apex:actionStatus startText="applying value..." id="status"/>
                        </apex:outputPanel>
                    </apex:pageBlockSectionItem>
                    <apex:inputField value="{!opportunity.amount}"/>
                    <apex:inputField value="{!opportunity.closedate}"/>
                    <apex:inputField value="{!opportunity.Probability}"/>

                </apex:pageBlockSection>
            </apex:actionRegion>
            <apex:pageBlockSection title="Closed Lost Information" columns="1"
                                   rendered="{!opportunity.stageName == 'Closed Lost'}">
                <apex:inputField value="{!opportunity.Primary_Competitor__c}"  required="true"/>
                <apex:inputField value="{!opportunity.Reason_Lost__c}"/>
                <apex:inputField value="{!opportunity.OrderNumber__c}"/>
                <apex:inputField value="{!opportunity.TrackingNumber__c}"/>
                
            </apex:pageBlockSection>
            
            

        </apex:pageBlock>

    </apex:form>
    
</apex:page>

 
Dear all, I`m trying to create a code which will prevent duplication in my org. THis code will run if lead is being created/updated and contact is already exisiting. If contact is already exisitng, lead will give an error. what I want to do is, if creator of this lead (user) is "Internal Login", trigger should not be applied and lead should be allowed to create. When I add "If" argument**, it is not working. It is either allowing everyone to create or no one to create dupe. I need a condition where only "Internal User" should be allowed to create dupes.. Can someone please help?

 
trigger AvoidDupe on Lead (before insert, before update) {

  for (Lead myLead : Trigger.new) {
              String Fullname;

                *//adding "if " argument below is not helping. it is either allowing everyone to create or no one to create dupe. I need a condition where only "Internal User" should be allowed to create dupes.

                 if (myLead.CreatedById == '00580000003a935') {
 
if (myLead.Email != null) {
List<Contact> dupes = [SELECT Id, FirstName, LastName,Name FROM Contact WHERE Email = :myLead.Email];
if (dupes.size() > 0) { 
FullName = dupes[0].Name;
mylead.addError('ERROR: There is already an identical record with same email. <a href=\'https://cs1.salesforce.com/' + dupes[0].Id + '\'> Contact - '+ FullName  +  '</a>', false);

} }
  }
}
}

 
Dear all, what I want to do is extract all "Filter" information about reports in Excel. I have already tried doing this via Data loader however I`m not getting information that I need. I want to extract all information about "Filters" that are applied in each of reports in my org. I see information about filters in eclipse .report metadata but I`m not able to extract it in excel. For example, I want to see how may reports are being run with specific stage in my org. (Not the data, just filters)

Any suggestion how I can get information about report Filters in excel ?? Any suggestions are appricated.
Dear all, what I want to do is extract all "Filter" information about reports in Excel. I have already tried doing this via Data loader however I`m not getting information that I need. I want to extract all information about "Filters" that are applied in each of reports in my org. I see information about filters in eclipse .report metadata but I`m not able to extract it in excel. For example, I want to see how may reports are being run with specific stage in my org. (Not the data, just filters)

Any suggestion how I can get information about report Filters in excel ?? Any suggestions are appricated.

 
Dear all, this may be really simple but I`m not able to figure it out. I have two Number fields "Agents__c" and "stations__c". I want formula field (# of TRE) which will help me to evaluate that if Agent__C is Blank, it will multiply the amount stations__c * 0.55. Similarly, if stations__c is Blank, it will multiply amount Agent__C * 0.55. If both are blank, it should be zero. Can someone please help me with appropriate formula?

I tried below formulas but it does not work. Formula works well on Agent__c but if Agent__c is Blank, and stations__c has value, it does not work

BLANKVALUE(BLANKVALUE(Agent__c, Section__c), 0) * 0.55


IF( NOT(ISBLANK(Agent__c)), Agent__c, IF( NOT(ISBLANK(Station__c)), Station__c, 0 ) ) * 0.55

 
Dear all, below is my code which automatically send email notificaitons when a new Event is created. If opportunity is not tagged to Event, I`m getting a System.NullpointerException. Could you please help in understanding what I`m doing wrong? I`m new to Apex 

Apex trigger NotifyOnSiteVist2 caused an unexpected exception, contact your administrator: Visitnotify: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Visitnotify: line 29, column 1

 
Trigger Visitnotify on Event (after insert){
        
    List<Messaging.SingleEmailMessage> newEmails = new List<Messaging.SingleEmailMessage>();
    List<Id> whatIds = new List<Id>();
    List<Id> createdByIds = new List<Id>();
    for(Event e :Trigger.new)
    {
        createdByIds.add(E.CreatedByID);
        whatIds.add(E.whatId);
    }
    Map<Id, User> users = new Map<Id, User>([SELECT Id, Name from User WHERE Id in :createdByIds]);
    Map<Id, Opportunity> opportunities = new Map<Id, Opportunity>([SELECT Name, Account.Name from Opportunity WHERE Id in :whatIds]);
    for(Event e :Trigger.new){
    
    if(e.whatid != NULL){ 
            String fullTaskURL;
            String Facility;
            Datetime startDate;
            Datetime endDate;
            String Purpose;

            
            // Query to populate CreatedBy name in html template
            Id createdByID = E.CreatedByID;
            String createdByName = users.get(createdByID).Name;
                   
            // Query to populate Opportunity name in html template
            String oppID = E.whatId;  
            String oppName = opportunities.get(oppID).Name;
                                 
        if(E.Site_Visit__C ){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                
            mail.setSubject(' Alert: A New Visit Record is Created');
            mail.setSaveAsActivity(false);
            mail.setTargetObjectId('00580000005LedR'); 
                                     
            fullTaskURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + E.Id;
            Facility = E.Facility__c;
            startDate = E.StartDateTime;
            endDate = E.EndDateTime;
            Purpose = E.Purpose_of_Visit__c;
                
   
            //Generate email template
                String emailBody;
                emailBody = '<html><body>Hi ,<br> <br> A New Site Visit Record has been created: <a href="' + fullTaskURL + '">' + E.Id + '</a><br></body></html>' + '<br> Sales VP: '+ createdByName + '<br> Opportunity/Account Name: '+ oppName + '<br> <br> Site/Facility: ' + Facility+ '<br> Purpose of Visit: ' + Purpose +  '<br> Start Date/Time: ' + StartDate +  '<br> End Date/Time: ' +endDate +  '<br> <br> Thank you <br> <br> Salesforce Admin' ;
                mail.setHtmlBody(emailBody );

            newEmails.add(mail);
        }
    }

    messaging.sendEmail(newEmails);
} }

 
Dear all, below is my code which auto follows accounts when a new custom object KTT is created or updated. Code works fine on single record but I`m having trouble in bulkfying this code. I get "System.LimitException: Too many DML rows: 10001" error when I try to insert records in bulk via data loader. Is there something wrong with my code? I`m new to Apex world so it would really help if someone can point me to right direction.

Also, if I try to remove last few lines of DML statement, I get "System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>: []" error.
 
trigger RTTAutoFollow2 on RTT__C (after insert,after update) {


            List <EntitySubscription > NewFollowers = new List <EntitySubscription > ();   

                            List<Id> whatIds = new List<Id>();
               
   for(RTT__C sampletracker : trigger.new)

                         {
                whatIds.add(sampletracker.Account__c);
                             }
    
Map<Id, Account> Accounts = new Map<Id, Account>([SELECT Id, Name from Account WHERE Id in :whatIds]);
             

for(RTT__C sampletracker : trigger.new){  

              
                  if(sampletracker.Account__c != NULL){ 

 
           String Accid = sampletracker.Account__c;           
            String AccIds = accounts.get(Accid).ID;                  

    if (sampletracker.No_longer_Key__c == False)
{
  
               EntitySubscription ES = new EntitySubscription();    
               ES.SubscriberId = sampletracker.Assigned_Sales_Team__c;  
               ES.ParentId = sampletracker.Account__c;  
    
           }  
  
           try{  
                insert NewFollowers;                 
           }  
           catch (System.DmlException e){  
           }  
}
}}

 
Hello, I`m new to Apex programming and I need help with test class. Below is my trigger and i`m not getting more than 54% test coverage on this trigger.  Can someone please help me with test code? Thanks in advance.
 
Trigger VisitNotification on Event (after insert){
		
    List<Messaging.SingleEmailMessage> newEmails = new List<Messaging.SingleEmailMessage>();
	List<Id> whatIds = new List<Id>();
	List<Id> createdByIds = new List<Id>();
	for(Event e :Trigger.new)
	{
		createdByIds.add(E.CreatedByID);
		whatIds.add(E.whatId);
	}
	Map<Id, User> users = new Map<Id, User>([SELECT Id, Name from User WHERE Id in :createdByIds]);
	Map<Id, Opportunity> opportunities = new Map<Id, Opportunity>([SELECT Name, Account.Name from Opportunity WHERE Id in :whatIds]);
    for(Event e :Trigger.new){
            String fullTaskURL;
            String Facility;
            Datetime startDate;
            Datetime endDate;
            String Purpose;
            String Salesexec;

            // Query to populate CreatedBy name in html template
            Id createdByID = E.CreatedByID;
            String createdByName = users.get(createdByID).Name;
            
            // Query to populate Opportunity name in html template
            String oppID = E.whatId;  
            String oppName = opportunities.get(oppID).Name;
    
        if(E.Visit__C){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                
            mail.setSubject('Automated Alert: A New Record is Created');
            mail.setSaveAsActivity(false);
            mail.setTargetObjectId('00580000005HreR') ;        

            fullTaskURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + E.Id;
            Facility = E.Facility__c;
            startDate = E.StartDateTime;
            endDate = E.EndDateTime;
            Purpose = E.Purpose__c;
            Salesexec = E.Salesexec__c;
   
   
            //Generate email template
                String emailBody;
                emailBody = '<html><body>Hi<br> <br> A New Record has been created: <a href="' + fullTaskURL + '">' + E.Id + '</a><br></body></html>' + '<br> <br> Site/Facility: ' + Facility+ '<br> Start Date/Time: ' + StartDate + '<br> End Date/Time: ' +endDate + '<br> Purpose: ' + Purpose + '<br> Sales VP: '+ Salesexec +  '<br> <br> Thank you <br> <br> Salesforce Admin' ; 
                mail.setHtmlBody(emailBody );

            newEmails.add(mail);
        }
    }

    messaging.sendEmail(newEmails);
}

 
Hello. I need help with adding my SOQL queires outside the 'For' Loops. I`m new to Apex coding and I was reading the article about governor limits. I tried adding by queries outside 'for' loop but they are not working. Can someone please give me an example on how to do this by using List or maps?? Also, is the code below correct or will it hit governor limit?
 
Trigger VisitNotification on Event (after insert){
		
    List<Messaging.SingleEmailMessage> newEmails = new List<Messaging.SingleEmailMessage>();
    for(Event e :Trigger.new){
            String fullTaskURL;
            String Facility;
            Datetime startDate;
            Datetime endDate;
            String Purpose;
            String Salesexec;

            // Query to populate CreatedBy name in html template
            String createdByID = E.CreatedByID;
            String createdByName = [SELECT Name from User WHERE id=: createdByID limit 1].Name;
            
            // Query to populate Opportunity name in html template
            String oppID = E.whatId;  
            String oppName = [SELECT Name, Account.Name from Opportunity WHERE id=: oppID limit 1].Name;
    
        if(E.Visit__C){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                
            mail.setSubject('Automated Alert: A New Record is Created');
            mail.setSaveAsActivity(false);
            mail.setTargetObjectId('00580000005HreR') ;        

            fullTaskURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + E.Id;
            Facility = E.Facility__c;
            startDate = E.StartDateTime;
            endDate = E.EndDateTime;
            Purpose = E.Purpose__c;
            Salesexec = E. Salesexec__c;
   
   
            //Generate email template
                String emailBody;
                emailBody = '<html><body>Hi<br> <br> A New Record has been created: <a href="' + fullTaskURL + '">' + E.Id + '</a><br></body></html>' + '<br> <br> Site/Facility: ' + Facility+ '<br> Start Date/Time: ' + StartDate + '<br> End Date/Time: ' +endDate + '<br> Purpose: ' + Purpose + '<br> Sales VP: '+ Salesexec +  '<br> <br> Thank you <br> <br> Salesforce Admin' ; 
                mail.setHtmlBody(emailBody );

            newEmails.add(mail);
        }
    }

    messaging.sendEmail(newEmails);
}

 
Dear all, below is my trigger to send email from Salesforce. This trigger fires when Visit__c field is checked as True. Trigger works fine, but issue is that I`m not able to populate Created By Name, Assigned To name, Opportunity/Account Name (RelatedTo) etc in my html email body. How can I populate these fields in my email body? If I String E.Whatid or Whoid, it gives me ID in template instead of name.

Also, is there a way I can populate Contact name, phone number etc. tagged to this event? I`m new to Apex so any help will be much appreciated! :)
Trigger VisitNotification on Event (after insert){
	
    List<Messaging.SingleEmailMessage> newEmails = new List<Messaging.SingleEmailMessage>();
    for(Event e :Trigger.new){
            String fullTaskURL;
            String Facility;
            Datetime startDate;
            Datetime endDate;
            String Purpose;
            String Salesexec;
    
        if(E.Visit__C){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                
            mail.setSubject('Automated Alert: A New Record is Created');
            mail.setSaveAsActivity(false);
            mail.setTargetObjectId('00580000005HreR') ;        

            fullTaskURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + E.Id;
            Facility = E.Facility__c;
            startDate = E.StartDateTime;
            endDate = E.EndDateTime;
            Purpose = E.Purpose__c;
            Salesexec = E. Salesexec__c;
   
   
            //Generate email template
                String emailBody;
                emailBody = '<html><body>Hi<br> <br> A New Record has been created: <a href="' + fullTaskURL + '">' + E.Id + '</a><br></body></html>' + '<br> <br> Site/Facility: ' + Facility+ '<br> Start Date/Time: ' + StartDate + '<br> End Date/Time: ' +endDate + '<br> Purpose: ' + Purpose + '<br> Sales VP: '+ Salesexec +  '<br> <br> Thank you <br> <br> Salesforce Admin' ; 
                mail.setHtmlBody(emailBody );

            newEmails.add(mail);
        }
    }

    messaging.sendEmail(newEmails);
}

 
All, I was wondering if someone can help me. Below is my trigger which is very simple. It will take Feed item from Account page and will repost it to Chatter group. Trigger works fine for Post and Link, but when I`m trying to attach exisitng File from content library and share it, it generates below error.

Field_Integrity_Exception, ContentFileName is required field for feed post of type ContentPost. Content File Name: [ContentFileName]

Can someone pls suggest a workaround?
trigger autoPostFromAccToGroup on FeedItem (before insert) {

List <FeedItem> Feedlist = New List <FeedItem> ();

 Map <id,Account> AccMaps = New Map <id, Account> () ;
Set <Id> idsets = New Set <Id> ();

      For (Feeditem fe : Trigger.New) {
          String idStr = fe.Parentid;
           if(idStr.startsWith('001')){
                     idsets.add(idStr);    
           
      
      }
    }
    
       List <Account> accs = [SELECT ID, Owner.Name, RecordTypeid, Name FROM Account WHERE id IN :idsets ];
       
           for (Account  acc : accs) {
                   
            AccMaps.put(acc.id,acc);      

    
        
        
                   for (Feeditem f : Trigger.New) {
                   
                   if (AccMaps.get(f.parentid).Recordtypeid == '012300000000uth') {  
                   
            FeedItem FI = New FeedItem ();
            FI.ParentId = '0F91b0000008ThRCAU' ; 
            FI.TYPE = F.TYPE; 
            Fi.IsRichText = True;
            FI.Body = F.Body;
            Fi.LINKURL = F.LINKURL;
            Fi.TITLE = F.TITLE;
            Fi.ContentFileName = F.ContentFileName;
            Fi.ContentData = F.ContentData ;
            Fi.ContentDescription= F.ContentDescription;
           Fi.CreatedByid = UserInfo.getUserId() ;


            Feedlist.add(FI);

        
        }
        }
        }
         insert Feedlist;  
        
}

 
Dear All, I`m new to Apex and I`m stuck with this issue. I have a standardcontroller and below extension. What I want to do is override the standard Save button with save() method so that it redirects me to the Opportunity view page. Save works fine but it doesnt throw any error. It directly save the page. Can someone pls help? 
Thanks!
 
public with sharing class myclass {

    String oppId;
    String ownerId;
    private Opportunity Oppty;
 
    public myclass(ApexPages.StandardController stdController) {
        oppId = stdController.getId();
        Oppty = (Opportunity) stdController.getRecord();
        ownerId = oppty.OwnerId;
        oppty.StageName = 'Identified Opportunity';
         oppty.Probability = 0;
    }



public transient Map<String, Decimal> probabilityStageNameMap;

public PageReference changeStageName() {

if (probabilityStageNameMap == null) {
 probabilityStageNameMap = new Map<String, Decimal>();
for (OpportunityStage oppStage : [Select MasterLabel, DefaultProbability
                                    From OpportunityStage]) {
 probabilityStageNameMap.put(oppStage.MasterLabel, oppStage.DefaultProbability);
   }
  }

 if (probabilityStageNameMap.containsKey(Oppty.StageName)) {
   Oppty.Probability = probabilityStageNameMap.get(Oppty.StageName);
 
 }

  return null;
 }
 
  public PageReference doSave()
  {
  
      if (Oppty.LeadSource == 'Marketing Campaign' && Oppty.CampaignId == null )
      {
        system.debug('I m in'); 
        oppty.addError('Please select the Marketing Campaign which influenced this opportunity.');
          //ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Error !!!'));    
      }
      
      if(oppty.Program_Length_in_months__c == 0){
          oppty.addError('The Contract Length Cant be "0".');
      }
      
      if(oppty.StageName != 'Awarded Business' &&  oppty.Probability > 99){
          oppty.addError('Probability of pipeline Opportunity cannot be 100%');
      }
      
      if(oppty.IsClosed != True  &&  oppty.Probability == 0){
          oppty.addError('The Probability of an Active opportunity cant be 0%');
      }
      
      
     upsert oppty;
     pagereference page=new pagereference('/apex/TPDynamicOppNEWLayout?id=' + oppty.id);
      return null;
  }
  
     public PageReference Save()
  {
  
      if (Oppty.LeadSource == 'Marketing Campaign' && Oppty.CampaignId == null )
      {
        system.debug('I m in'); 
        oppty.addError('Please select the Marketing Campaign which influenced this opportunity.');
          //ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Error !!!'));    
      }
      
      if(oppty.Program_Length_in_months__c == 0){
          oppty.addError('The Contract Length Cant be "0".');
      }
      
      if(oppty.StageName != 'Awarded Business' &&  oppty.Probability > 99){
          oppty.addError('Probability of pipeline Opportunity cannot be 100%');
      }
      
      if(oppty.IsClosed != True  &&  oppty.Probability == 0){
          oppty.addError('The Probability of an Active opportunity cant be 0%');
      }
      
      
     upsert oppty;
     pagereference page2 =new pagereference('/' + oppty.id);
      return page2 ;
  }
  
}

 
Dear all, I`m new to apex and I need help with issue below. I have a "New Case" custom button on Opportunity record which allows me to create Case. When clicked on "New Case" button, I can select record type and page gets redirected to standard page or visualforce page using redirect class below. Code works fine but I`m unable to auto-populate fields when record type with standard page is selected. Fields are not getting auto populated the way it happens with standard functionality. For example, I`m not able to auto-populate Opportunity Name, Stage or Close Date while creating new case record. Can someone please help? Any help is much appreciated. Thank you!

Redirect VF page
<apex:page standardController="Case" extensions="Redirect" action="{!Redirect}">

</apex:page>

Redirect class
 
public with sharing class Redirect{

    private Id id;


 private ApexPages.StandardController controller;
 public String retURL {get; set;}
 public String saveNewURL {get; set;}
 public String rType {get; set;}
 public String cancelURL {get; set;}
 public String ent {get; set;}
 public String confirmationToken {get; set;}


 public Redirect(ApexPages.StandardController controller) {

  this.controller = controller;
  retURL = ApexPages.currentPage().getParameters().get('retURL');
  rType = ApexPages.currentPage().getParameters().get('RecordType');
  cancelURL = ApexPages.currentPage().getParameters().get('cancelURL');
  ent = ApexPages.currentPage().getParameters().get('ent');
  confirmationToken = ApexPages.currentPage().getParameters().get('_CONFIRMATIONTOKEN');
  saveNewURL = ApexPages.currentPage().getParameters().get('save_new_url');
 }

 
 public PageReference redirect(){
  
  PageReference returnURL;
  // Redirect if Record Type corresponds to custom VisualForce page
  if(rType == '0121b0000009t60') {
   returnURL = new PageReference('/apex/vfcasepage');
  }
  else {
   returnURL = new PageReference('/500/e?nooverride=1');
  }

  returnURL.getParameters().put('retURL', retURL);
  returnURL.getParameters().put('RecordType', rType);
  returnURL.getParameters().put('cancelURL', cancelURL);
  returnURL.getParameters().put('ent', ent);
  returnURL.getParameters().put('_CONFIRMATIONTOKEN', confirmationToken);
  returnURL.getParameters().put('save_new_url', saveNewURL);
    returnURL.getParameters().put('nooverride', '1');
  returnURL.setRedirect(true);
  return returnURL;

 }

 public PageReference cancel() {
          PageReference pr = new PageReference('/500/o');
          pr.setRedirect(true);
          return pr;
     }


}


 
All, I was wondering if someone can help me. Below is my trigger which is very simple. It will take Feed item from Account page and will repost it to Chatter group. Trigger works fine for Post and Link, but when I`m trying to attach exisitng File from content library and share it, it generates below error.

Field_Integrity_Exception, ContentFileName is required field for feed post of type ContentPost. Content File Name: [ContentFileName]

Can someone pls suggest a workaround?
trigger autoPostFromAccToGroup on FeedItem (before insert) {

List <FeedItem> Feedlist = New List <FeedItem> ();

 Map <id,Account> AccMaps = New Map <id, Account> () ;
Set <Id> idsets = New Set <Id> ();

      For (Feeditem fe : Trigger.New) {
          String idStr = fe.Parentid;
           if(idStr.startsWith('001')){
                     idsets.add(idStr);    
           
      
      }
    }
    
       List <Account> accs = [SELECT ID, Owner.Name, RecordTypeid, Name FROM Account WHERE id IN :idsets ];
       
           for (Account  acc : accs) {
                   
            AccMaps.put(acc.id,acc);      

    
        
        
                   for (Feeditem f : Trigger.New) {
                   
                   if (AccMaps.get(f.parentid).Recordtypeid == '012300000000uth') {  
                   
            FeedItem FI = New FeedItem ();
            FI.ParentId = '0F91b0000008ThRCAU' ; 
            FI.TYPE = F.TYPE; 
            Fi.IsRichText = True;
            FI.Body = F.Body;
            Fi.LINKURL = F.LINKURL;
            Fi.TITLE = F.TITLE;
            Fi.ContentFileName = F.ContentFileName;
            Fi.ContentData = F.ContentData ;
            Fi.ContentDescription= F.ContentDescription;
           Fi.CreatedByid = UserInfo.getUserId() ;


            Feedlist.add(FI);

        
        }
        }
        }
         insert Feedlist;  
        
}

 
All, need help with a trigger. This trigger copies record from Contacts standard object to Strategic Contacts custom object. I want this code to copy all Contacts in account and create Strategic Contacts. For example, if account has 4 contacts, then 4 strategic contacts should be created. Code is currently inserting only 1 record. Can someone pls help?
 
trigger StrategicContactAutoCr on Account (after update) {

      List<Dev_che_123__Strategic_Contacts__c> STToInsert = new List<Dev_che_123__Strategic_Contacts__c>();
    
    Map <Id,Contact> ContactMaps = New Map <Id,Contact> ();
    Set <Id> accids = New Set <ID> ();
    for (Account acc: Trigger.New ) {
        if (acc.Strategic_Account__c != null ) {
            accids.add(acc.id);
				    system.debug('total strt accs' + accids);
            
        }
        
    }  
    
    List <Contact> Con = [SELECT AccountID, FirstName, LastName FROM Contact WHERE AccountID IN :accids ];
    system.debug('total Con List' + Con);

    For (Contact C : Con ) {
        If (C.AccountID != null) {
            ContactMaps.put(C.AccountID, c);
                system.debug('total Con List after Put Id and Contact in Map' + Con);
               
                
            }
            
        }
    
          
    
    for (Account acct: Trigger.New ) {
        if (acct.Strategic_Account__c != False ) {
            
            
                Dev_che_123__Strategic_Contacts__c SC = new Dev_che_123__Strategic_Contacts__c ();
  				SC.Dev_che_123__Account__c = acct.id;
				SC.Dev_che_123__First_Name__c = ContactMaps.get(acct.Id).FirstName;
				SC.Dev_che_123__Last_Name__c = ContactMaps.get(acct.Id).LastName;
				STToInsert.add(sc);
            
        }
        		
    }
    
        insert STToInsert;

       
    }

 
Dear All,
Here is my trigger. I want to update "Deactivated on" text field everytime Opportunty "Active" field changes to False. Trigger works fine but the issue is that it runs everytime Inactive user record is updated. I only want this trigger to run when user changes from True to False. Can someone please help?
 
trigger DeactivateDate on User (before update) {

String deastat = 'User license is deactivated on ';


User us = [select Name from user where id=:userinfo.getuserid()];
string username = us.Name;


            for (User u : Trigger.new) {
            
                DateTime dt = u.LastModifieddate;
                String formattedDt = dt.format('MM-dd-yyyy @ hh:mm:ss');

            if (u.IsActive == False){
            u.Deactivated_On__c = deastat + formattedDt   + ' by ' +  username;

            }
            
            } 
            

}

 
Dear all, I need help with pop up window. Requirement is that everytime Opportunity Close Date is changed on edit page, pop should appear with a notificaton and then allow users to save the record. I`m new to VF and Apex. Can someone please help me with VF code or Jscript that works?

Any help is appreciated. Thanks!
Dear all,
Below is my visualforce page. City is a dependent field which works with Country. Everytime I change the stage and save the page, city field gets reset when I advance to next stage. For some reason, City field is not retaining values on next stage. For example, if I select country as USA in "Prospecting" stage and save the page with "New York" as city. In next stage which is "Needs Analysis", City field automatically resets to blank. Can someone please help with a controller or a visualforce workaround?


 
<apex:page standardController="Opportunity" sidebar="false">
  <apex:sectionHeader title="Edit Opportunity" 
                      subtitle="{!opportunity.name}"/>
  <apex:form >
    <apex:pageBlock title="Edit Opportunity" id="thePageBlock" 
                    mode="edit">
      <apex:pageMessages />
      <apex:pageBlockButtons >
        <apex:commandButton value="Save" action="{!save}"/>
        <apex:commandButton value="Cancel" action="{!cancel}"/>
      </apex:pageBlockButtons>
      <apex:actionRegion >
        <apex:pageBlockSection title="Basic Information" 
                               columns="1">
          <apex:inputField value="{!opportunity.name}"/>
          <apex:pageBlockSectionItem >
            <apex:outputLabel value="Stage"/>
            <apex:outputPanel >
              <apex:inputField value="{!opportunity.stageName}">
                <apex:actionSupport event="onchange" 
                                    rerender="thePageBlock"
                                    status="status"/>
              </apex:inputField>
              <apex:actionStatus startText="applying value..." 
                                 id="status"/>
            </apex:outputPanel>
          </apex:pageBlockSectionItem>
          <apex:inputField value="{!opportunity.amount}"/>
          <apex:inputField value="{!opportunity.closedate}"/>
        </apex:pageBlockSection>
      </apex:actionRegion>
      
      <apex:pageBlockSection title="Closed Lost Information" 
            columns="1" 
            rendered="{!opportunity.stageName == 'Prospecting'}">
        <apex:inputField value="{!opportunity.Country__c}"  
              required="true"/>
        <apex:inputField value="{!opportunity.City__c}"/>
      </apex:pageBlockSection>
      
      <apex:pageBlockSection title="Closed Lost Information" 
            columns="1" 
            rendered="{!opportunity.stageName == 'Needs Analysis'}">
        <apex:inputField value="{!opportunity.Country__c}"  
              required="true"/>
        <apex:inputField value="{!opportunity.City__c}"/>
      </apex:pageBlockSection>
      
    </apex:pageBlock>
  </apex:form>
</apex:page>

 
Dear all, I`m new to apex and I would like to understand how can I add multiple validation rules to this extension. Our org has multiple validation rules and we would like to populate that on VF page. Can someone pls give me an example of how I can use multiple Try/Catch statements in dosave() method below. Whatever I`m trying is failing. Please help!!!

Thanks!
 
public with sharing class ExampleTP {

    String oppId;
    String ownerId;
    private final Opportunity Oppty;
 
    public ExampleTP (ApexPages.StandardController stdController) {
        oppId = stdController.getId();
        Oppty = (Opportunity) stdController.getRecord();
        ownerId = oppty.OwnerId;
        if(oppty.StageName == null)
          oppty.StageName = 'Identified Opportunity';
        if(oppty.Probability == null)
            oppty.Probability = 0;
    }



public transient Map<String, Decimal> probabilityStageNameMap;

public PageReference changeStageName() {

if (probabilityStageNameMap == null) {
 probabilityStageNameMap = new Map<String, Decimal>();
for (OpportunityStage oppStage : [Select MasterLabel, DefaultProbability
                                    From OpportunityStage]) {
 probabilityStageNameMap.put(oppStage.MasterLabel, oppStage.DefaultProbability);
   }
  }

 if (probabilityStageNameMap.containsKey(Oppty.StageName)) {
   Oppty.Probability = probabilityStageNameMap.get(Oppty.StageName);
 
 }

  return null;
 }
 
  public PageReference doSave()
  {
  Try
   {
      if (Oppty.LeadSource == 'Marketing Campaign' && Oppty.CampaignId == null )
  
  {
    upsert oppty;
     return new PageReference('/' + 'apex/TPDynamicOppNEWLayout?oppId= + Oppty.Id'); 
        }
        }
catch(Exception e)
        {
            Apexpages.addMessage(new Apexpages.message(ApexPages.Severity.Error,'Campaign is required'));
            }
            return null;
  }
        


}

 
Dear All, I`m new to Apex and I`m stuck with this issue. I have a standardcontroller and below extension. What I want to do is override the standard Save button with save() method so that it redirects me to the Opportunity view page. Save works fine but it doesnt throw any error. It directly save the page. Can someone pls help? 
Thanks!
 
public with sharing class myclass {

    String oppId;
    String ownerId;
    private Opportunity Oppty;
 
    public myclass(ApexPages.StandardController stdController) {
        oppId = stdController.getId();
        Oppty = (Opportunity) stdController.getRecord();
        ownerId = oppty.OwnerId;
        oppty.StageName = 'Identified Opportunity';
         oppty.Probability = 0;
    }



public transient Map<String, Decimal> probabilityStageNameMap;

public PageReference changeStageName() {

if (probabilityStageNameMap == null) {
 probabilityStageNameMap = new Map<String, Decimal>();
for (OpportunityStage oppStage : [Select MasterLabel, DefaultProbability
                                    From OpportunityStage]) {
 probabilityStageNameMap.put(oppStage.MasterLabel, oppStage.DefaultProbability);
   }
  }

 if (probabilityStageNameMap.containsKey(Oppty.StageName)) {
   Oppty.Probability = probabilityStageNameMap.get(Oppty.StageName);
 
 }

  return null;
 }
 
  public PageReference doSave()
  {
  
      if (Oppty.LeadSource == 'Marketing Campaign' && Oppty.CampaignId == null )
      {
        system.debug('I m in'); 
        oppty.addError('Please select the Marketing Campaign which influenced this opportunity.');
          //ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Error !!!'));    
      }
      
      if(oppty.Program_Length_in_months__c == 0){
          oppty.addError('The Contract Length Cant be "0".');
      }
      
      if(oppty.StageName != 'Awarded Business' &&  oppty.Probability > 99){
          oppty.addError('Probability of pipeline Opportunity cannot be 100%');
      }
      
      if(oppty.IsClosed != True  &&  oppty.Probability == 0){
          oppty.addError('The Probability of an Active opportunity cant be 0%');
      }
      
      
     upsert oppty;
     pagereference page=new pagereference('/apex/TPDynamicOppNEWLayout?id=' + oppty.id);
      return null;
  }
  
     public PageReference Save()
  {
  
      if (Oppty.LeadSource == 'Marketing Campaign' && Oppty.CampaignId == null )
      {
        system.debug('I m in'); 
        oppty.addError('Please select the Marketing Campaign which influenced this opportunity.');
          //ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Error !!!'));    
      }
      
      if(oppty.Program_Length_in_months__c == 0){
          oppty.addError('The Contract Length Cant be "0".');
      }
      
      if(oppty.StageName != 'Awarded Business' &&  oppty.Probability > 99){
          oppty.addError('Probability of pipeline Opportunity cannot be 100%');
      }
      
      if(oppty.IsClosed != True  &&  oppty.Probability == 0){
          oppty.addError('The Probability of an Active opportunity cant be 0%');
      }
      
      
     upsert oppty;
     pagereference page2 =new pagereference('/' + oppty.id);
      return page2 ;
  }
  
}

 

Dear all, I`m new to Apex programming and I need help with test class. Below is my apex class and i`m not getting any test coverage on this class.  Can someone please help me with test code to get me started? Thanks in advance.

 

public with sharing class Example {

    String oppId;
    String ownerId;
    private final Opportunity Oppty;
 
    public Example (ApexPages.StandardController stdController) {
        oppId = stdController.getId();
        Oppty = (Opportunity) stdController.getRecord();
        ownerId = oppty.OwnerId;
        oppty.StageName = 'Identified Opportunity';
         oppty.Probability = 0;
    }



public transient Map<String, Decimal> probabilityStageNameMap;

public PageReference changeStageName() {

if (probabilityStageNameMap == null) {
 probabilityStageNameMap = new Map<String, Decimal>();
for (OpportunityStage oppStage : [Select MasterLabel, DefaultProbability
                                    From OpportunityStage]) {
 probabilityStageNameMap.put(oppStage.MasterLabel, oppStage.DefaultProbability);
   }
  }

 if (probabilityStageNameMap.containsKey(Oppty.StageName)) {
   Oppty.Probability = probabilityStageNameMap.get(Oppty.StageName);
 
 }

  return null;
 }
 
           public PageReference dosave()
  {
    insert oppty;
    return new PageReference('/' + 'apex/OppNEWLayout?id= + oppty.id'); 
    }


}
 


 

Dear all:
I`m working on dynamic VF page which will show fields based on stages selected. Page works fine but the issue is with Probability field. While selecting Stage, Probability field does not show up value % associated at each level (like it generates for standard SF Opportunity page). Can one of you SF gurus please help in fixing this? Thanks!



 

<apex:page standardController="Opportunity" sidebar="false">


    <apex:sectionHeader title="Edit Opportunity" subtitle="{!opportunity.name}"/>
    <apex:form >
        <apex:pageBlock title="Edit Opportunity" id="thePageBlock" mode="edit">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Cancel" action="{!cancel}"/>                
            </apex:pageBlockButtons>
            <apex:actionRegion >
                <apex:pageBlockSection title="Basic Information" columns="1">
                    <apex:inputField value="{!opportunity.name}"/>
                    <apex:pageBlockSectionItem >
                        <apex:outputLabel value="Stage"/>
                        <apex:outputPanel >
                            <apex:inputField value="{!opportunity.stageName}">
                                <apex:actionSupport event="onchange" rerender="thePageBlock"
                                                    status="status"/>
                            </apex:inputField>
                            <apex:actionStatus startText="applying value..." id="status"/>
                        </apex:outputPanel>
                    </apex:pageBlockSectionItem>
                    <apex:inputField value="{!opportunity.amount}"/>
                    <apex:inputField value="{!opportunity.closedate}"/>
                    <apex:inputField value="{!opportunity.Probability}"/>

                </apex:pageBlockSection>
            </apex:actionRegion>
            <apex:pageBlockSection title="Closed Lost Information" columns="1"
                                   rendered="{!opportunity.stageName == 'Closed Lost'}">
                <apex:inputField value="{!opportunity.Primary_Competitor__c}"  required="true"/>
                <apex:inputField value="{!opportunity.Reason_Lost__c}"/>
                <apex:inputField value="{!opportunity.OrderNumber__c}"/>
                <apex:inputField value="{!opportunity.TrackingNumber__c}"/>
                
            </apex:pageBlockSection>
            
            

        </apex:pageBlock>

    </apex:form>
    
</apex:page>

 
Dear all, I`m trying to create a code which will prevent duplication in my org. THis code will run if lead is being created/updated and contact is already exisiting. If contact is already exisitng, lead will give an error. what I want to do is, if creator of this lead (user) is "Internal Login", trigger should not be applied and lead should be allowed to create. When I add "If" argument**, it is not working. It is either allowing everyone to create or no one to create dupe. I need a condition where only "Internal User" should be allowed to create dupes.. Can someone please help?

 
trigger AvoidDupe on Lead (before insert, before update) {

  for (Lead myLead : Trigger.new) {
              String Fullname;

                *//adding "if " argument below is not helping. it is either allowing everyone to create or no one to create dupe. I need a condition where only "Internal User" should be allowed to create dupes.

                 if (myLead.CreatedById == '00580000003a935') {
 
if (myLead.Email != null) {
List<Contact> dupes = [SELECT Id, FirstName, LastName,Name FROM Contact WHERE Email = :myLead.Email];
if (dupes.size() > 0) { 
FullName = dupes[0].Name;
mylead.addError('ERROR: There is already an identical record with same email. <a href=\'https://cs1.salesforce.com/' + dupes[0].Id + '\'> Contact - '+ FullName  +  '</a>', false);

} }
  }
}
}

 
Dear all, this may be really simple but I`m not able to figure it out. I have two Number fields "Agents__c" and "stations__c". I want formula field (# of TRE) which will help me to evaluate that if Agent__C is Blank, it will multiply the amount stations__c * 0.55. Similarly, if stations__c is Blank, it will multiply amount Agent__C * 0.55. If both are blank, it should be zero. Can someone please help me with appropriate formula?

I tried below formulas but it does not work. Formula works well on Agent__c but if Agent__c is Blank, and stations__c has value, it does not work

BLANKVALUE(BLANKVALUE(Agent__c, Section__c), 0) * 0.55


IF( NOT(ISBLANK(Agent__c)), Agent__c, IF( NOT(ISBLANK(Station__c)), Station__c, 0 ) ) * 0.55

 
Dear all, below is my code which automatically send email notificaitons when a new Event is created. If opportunity is not tagged to Event, I`m getting a System.NullpointerException. Could you please help in understanding what I`m doing wrong? I`m new to Apex 

Apex trigger NotifyOnSiteVist2 caused an unexpected exception, contact your administrator: Visitnotify: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Visitnotify: line 29, column 1

 
Trigger Visitnotify on Event (after insert){
        
    List<Messaging.SingleEmailMessage> newEmails = new List<Messaging.SingleEmailMessage>();
    List<Id> whatIds = new List<Id>();
    List<Id> createdByIds = new List<Id>();
    for(Event e :Trigger.new)
    {
        createdByIds.add(E.CreatedByID);
        whatIds.add(E.whatId);
    }
    Map<Id, User> users = new Map<Id, User>([SELECT Id, Name from User WHERE Id in :createdByIds]);
    Map<Id, Opportunity> opportunities = new Map<Id, Opportunity>([SELECT Name, Account.Name from Opportunity WHERE Id in :whatIds]);
    for(Event e :Trigger.new){
    
    if(e.whatid != NULL){ 
            String fullTaskURL;
            String Facility;
            Datetime startDate;
            Datetime endDate;
            String Purpose;

            
            // Query to populate CreatedBy name in html template
            Id createdByID = E.CreatedByID;
            String createdByName = users.get(createdByID).Name;
                   
            // Query to populate Opportunity name in html template
            String oppID = E.whatId;  
            String oppName = opportunities.get(oppID).Name;
                                 
        if(E.Site_Visit__C ){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                
            mail.setSubject(' Alert: A New Visit Record is Created');
            mail.setSaveAsActivity(false);
            mail.setTargetObjectId('00580000005LedR'); 
                                     
            fullTaskURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + E.Id;
            Facility = E.Facility__c;
            startDate = E.StartDateTime;
            endDate = E.EndDateTime;
            Purpose = E.Purpose_of_Visit__c;
                
   
            //Generate email template
                String emailBody;
                emailBody = '<html><body>Hi ,<br> <br> A New Site Visit Record has been created: <a href="' + fullTaskURL + '">' + E.Id + '</a><br></body></html>' + '<br> Sales VP: '+ createdByName + '<br> Opportunity/Account Name: '+ oppName + '<br> <br> Site/Facility: ' + Facility+ '<br> Purpose of Visit: ' + Purpose +  '<br> Start Date/Time: ' + StartDate +  '<br> End Date/Time: ' +endDate +  '<br> <br> Thank you <br> <br> Salesforce Admin' ;
                mail.setHtmlBody(emailBody );

            newEmails.add(mail);
        }
    }

    messaging.sendEmail(newEmails);
} }