• MTBRider
  • NEWBIE
  • 494 Points
  • Member since 2008

  • Chatter
    Feed
  • 16
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 47
    Questions
  • 113
    Replies
This may be a basic question, but I need to manipulate a string. I have a string that is a phone number in this format: +18888888888. I need it to become 888-888-8888. How can I do so?
Thank you!
Can Any Idea about this both alpha numeric and values between 100-200 should work.
ex.zx12should work
ex.101should work
ex.201 should not work.
Any formula idea about this.

I have a trigger that runs after a PO Number record is created. It finds the record's related Opportunity and updates the PO Number lookup field on the Opportunity with the PO Number that fired the trigger. 

 

Everything works fine except that it's not bulkified. SOQL and DML in a for loop. I'm having difficulty understanding how to bulkify something like this. I know collections are needed but I'm not sure how to use them correctly.

 

Can anyone please help me understand a step by step process of how to bulkify something like this trigger? Any help is greatly appreciated.

 

trigger updateOppPoNumber on PO_Number__c (after insert) {
    for (PO_Number__c poNum : Trigger.new) {
        if (poNum.Id != null && poNum.Opportunity__c != null) {
            // Get related Opportunity
            List<Opportunity> opp = [
                SELECT Id, PO_Number__c
                  FROM Opportunity
                 WHERE Id = :poNum.Opportunity__c
                 LIMIT 1
            ];

            // Update related Opportunity with PO Number
            if (!opp.isEmpty()) {
                opp.get(0).PO_Number__c = poNum.Id;
                update opp;
            }
        }
    }
}
Can you deserializeUntyped with JSON arrays?
I'm finding it difficult to get down into the "client" level so that I can retrieve ID and Status. 
results.get('items') was easy enough at the top level, but attempting results.get('client') fails.

Using this JSON:
{
    "items": [
        {
            "client": {
                "id": "xyz65240-a8e0-4184-8aaa-8b381ea83ce5",
                "status": "enabled"
            }
        },
        {
            "client": {
                "id": "8b265241-3662-4a49-b7dd-97f948ca9bb6",
                "status": "enabled"
            }
        }
    ]
}

Using this code:
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());

List<Object> items = (List<Object>) results.get('items');
    System.debug('Received the following items:');
    for (Object item: items) {
        System.debug('Item:');
        System.debug(item);
    }

Hi All!

The LWC I've created lives on the Opportunity record page - and I want the LWC to pull all of the related records from an object titled, 'Junction - Opportunity/Competitor'. Right now, I am only able to hard code the recordid that the component pulls from. 

I am trying to get my LWC (a lightning-datatable) to pull in the recordid automatically so that the component shows information relevant to the record you're viewing.



relatedlist_competitor.cls

public with sharing class relatedlist_competitor {
    @AuraEnabled(cacheable = true)
public static List<Junction_Competitor_Opportunity__c> fetchCompetitor (String Opportunityid){
       return [SELECT Id,Competitor_Name_for_Flow__c,Bullet_1__c,Bullet_2__c,Opportunity__c FROM Junction_Competitor_Opportunity__c WHERE Opportunity__c = :Opportunityid];
    }
}


relatedlist_competitor.html
<template>

        <!--lightning datatable-->
         <lightning-datatable 
               key-field="id"
               data={parameters.data}
               onrowaction={handleRowAction}
               row-number-offset={rowOffset}
               hide-checkbox-column="true"
               columns={columns}></lightning-datatable>
                  
           <!-- Detail view modal start -->
         <template if:true={bShowModal}>
          <section role="dialog" tabindex="-1"
                   aria-labelledby="modal-heading-01"
                   aria-modal="true"
                   aria-describedby="modal-content-id-1"
                  class="slds-modal slds-fade-in-open">
             <div class="slds-modal__container">
                <!-- modal header start -->
                <header class="slds-modal__header">
                   <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={closeModal}>
                      <lightning-icon icon-name="utility:close" alternative-text="close" variant="inverse" size="small" ></lightning-icon>
                   </button>
                   <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Record Detail</h2>
                </header>
                <!-- modal body start -->
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                  <dl class="slds-list_horizontal slds-wrap">
                      <dt class="slds-item_label" title="Name">Competitor Name</dt>
                      <dd class="slds-item_detail">{record.Competitor_Name_for_Flow__c}</dd>
                  </dl>
                </div>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-2">
                     <dl class="slds-list_horizontal slds-wrap">
                         <dt class="slds-item_label" title="Name">Bullet 1</dt>
                         <dd class="slds-item_detail">{record.Bullet_1__c}</dd>
                     </dl>
                   </div>
                   <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-3">
                        <dl class="slds-list_horizontal slds-wrap">
                            <dt class="slds-item_label" title="Name">Bullet 2</dt>
                            <dd class="slds-item_detail">{record.Bullet_2__c}</dd>
                        </dl>
                      </div>
                <!-- modal footer start-->
                <footer class="slds-modal__footer">
                     <lightning-button variant="brand"
                     label="Close"
                     title="Close"
                     onclick={closeModal}
                     ></lightning-button>
                </footer>
             </div>
          </section>
          <div class="slds-backdrop slds-backdrop_open"></div>
       </template>
       <!-- Detail view modal end -->
  
      </template>

relatedlist_competitor.js
import {
    LightningElement,
    wire,
    api,
    track,
} from 'lwc';
 
//import method from the Apex Class
import fetchCompetitor from '@salesforce/apex/relatedlist_competitor.fetchCompetitor';
 
// Declaring the columns in the datatable
const columns = [{
        label: '',
        type: 'button-icon',
        initialWidth: 75,
        typeAttributes: {
            iconName: 'utility:picklist_type',
            title: 'Preview',
            variant: 'border-filled',
            alternativeText: 'View'
        }
    },
    {
        label: 'Competitor',
        fieldName: 'Competitor_Name_for_Flow__c'
    },
];
 
// declare class to expose the component
export default class DataTableComponent extends LightningElement {
    @track columns = columns;
    @track record = {};
    @track rowOffset = 0;
    @track data = {};
    @track bShowModal = false;
    @api recordid;
    @wire(fetchCompetitor, {Opportunityid:"00629000008UIbbAAG"}) parameters;
 
    // Row Action event to show the details of the record
    handleRowAction(event) {
        const row = event.detail.row;
        this.record = row;
        this.bShowModal = true; // display modal window
    }
 
    // to close modal window set 'bShowModal' tarck value as false
    closeModal() {
        this.bShowModal = false;
    }
}

relatedlist_competitor.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="dataTableComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <!-- With following targets make component available for lightning app page, record page and home page in salesforce --><targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 
I have a client that I implemented nightly batch load process for years ago using the dataloader command line interface.  It has worked every night for 7 years without an issue.  They now need to upgrade the server it is running on and at the same time want to upgrade dataloader.  They installed dataloader 34.0 and I cannot get it to connect to salesforce and I am starting to think there is a bug in dataloader 34. 

Here is the error:
 
C:\Program Files (x86)\salesforce.com\Data Loader\bin>process "C:\Program Files (x86)\salesforce.com\Data Loader" tempCont
2015-06-23 11:19:54,373 INFO  [main] controller.Controller initLog (Controller.java:389) - Using built-in logging configuration
\salesforce.com\Data Loader\bin\log-conf.xml
2015-06-23 11:19:54,373 INFO  [main] controller.Controller initLog (Controller.java:391) - The log has been initialized
2015-06-23 11:19:54,373 INFO  [main] process.ProcessConfig getBeanFactory (ProcessConfig.java:103) - Loading process configurat
)\salesforce.com\Data Loader\process-conf.xml
2015-06-23 11:19:54,443 INFO  [main] support.AbstractApplicationContext prepareRefresh (AbstractApplicationContext.java:495) -
ort.FileSystemXmlApplicationContext@13bd574: startup date [Tue Jun 23 11:19:54 PDT 2015]; root of context hierarchy
2015-06-23 11:19:54,474 INFO  [main] xml.XmlBeanDefinitionReader loadBeanDefinitions (XmlBeanDefinitionReader.java:315) - Loadi
/Program Files (x86)/salesforce.com/Data Loader/process-conf.xml]
2015-06-23 11:19:59,029 ERROR [main] process.ProcessConfig getProcessInstance (ProcessConfig.java:96) - Error loading process:
\Program Files (x86)\salesforce.com\Data Loader\process-conf.xml
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from URL [file://C:/Program Fi
s-conf.xml]; nested exception is java.net.UnknownHostException: C
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionRea
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionRea
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionRea
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionRea
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableAppl
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.jav
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:436)
        at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:140)
        at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:84)
        at com.salesforce.dataloader.process.ProcessConfig.getBeanFactory(ProcessConfig.java:105)
        at com.salesforce.dataloader.process.ProcessConfig.getProcessInstance(ProcessConfig.java:93)
        at com.salesforce.dataloader.process.ProcessRunner.getInstance(ProcessRunner.java:287)
        at com.salesforce.dataloader.process.ProcessRunner.getInstance(ProcessRunner.java:273)
        at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:246)
Caused by: java.net.UnknownHostException: C
        at java.net.PlainSocketImpl.connect(Unknown Source)
        at java.net.SocksSocketImpl.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at sun.net.NetworkClient.doConnect(Unknown Source)
        at sun.net.NetworkClient.openServer(Unknown Source)
        at sun.net.ftp.FtpClient.openServer(Unknown Source)
        at sun.net.ftp.FtpClient.openServer(Unknown Source)
        at sun.net.www.protocol.ftp.FtpURLConnection.connect(Unknown Source)
        at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(Unknown Source)
        at org.springframework.core.io.UrlResource.getInputStream(UrlResource.java:125)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
        ... 17 more
2015-06-23 11:19:59,045 FATAL [main] process.ProcessRunner topLevelError (ProcessRunner.java:238) - Failed to create process
com.salesforce.dataloader.exception.ProcessInitializationException: Error loading process: tempCont configuration from config f
Data Loader\process-conf.xml
        at com.salesforce.dataloader.process.ProcessConfig.getProcessInstance(ProcessConfig.java:97)
        at com.salesforce.dataloader.process.ProcessRunner.getInstance(ProcessRunner.java:287)
        at com.salesforce.dataloader.process.ProcessRunner.getInstance(ProcessRunner.java:273)
        at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:246)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from URL [file://C:
ader/process-conf.xml]; nested exception is java.net.UnknownHostException: C
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionRea
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionRea
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionRea
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionRea
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableAppl
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.jav
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:436)
        at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:140)
        at org.springframework.context.support.FileSystemXmlApplicationContext.(FileSystemXmlApplicationContext.java:84)
        at com.salesforce.dataloader.process.ProcessConfig.getBeanFactory(ProcessConfig.java:105)
        at com.salesforce.dataloader.process.ProcessConfig.getProcessInstance(ProcessConfig.java:93)
        ... 3 more
Caused by: java.net.UnknownHostException: C
        at java.net.PlainSocketImpl.connect(Unknown Source)
        at java.net.SocksSocketImpl.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at sun.net.NetworkClient.doConnect(Unknown Source)
        at sun.net.NetworkClient.openServer(Unknown Source)
        at sun.net.ftp.FtpClient.openServer(Unknown Source)
        at sun.net.ftp.FtpClient.openServer(Unknown Source)
        at sun.net.www.protocol.ftp.FtpURLConnection.connect(Unknown Source)
        at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(Unknown Source)
        at org.springframework.core.io.UrlResource.getInputStream(UrlResource.java:125)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
        ... 17 more

The error is java.net.UnknownHostException: C

Here is the relevent bean in the process-conf.xml file:
 
        Test upsert
        
        
            
        
    

The reason that I think there is a bug in DL 34 is because I also have DL 30.0.0 installed on my machine and when I change this line in the process.bat file:
 
..\Java\bin\java.exe -cp ..\dataloader-34.0-uber.jar -Dsalesforce.config.dir=%1  com.salesforce.dataloader.process.ProcessRunner %PROCESS_OPTION%

to this:
 
..\Java\bin\java.exe -cp ..\dataloader-30.0.0-uber.jar -Dsalesforce.config.dir=%1  com.salesforce.dataloader.process.ProcessRunner %PROCESS_OPTION%

and keep everything else the same, I don't get the  java.net.UnknownHostException: C  error.  

Can anyone shed any light onto this?

Thanks
Hi There,

I am looking to make a minor change to an apex class in production? What is the best and secure way of making this change? (ie: change it in sandbox, and push the change set through to production? OR make the change in Eclipse and update the changes to the server?)

Also, if you could point me a resource which shows you how to update the code from eclipse to our production environment, it would be much appreciated. Thanks!
I have a controller that I built based off this article:

http://www.soliantconsulting.com/blog/2012/08/view-triggers-salesforce-trigger-opportunity-contact-roles

However the issues is after I add a contact role and return to the opportunity page, the fields are not updated. It only updates when I do a manual page refresh.

Here is my controller:
 
public without sharing class OppHelper {
    public Opportunity opp;
    public OppHelper( ApexPages.StandardController stdController ) {
        opp = ( Opportunity )stdController.getRecord();        
    }
    public void insertOppContacts(){
        OppHelper.insertOppContactsFuture( opp.Id );    
    }
    @future public static void insertOppContactsFuture( Id oppId ) {
        Contact[] contactList = [ SELECT Id, FirstName, LastName, Email FROM Contact
                             WHERE Id IN ( SELECT ContactId FROM OpportunityContactRole
                                         WHERE OpportunityId = :oppId AND isPrimary = True ) ];
        Opportunity opp = [ SELECT Id, Primary_Contact__c FROM Opportunity WHERE Id = :oppId ];
        
        for( Contact contact : contactList ) {
            opp.Primary_Contact__c = contact.Id;
        }
        update opp;
    }
}



Here is my visualforce page:
 
<apex:page standardController="Opportunity" extensions="OppHelper" action="{!insertOppContacts}" />

 
I am seeing an issue with Activities History since my client's org got upgraded to Winter 15 over this last weekend.  Look at the sample VF page below:
<apex:page standardcontroller="Account">
	<apex:pageBlock title="Testing Activities History" >
	 	<apex:pageBlockSection title="Activities History in pageBlockTable use to work before Winter 15">
			<apex:pageBlockTable value="{!account.ActivityHistories}" var="x">
				<apex:column value="{!x.Account.Name}"/>
				<apex:column value="{!x.subject}"/>	
				<apex:column value="{!x.status}"/>
				<apex:column value="{!x.owner.name}"/>
			</apex:pageBlockTable>
		</apex:pageBlockSection>
	 	<apex:pageBlockSection title="Activities History using relatedList tag">
			<apex:relatedList list="ActivityHistories" pageSize="10"/>
		</apex:pageBlockSection>
	</apex:pageBlock>
	
	<apex:pageBlock title="Testing Open Activities" >
		<apex:pageBlockSection title="Open Activities in pageBlockTable still works after Winter 15">
			<apex:pageBlockTable value="{!account.OpenActivities}" var="x">
				<apex:column value="{!x.Account.Name}"/>
				<apex:column value="{!x.subject}"/>	
				<apex:column value="{!x.status}"/>
				<apex:column value="{!x.owner.name}"/>
			</apex:pageBlockTable>
		</apex:pageBlockSection>
		<apex:pageBlockSection title="Open Activities using relatedList tag">
			<apex:relatedList list="OpenActivities" pageSize="10"/>
		</apex:pageBlockSection>
	</apex:pageBlock>
</apex:page>
There have always been restrictions on how you look up Activities History and Open Activities for non Admin users, but the two pageBlockTables worked for non Admin users before the Winter 15 upgrade.  After the upgrade, only the Open Activities pageBloackTable works for non Admin users.  The ActivityHistories pageBlockTable for a non Admin user will now return the error message:

Object type not accessible. Please check permissions and make sure the object is not in development mode: There is an implementation restriction on ActivityHistories. When you query this relationship, security evaluation is implemented for users who don't have administrator permissions, and you must use a specific sort order: ActivityDate DESC, LastModifiedDate DESC 

Since the pageBlockTable is just using the standard relationship lookup in this case, there is no opportunity to add the sort order to the query.  

I read through the Winter 15 release notes and cannot find anything about a change that might effect this.

Anyone else seeing this?

Salesforce, is this a bug?  

I need a resolution to this since my clients cannot use some functionality since this weekend due to this issue.  

Thanks
Hello,

I am building a "Site" for guest users to submit a Case for support.  I have the site built, the visualforce page, and a controller extension built to add an attchment.  When the case is submitted form the site, it creates a Case record in Salesforce, the attachment shows under the notes and attachments related list, but the subject and description fields that were filled out on the Site are not being populated on the case record.  

I am at a loss here as to why they are not working, and I am a new developer so I very well could have missed something very easy.  Please look over the following code for my VF Page, and the controller extension, and if available please help me figure out how to get the subject and description fields to populate on the case record with the information that was submitted via the site submission.  

Thank you in advance for your time and help!

VF Page

<apex:page standardcontroller="Case" extensions="caseattachment"
showHeader="false">
<img src="{!$resource.AVISPL_Logo2}"></img><b/><b/>
    <apex:form >
    <apex:pageBlock >
<apex:pageBlockSection title="Hello, Thank You For Reporting Your Incident!  A Salesforce Platform Engineer Will Be In Touch Shortly. " columns="1" showHeader="True" collapsible="False">
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageMessages />

        <apex:pageBlock >
        <apex:inputField value="{!Case.CaseNumber}"/>
            <apex:pageBlockSection title="Subject">
                <apex:inputText value="{!Case.subject}" />
            </apex:pageBlockSection>

            <apex:pageBlockSection title="Attachment Or ScreenShot">                                   
            <apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>                            
            
            </apex:pageBlockSection>

            <apex:pageBlockSection title="Tell Us About The Incident">
                <apex:inputTextarea value="{!Case.Description}" rows="8" cols="80" />
            </apex:pageBlockSection>

            <apex:commandButton value="Submit Incident" action="{!Save}" />
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller extension

public class caseattachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;} 
public Blob fileBody{get;set;}

    public caseattachment(Apexpages.standardcontroller controller)
    {
        objcase = new case();
        myAttachment =new Attachment();
    }
    public pagereference save()
    {
        insert objcase;
        System.debug('@@@@@fileBody'+fileBody);     
        myAttachment  = new Attachment();
              Integer i=0;
              myAttachment .clear();
              myAttachment.Body = fileBody;
              myAttachment.Name = this.fileName; 
              myAttachment.ParentId = objcase.id;             
              insert myAttachment;                 
        pagereference pr = new pagereference('/'+objcase.id);                           
        return pr;
    }
}
I have a trigger that fires on Insert/Update.  Works fine when testing this by entering contacts or updating contacts manually one at a time.
However, when there is a batch update it seems to ignore this one  IF condition in my code.

Anyone ever experience this?
I think I have done all I can to "bulkify" this trigger but if I update 200 opportunities at once then I get the error about too many SOQL queries. I can't see anything more I need to do for this trigger. What else is there to do?

trigger Update_Sam_Marketing_Customer_Field on Opportunity (after insert, after update, after delete) {

try{
    //the trigger will update the account's SAM Marketing Customer field
    if (! trigger.isDelete) {
    
  List<Id> oppIds = new List<Id>() ;
  List<Id> AccountIds = new List<Id>() ;
  List<Account> AcctToUpdate = new List<Account>() ;
     
      for (opportunity op : trigger.New){
        oppIds.add(op.Id);
        AccountIds.add(op.AccountId);
        
  Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([Select id, StageName from Opportunity where id in :oppIds and
   name = 'Security Audit Manager'and Status__c != 'Inactive']) ;   
    
  Map<Id,Account> acctMap = new Map<Id,Account>([select id, SAM_Marketing_Customer__c, name, Closed_Won_Opps__c, Type 
   from Account where id in :AccountIDs]);
  
        //Find the account for this opportunity which is being updated
        Account oAccount =  acctMap.get(op.AccountId);
        Opportunity SamOpportunity = oppMap.get(op.Id);

         if (oppMap.isEmpty()){  //No SAM opportunities
    if (oAccount.Closed_Won_Opps__c == 0 && SamOpportunity.StageName != 'Closed Won') {
     oAccount.SAM_Marketing_Customer__c = 5;
    }
    else {
     oAccount.SAM_Marketing_Customer__c = 4;
    }
    AcctToUpdate.add(oAccount);
         }
         else { //There are SAM opportunities so see how many of them are closed/won
          Integer iCountClosedWon = 0;
          
      for(Opportunity samMap: oppMap.values()){       
     if (samMap.StageName == 'Closed Won') {
      iCountClosedWon += 1;
     }      
      }   
          
          if (iCountClosedWon > 0) {
     oAccount.SAM_Marketing_Customer__c = 1;
          }
          else {
           if (oAccount.Closed_Won_Opps__c == 0){
            oAccount.SAM_Marketing_Customer__c = 3;
      //update oAccount;  
           }
           else {
             oAccount.SAM_Marketing_Customer__c = 2;
           }
           
          }
          AcctToUpdate.add(oAccount);
         }
       }
       update AcctToUpdate;
   }
 
 if (trigger.isDelete) {
    
  List<Id> oppIds = new List<Id>() ;
  List<Id> AccountIds = new List<Id>() ;
  List<Account> AcctToUpdate = new List<Account>() ;
    
     for (opportunity op : trigger.Old){
        oppIds.add(op.Id);
        AccountIds.add(op.AccountId);
        
  Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([Select id, StageName from Opportunity where id in :oppIds and
   name = 'Security Audit Manager'and Status__c != 'Inactive']) ;   
    
  Map<Id,Account> acctMap = new Map<Id,Account>([select id, SAM_Marketing_Customer__c, name, Closed_Won_Opps__c, Type 
   from Account where id in :AccountIDs]);
  
        //Find the account for this opportunity which is being updated
        Account oAccount =  acctMap.get(op.AccountId);
        Opportunity SamOpportunity = oppMap.get(op.Id);

         if (oppMap.isEmpty()){  //No SAM opportunities
    if (oAccount.Closed_Won_Opps__c == 0 && SamOpportunity.StageName != 'Closed Won') {
     oAccount.SAM_Marketing_Customer__c = 5;
    }
    else {
     oAccount.SAM_Marketing_Customer__c = 4;
    }
    AcctToUpdate.add(oAccount);
         }
         else { //There are SAM opportunities so see how many of them are closed/won
          Integer iCountClosedWon = 0;
          
      for(Opportunity samMap: oppMap.values()){       
     if (samMap.StageName == 'Closed Won') {
      iCountClosedWon += 1;
     }      
      }   
          
          if (iCountClosedWon > 0) {
     oAccount.SAM_Marketing_Customer__c = 1;
          }
          else {
           if (oAccount.Closed_Won_Opps__c == 0){
            oAccount.SAM_Marketing_Customer__c = 3;
      //update oAccount;  
           }
           else {
             oAccount.SAM_Marketing_Customer__c = 2;
           }
          }
          AcctToUpdate.add(oAccount);
         }
     }
     update AcctToUpdate;    
   }
}
catch (Exception e ){
            System.debug('Create customer field trigger exception ' + e.getMessage());
            
      }
 }