• Redmanx03
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 8
    Replies

Has anyone had experience with this? Wondering if i can force a trigger to Truncate a custom object prior to inserting new records. 

Hello All recently this error came up, i have not done anything but create a new trigger on opportunity. Any Idea Why this would fire off if my trigger is after update

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OpportunityLineItemUniqueID: execution of BeforeUpdate

caused by: System.LimitException: Too many SOQL queries: 101

Trigger.OpportunityLineItemUniqueID: line 7, column 1: []

 

Trigger:

trigger OpportunityLineItemUniqueID on OpportunityLineItem (before insert, before update) {
    Set<Id> OpportunityIDs = new Set<Id>();
    for (OpportunityLineItem oli : Trigger.New) {
        OpportunityIDs.add(oli.OpportunityId);
    }
    
    Map<Id, Opportunity> Opportunities = new Map<Id, Opportunity>([SELECT Id, OrderId__c FROM Opportunity WHERE Id in :OpportunityIDs]);
    
    for (OpportunityLineItem oli : Trigger.New) {
        Opportunity opp = Opportunities.get(oli.OpportunityId);
        if (opp == null) continue;
        if (opp.OrderId__c == null || opp.OrderId__c == '') continue;
        if (oli.Sequence__c == null || oli.Sequence__c == '') continue;
        
        oli.ScheduleId__c = opp.OrderId__c + '.' + oli.Sequence__c;
    }
}

 

Hello Have A trigger on Opportunity but I cannot Get Code Coverage over 37%. What Am I Doing Wrong?

Trigger:

 

trigger ChatterWonOpportunitySAPremise on Opportunity (After insert, After update) {

String status;
String OppAccName;
String OppOwnerName;
FeedItem post = new FeedItem();



   Set<Id> ownerIds = new Set<Id>();
   
       for (Opportunity o : trigger.new) {
        ownerIds.add(o.OwnerId);
    }
 
    Map<Id, User> mapUsers = new Map<Id, User>([SELECT Id, Profile.Name,User_Market__c FROM User WHERE Id IN :ownerIds ]);
 
    for (Opportunity o : trigger.new) {
    
        User oOwner = mapUsers.get(o.OwnerId);
 
        if (oOwner.Profile.Name != 'Hearst Premise/ DMS User '& oOwner.User_Market__c!='San Antonio') {
            Return;
        }
        
        
    
/*    for(Opportunity o : Trigger.new) {
        if(o.OwnerId == '005d0000001TUC8') { //It will not post record for for this user to group.
            return;
        }    */
        else {
            if(Trigger.isInsert ) { 
                if(o.IsWon == true ) { //This will be executed on any Closed Won Record
                    for (Opportunity oppty : [SELECT Account.Name, Owner.Name,Amount FROM Opportunity WHERE Id =:o.Id] ) {
                        OppAccName = oppty.Account.Name;
                        OppOwnerName = oppty.Owner.Name;
                    }    
                    status = OppOwnerName + ' just won ' + OppAccName + ' for ' + o.Amount + '!';

                    post.ParentId = '0F9J00000008VHB';
                    post.Title = o.Name;
                    post.Body = status;
                    
                    insert post;
                }
            }    
            else {
                if ( Trigger.isUpdate ) {
                    if(o.IsWon == true && Trigger.oldMap.get(o.id).IsWon == false) { //This will be executed on update to existing record
                        for (Opportunity oppty : [SELECT Account.Name, Owner.Name FROM Opportunity WHERE Id =:o.Id] ) {
                            OppAccName = oppty.Account.Name;
                            OppOwnerName = oppty.Owner.Name;
                        }    
                        status = OppOwnerName + ' just won ' + OppAccName + ' for ' + o.Amount + '!';
                            
                        post.ParentId = '0F9J00000008VHB';
                        post.Title = o.Name;
                        post.Body = status;
                        
                        insert post;      
                    }
                }
            }
        }
    }    
}

 Test Class:

@isTest
private class TestChatterWonOpportunitySAPremise{




    static testMethod void TestChatterWonOpportunitySAPremise() {
//        Profile p = [SELECT Id FROM profile WHERE name='Hearst Premise/ DMS User']; //

Profile pp = [Select id from Profile where Name = 'Hearst Premise/ DMS User' limit 1];
        User u = new User(
            Alias = 'Prem', 
            Email='Premiseuser@testorg.com',
            EmailEncodingKey='UTF-8',
            LastName='PremiseTesting',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            ProfileId = pp.Id,
            TimeZoneSidKey='America/Los_Angeles',
            UserName='Premiseuser@testorg.com',
            User_Market__c='San Antonio'            
        );
        Insert u;
        
        


    
       
        
        Account account = new Account(Name = 'Test Account');
    Database.insert(account);
        Opportunity o = new Opportunity(Account=Account,Amount =1500,Name='Test', StageName='Closed - Won',CloseDate= system.Today());
//o.Ownerid=u.id;//
        insert o; 
Opportunity oppCreated = [Select Name, Account.Name, StageName, Owner.Name, Amount From Opportunity Where Id =: o.Id LIMIT 1];        
        
        
String status;
String OppAccName;
String OppOwnerName;
FeedItem post = new FeedItem(); 
 
             
        
                           for (Opportunity oppty1 : [SELECT Account.Name,StageName, Owner.Name,Amount FROM Opportunity WHERE Id =:o.Id] ) {
                        OppAccName = oppty1.Account.Name;
                        OppOwnerName = oppty1.Owner.Name;
                            //Test that Stage = 'Closed - Won'
        system.assertEquals(o.StageName, 'Closed - Won');           
                    } 

     

        
                            status = OppOwnerName + ' just won ' + OppAccName + ' for ' + o.Amount + '!';

                    post.ParentId = '0F9J00000008VHB';
                    post.Title = o.Name;
                    post.Body = status;
    
            insert post;
}
}

 

public with sharing class CompsearchController {

  
  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of Comps to display
  public List<Comp__c> Comps {get;set;}
  

  
  
 
  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }
 
  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'SubMarket__c'; } return sortField;  }
    set;
  }
 
  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }
 
  // init the controller and display some sample data when the page loads

       
    public CompsearchController(ApexPages.StandardController controller){

            
    soql = 'select Zip_Code__c, SubMarket__c, Property_Type__c, Picklist__c from Comps where Property_Type__c != null';
    runQuery();
  }
 
 
  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }
 
  // runs the actual query
  public void runQuery() {
 
    try {
      Comps = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error Please check!'));
    }
 
  }
 
  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
 
    String SubMarket = Apexpages.currentPage().getParameters().get('SubMarket__c');

 
    soql = 'select Zip_Code__c, SubMarket__c, Property_Type__c, Picklist__c from Comps ';

    if (!SubMarket.equals(''))
      soql += ' SubMarket__c Like (\''+SubMarket+'\')';
 
    // run the query again
    runQuery();
 
    return null;
  }
 
  // use apex describe to build the picklist values
  public List<String> SubMarkets {
    get {
      if (SubMarkets == null) {
 
        SubMarkets = new List<String>();
        Schema.DescribeFieldResult field = Comp__c.SubMarket__c.getDescribe();
 
        for (Schema.PicklistEntry f : field.getPicklistValues())
          SubMarkets.add(f.getLabel());
 
      }
      return SubMarkets;          
    }
    set;
  }
 
}

I get the error when I run the code above... What am I doing wrong? I tried tweaking to work with a custom object.

 

 

Below is VF Page

 

<apex:page StandardController="Comp__c" extensions="CompsearchController" sidebar="false">
 
  <apex:form >

  <apex:pageMessages id="errors" />
 
  <apex:pageBlock title="Find Me A Customer!" mode="edit">
 
  <table width="100%" border="0">
  <tr> 
    <td width="200" valign="top">
 
      <apex:pageBlock title="Parameters" mode="edit" id="criteria">
 
      <script type="text/javascript">
      function doSearch() {
        searchServer(

          document.getElementById("SubMarket").options[document.getElementById("SubMarket").selectedIndex].value
          );
      }
      </script>
 
      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="Submarket" value="" />
      </apex:actionFunction>
 
      <table cellpadding="2" cellspacing="2">
      <tr>

        <td style="font-weight:bold;">SubMarket<br/>
          <select id="SubMarket" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!Submarkets}" var="tech">
              <option value="{!tech}">{!tech}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>
 
      </apex:pageBlock>
 
    </td>
    <td valign="top">
 
    <apex:pageBlock mode="edit" id="results">
 
        <apex:pageBlockTable value="{!Comps}" var="Comp">
 
                  
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Submarket" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="Submarket__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!Comp__c.SubMarket__c}"/>
            </apex:column>
 
        </apex:pageBlockTable>
 
    </apex:pageBlock>
 
    </td>
  </tr>
  </table>
 
  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />          
  </apex:pageBlock>   
 
  </apex:pageBlock>
 
  </apex:form>
 
</apex:page>