• Bradley Delaune
  • NEWBIE
  • 94 Points
  • Member since 2013
  • Technical Consultant
  • Etherios

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 28
    Replies

I have several fields on my Case object that I want to auto populate depending on certain conditions.  For the most part, I have my trigger set up to do what I want.  The issue I am running into is at the end of the trigger.  The field (c.Task_Steps__c) is a text field with the ability to have 255 characters.  Currently, how my trigger is written, it populates the text field with a horizontal list like such:

1. Review Quote  2. Approve / Reject Quote  3. Complete task in Salesforce

However, I want to populate this field with vertical list values so that it looks like the following:

  1. Review Quote
  2. Approve / Reject Quote
  3. Complete task in Salesforce

Is this even possible?  I am new to writing Apex and Triggers so any information / code modification would be greatly appreciated :)!

Code:

trigger SEApproveRejectQuote_assignment on Case (Before update)
{for (Case c: Trigger.new)
{if(c.Reason=='Approve / Reject Quote' && c.Status=='New')
{
c.Origin='End User Request';
c.Type='SE Task';
c.Subject='Approve / Reject Quote';
c.Description='Quote approval is needed';
c.Task_Steps__c='1. Review Quote  2. Approve / Reject Quote  3. Complete task in Salesforce';
             }}}

 

Hey,

I have contact Followed Object ,and It has master detail retailionship with contact and look up with user.

When I am deleteing contact ,it's delete contact follow by.it's natural and expected.But when I see debug log  there is DML opetion happening for Delete Contact ,But I can't see DML opertion for Delete Contact Follow,But it's deleting contact follow by.Becuase of absent of DML opertion  in contact follow,My trigger is not firring for contact follow by ?

This behaviour is natural or weired ?
Does anyone know why an
<pre>
<apex:outputPanel layout="block">
</pre>
would generate
<pre>
<div xmlns="http://www.w3.org/1999/xhtml">
</pre>
?  I think it is messing with a javascript library I'm using in my page.  Is there a way to prevent it?

Does anyone understand how to connect Apex DataLoader with a Microsoft SQL Database to moved data in either direction?  Right now, I have my database-conf.xml set up like

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="dbDataSource"
      class="org.apache.commons.dbcp.BasicDataSource"
      destroy-method="close">
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
    <property name="url" value="jdbc:sqlserver://Localhost;databaseName=dltest;selectMethod=cursor;"/>
    <property name="username" value="test"/>
    <property name="password" value="test"/>
</bean>
<bean id="queryAccount"
      class="com.salesforce.dataloader.dao.database.SqlConfig"
      singleton="true">
    <property name="sqlConfig" ref="queryAccountSql"/>
    <property name="dataSource" ref="dbDataSource"/>
</bean>
</beans>

 The process-conf.xml file looks like this.

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="upsertDLTest"
          class="com.salesforce.dataloader.process.ProcessRunner"
          singleton="false">
        <description>.</description>
        <property name="name" value="upsertDLTest"/>
        <property name="configOverrideMap">
            <map>
                <entry key="sfdc.debugMessages" value="true"/>
                <entry key="sfdc.debugMessagesFile" value="DEBUG LOG FILE"/>
                <entry key="sfdc.endpoint" value="ENDPOINT URL"/>
                <entry key="sfdc.username" value="MY USERNAME"/>
                <!-- password below has been encrypted using key file, therefore it will not work without the key setting: process.encryptionKeyFile
                the password is not a valid encrypted value, please generate the real value using encrypt.bat utility -->
                <entry key="sfdc.password" value="ENCRYPTED VALUE"/>
                <entry key="process.encryptionKeyFile" value="ENCRYPTION KEY FILE LOCATION"/>
                <entry key="sfdc.timeoutSecs" value="600"/>
                <entry key="sfdc.loadBatchSize" value="200"/>
                <entry key="sfdc.entity" value="DLTest__c"/>
                <entry key="process.operation" value="upsert"/>
                <entry key="process.mappingFile" value="MAPPING FILE"/>
                <entry key="process.statusOutputDirectory" value="STATUS LOG FOLDER"/>
                <entry key="dataAccess.name" value="queryAccount"/>
                <entry key="dataAccess.type" value="databaseRead"/>
            </map>
        </property>
    </bean>

 I'd appreciate any help anyone can give me.  Thanks!

I wrote and deployed a Test for using a VF page for product line entry.  My Test class worked previously.  Now I am getting a System.Assert Exception error for virtually the same code.  I only added additional required fields for the Opportunity Line Item.  Can anyone help?

Here is the test Class:

@istest (SeeAllData=true)
private class opportunityProductEntryTests {

    static testMethod void theTests(){
       
        // You really should create test data, but I'm going to query instead
        // It's my best shot of avoiding a test failure in most orgs
        // Once you've installed this package though, you might want to write your own tests
        // or at least customize these ones to make them more applicable to your org
           
        OpportunityLineItem oli = [select Id, PricebookEntryId, PricebookEntry.Pricebook2Id, PricebookEntry.Name, PriceBookEntry.Product2Id, OpportunityId, Opportunity.AccountId from OpportunityLineItem limit 1];
              
               
        ////////////////////////////////////////
        //  test opportunityProductEntry
        ////////////////////////////////////////
       
        // load the page      
        PageReference pageRef = Page.opportunityProductEntry;
        pageRef.getParameters().put('Id',oli.OpportunityId);
        system.Test.setCurrentPageReference(pageRef);
       
        // load the extension
        opportunityProductEntryExtension oPEE = new opportunityProductEntryExtension(new ApexPages.StandardController(oli.Opportunity));
       
        // test 'getChosenCurrency' method
        if(UserInfo.isMultiCurrencyOrganization())
            System.assert(oPEE.getChosenCurrency()!='');
        else
            System.assertEquals(oPEE.getChosenCurrency(),'');

        // we know that there is at least one line item, so we confirm
        Integer startCount = oPEE.ShoppingCart.size();
        system.assert(startCount>0);

        //test search functionality without finding anything
        oPEE.searchString = 'michaelforce is a hip cat';
        oPEE.updateAvailableList();
        system.assert(oPEE.AvailableProducts.size()==0);
       
        //test remove from shopping cart
        oPEE.toUnselect = oli.PricebookEntryId;
        oPEE.removeFromShoppingCart();
        system.assert(oPEE.shoppingCart.size()==startCount-1);
       
        //test save and reload extension
        oPEE.onSave();
        oPEE = new opportunityProductEntryExtension(new ApexPages.StandardController(oli.Opportunity));
        system.assert(oPEE.shoppingCart.size()==startCount-1);
       
        // test search again, this time we will find something
        oPEE.searchString = oli.PricebookEntry.Name;
        oPEE.updateAvailableList();
        system.assert(oPEE.AvailableProducts.size()>0);      

        // test add to Shopping Cart function
        oPEE.toSelect = oPEE.AvailableProducts[0].Id;
        oPEE.addToShoppingCart();
        system.assert(oPEE.shoppingCart.size()==startCount);
               
        // test save method - WITHOUT quanitities and amounts entered and confirm that error message is displayed
        oPEE.onSave();
        system.assert(ApexPages.getMessages().size()>0);
       
        // add required info and try save again
        for(OpportunityLineItem o : oPEE.ShoppingCart){
            o.quantity = 5;
            o.unitprice = 300;
            o.Term_Months__c = 12;
            o.Term_on_Product__c = FALSE;
            o.Opportunity_Type__c = 'New Business';
        }
        oPEE.onSave();
       
        // query line items to confirm that the save worked **HERE IS WHERE THE ERROR OCCURS**
        opportunityLineItem[] oli2 = [select Id from opportunityLineItem where OpportunityId = :oli.OpportunityId];
        system.assert(oli2.size()==startCount);
       
        // test on new Opp (no pricebook selected) to make sure redirect is happening
        Opportunity newOpp = new Opportunity(Name='New Opp',stageName='Pipeline',Amount=10,closeDate=System.Today()+30,AccountId=oli.Opportunity.AccountId);
        insert(newOpp);
        oPEE = new opportunityProductEntryExtension(new ApexPages.StandardController(newOpp));
        System.assert(oPEE.priceBookCheck()!=null);
       
        // final quick check of cancel button
        System.assert(oPEE.onCancel()!=null);
       
       
        ////////////////////////////////////////
        //  test redirect page
        ////////////////////////////////////////
       
        // load the page
        pageRef = Page.opportunityProductRedirect;
        pageRef.getParameters().put('Id',oli2[0].Id);
        system.Test.setCurrentPageReference(pageRef);

        // load the extension and confirm that redirect function returns something
        opportunityProductRedirectExtension oPRE = new opportunityProductRedirectExtension(new ApexPages.StandardController(oli2[0]));
        System.assert(oPRE.redirect()!=null);
    
    }

}
Hello All,

We are setting up entitlements within our organization. The requirement is to have a standard SLA for all the accounts and contacts. I have contacted SFDC and they have provided this trigger which will select and set a default entitlement from a contact or account. The trigger is in this link.

https://developer.salesforce.com/page/Default_Entitlement_on_Case_with_Triggers#Trigger_on_Case

However, i need help to add a variable in this trigger which select a default entitlement even if there is nothing on a contact or a account. Basically all new cases created will have a default entitlement set. Can somebody please help? Thank you for your assistance in advance.

Praveen Muppri
I’m a developer that is working on the KnowledgeBase system (PKB2) and featured articles do not work. The out-of-the-box code has the featured articles query populating as below:

String q = '';
q += 'select ' +join(kavFields, ',')+ ' from KnowledgeArticleVersion';
q += ' where PublishStatus = \'' +pkb_Controller.DEFAULT_PUBLISH_STATUS+ '\' and Language = \'' +lang+ '\' and ArticleNumber in :anums’;

Which clearly will not work since you can’t have “in: anums” in a query string, so I fixed that part of it and ran the query again, but there is also a problem when trying to query “ArticleNumber” – it returns 0 in the list on the public knowledge site, but 1 (which is the correct size) when I’m querying it on the Development Console (as a System Admin)

Anyone run into this issue?

  • May 07, 2014
  • Like
  • 0
I'm a newb when it comes to developing on the SF platform.  I've got experience with web application development, but like I said, I'm new to this.  

So I'm trying to create a VF page that will renderas="pdf".  The information will come from the Account sObject that will have use the information from custom fields.  It'll be really easy to make accept for that I can't make an pages in an active org.

I start the dev console > New > Visual Force page

The console looks like its already to go, but I can't save as an alert box pops up with the following:

Deployment Failed
Can't alter metadata in an active org

Right now the only thing that is typed into the editor is:
<apex:page>
</apex:page>

So how do I go about developing a page?
Hello, I am trying to pull the number of results from a query and returning the results.  Here's my code:

function getProductTypes (oppId) { 

var result = sforce.connection.query("Select COUNT() From OpportunityLineItem where OpportunityId = '" + oppId + "' and PricebookEntry.Product2.Name IN ('EAP') "); 

return result; 

}

This is how I am calling it:

if(getProductTypes('{!Opportunity.Id}') >= 1){ 

//do stuff here

} else { 

//do stuff here

}

What I am trying to do is find the number of product attached to the Opportunity.  If there's more than and equal to 1, i want it to run this code.  Else, run the other code.  Is my query and function correct or am I missing something?

Thanks!

Rachel


I have setup a trigger to prevent users with a certain profile from deleting tasks. My trigger won't save to the server due to 0% test coverage, but I based on my understanding, my tyest code is testing the trigger just fine.

Here's my code:

trigger TaskNoDelete on Task (before delete) {

for (Task t : Trigger.old)
{
  if (UserInfo.getProfileId() == '00e600000015vZp')
  {
   t.addError('You are not authorized to delete tasks.');
  }
}
}



@isTest(SeeAllData=true)
public with sharing class TestTaskTriggers {

static testmethod void updatecharge() {

  User u = new User(alias = 'standt', email='standarduser@testorg.com',
  emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
  localesidkey='en_US', profileid = '00e600000015vZp', Center__c = 'Las Vegas, NV',
  timezonesidkey='America/Los_Angeles', username='shalstesteruser@testorg.com');
  insert u;

  Lead l = new Lead(Web_Salutation__c = 'Mrs.', LastName = 'Test',
  Gender__c = 'Female', LeadSource = 'Web Registrant',
  Referral_Source__c = 'Test Referral');

  Task task = new Task();
  task.Subject = 'Test Subject';
  task.ActivityDate = date.newInstance(2100, 4, 22);
  task.OwnerId = u.id;
  task.whatId = l.id;
  insert task;

  System.runAs(u)
  {
   try
   {
    delete task;
   }
   catch (DMLException e)
   {
    task.addError(e);
   }
  }
}


}




Any help is appreciated.
Need help in writing trigger.
I have a custom object 'MPEContact__c' is associated with Account and an standard object 'Contact'. If i delete the Contact record, the record associated with 'MPEContact__c' object should also be deleted.

My Code:

trigger updateContactMpe on MPEContact__c (after update) {

    Set<Id> accountId = new Set<Id>();
    Set<Id> empAppId = new Set<Id>();
    Set<String> ctxType;
    List<Contact> contactUpdateList = new List<Contact>();
    Map<String,MPEContact__c> mapContact = new Map<String,MPEContact__c>();
    Map<String,Contact> accContact = new Map<String,Contact>();
    Map<String,Contact> conUpdMap = new Map<String,Contact>();
  
    Schema.DescribeSObjectResult CONT_RT = Schema.SObjectType.Contact;
    Map<String,Schema.RecordTypeInfo> CONT_RTMapByName = CONT_RT.getRecordTypeInfosByName();
    Schema.RecordTypeInfo MPE_PART_CON_NAME = CONT_RTMapByName.get('MPE Partner Contact');
    Id PART_CON_RTId = MPE_PART_CON_NAME.getRecordTypeId();
  
  
try{
    for(MPEContact__c mpContact: trigger.new)
    {
        if(mpContact.Account__c!=null && mpContact.Application__c!=null && mpContact.EMail__c!=null)
        {
                accountId.add(mpContact.Account__c);
                empAppId.add(mpContact.Application__c);
                mapContact.put(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase(),mpContact);
        }
    }

    List<Empower_Application__c> empApp = new List<Empower_Application__c>();
    if(accountId.size()>0)
        empApp= [Select  Id,Application_Status__c from Empower_Application__c where Id in :empAppId and Application_Status__c in ('Transition Completed','Approved')];
  
    if(empApp.size()>0){
        if(accountId.size()>0){
            List<Contact> theContact = [Select Id, AccountId, firstName, lastName, Email, Phone, Title, MailingStreet, MailingCity, MailingState,
                                               MailingPostalCode, MailingCountry, MobilePhone, Salutation, Technolgy_Preference__c,
                                               Contact_Type__c, Primary_Contact_Type__c, Vertical_Market_Preference__c, Preferred_Language__c
                                          From Contact Where Accountid in :accountId];
          
            if(theContact.size()>0){
                for(Contact con : theContact)
                {
                    if(con.Email != null && mapContact.containsKey(con.lastName.toLowerCase()+'-'+con.Email.toLowerCase())) {
                        accContact.put(con.lastName.toLowerCase()+'-'+con.Email.toLowerCase(),con);
                    }
                }
            }
        }
      
        for(MPEContact__c mpContact: trigger.new)
        {
          
            if(mpContact.Account__c!=null && mpContact.Application__c!=null && mpContact.EMail__c!=null)
            {
              
                Contact cont;
                ctxType = new Set<String>();
              
                if (mpContact.Secondary_Role__c != null){
                    ctxType = new Set<String> (mpContact.Secondary_Role__c.split(';'));
                }
              
                if(accContact.containsKey(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()) &&
                   !conUpdMap.containsKey(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase())) {
                  
                    cont = new Contact(Id=accContact.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Id,
                                       Primary_Contact_Type__c=accContact.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Primary_Contact_Type__c,
                                       Contact_Type__c=accContact.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Contact_Type__c,
                                       LastName=accContact.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).LastName,
                                       Email=accContact.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Email);                                      
                  
                    if(cont.Primary_Contact_Type__c == null || cont.Primary_Contact_Type__c.trim() == ''){
                        cont.Primary_Contact_Type__c = mpContact.Primary_Role__c;
                    } else {
                        ctxType.add(mpContact.Primary_Role__c);
                    }
                  
                    if(cont.Contact_Type__c == null || cont.Contact_Type__c.trim() == ''){
                        cont.Contact_Type__c = mpContact.Secondary_Role__c;
                    } else {                                              
                        if(mpContact.Secondary_Role__c != null && ctxType.size()>0){
                            for(String sc : ctxType){
                                if(!accContact.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Contact_Type__c.contains(sc)){
                                    cont.Contact_Type__c = cont.Contact_Type__c + ';' + sc;
                                }
                            }
                        }
                    }                  
                     
                }
              
                if(conUpdMap.containsKey(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase())){

                  cont = new Contact(Id=conUpdMap.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Id,
                                       Primary_Contact_Type__c=conUpdMap.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Primary_Contact_Type__c,
                                       Contact_Type__c=conUpdMap.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Contact_Type__c,
                                       LastName=conUpdMap.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).LastName,
                                       Email=conUpdMap.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Email,                                     
                                       Tag__c=conUpdMap.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Tag__c);
                                     

                    if(cont.Primary_Contact_Type__c == null || cont.Primary_Contact_Type__c.trim() == ''){
                        cont.Primary_Contact_Type__c = mpContact.Primary_Role__c;
                    } else {
                        ctxType.add(mpContact.Primary_Role__c);
                    }
                  
                    if(cont.Contact_Type__c == null || cont.Contact_Type__c.trim() == ''){
                        cont.Contact_Type__c = mpContact.Secondary_Role__c;
                    } else {
                        if(mpContact.Secondary_Role__c != null && ctxType.size()>0){
                            for(String sc : ctxType){
                                if(!conUpdMap.get(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()).Contact_Type__c.contains(sc)){
                                    cont.Contact_Type__c = cont.Contact_Type__c + ';' + sc;
                                }
                            }
                        }
                    }
                  
                }
              
                if(!accContact.containsKey(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase()) &&
                   !conUpdMap.containsKey(mpContact.Last_Name__c.toLowerCase()+'-'+mpContact.Email__c.toLowerCase())) {
                    cont = new Contact();
                    cont.Primary_Contact_Type__c = mpContact.Primary_Role__c;
                    cont.Contact_Type__c = mpContact.Secondary_Role__c;
                    cont.Email=mpContact.Email__c;
                    cont.LastName = mpContact.Last_Name__c;                  
                }
              
                cont.AccountId = mpContact.Account__c;
                cont.FirstName = mpContact.First_Name__c;

                cont.First_Name_Local_Language__c = mpContact.First_Name_Local_Language__c;
                cont.Last_Name_Local_Language__c = mpContact.Last_Name_Local_Language__c;
                cont.Phone = mpContact.Phone__c;
                cont.Fax=mpContact.Fax__c;
                cont.MobilePhone=mpContact.Mobile__c;
                cont.MailingPostalCode=mpContact.Postal_Code__c;
                cont.Preferred_Language__c=mpContact.Primary_Language__c;              
                cont.Salutation=mpContact.Salutation__c;
                cont.MailingState=mpContact.State__c;
                cont.MailingCountry = mpContact.Country__c;
              

                cont.RecordTypeId=PART_CON_RTId;
              

              
                if(mpContact.Authorized_Partner_Admin__c){
                    cont.Tag__c ='SFDC Partner Admin';
                }
              
                if (mpContact.Street_Address2__c != null) {
                    cont.MailingStreet = mpContact.Street_Address1__c+' '+mpContact.Street_Address2__c;
                } else {
                    cont.MailingStreet=mpContact.Street_Address1__c;
                }
              
                cont.Technolgy_Preference__c=mpContact.Technolgy_Preference__c;
                cont.Title=mpContact.Title__c;
                cont.Vertical_Market_Preference__c=mpContact.Vertical_Market_Preference__c;
                cont.MailingCity=mpContact.City__c;
              
                conUpdMap.put(cont.LastName.toLowerCase()+'-'+cont.Email.toLowerCase(),cont);
                              
            }
        }
    }
  
    if(conUpdMap.size()>0){
        contactUpdateList = conUpdMap.values();
    }
  
    if(contactUpdateList.size()>0){
        upsert contactUpdateList;
    }
      
}
catch(Exception e)
    {
        String objectName ='MPEContact__c';
        String userName=userInfo.getName();
        datetime myDateTime = datetime.now();
        CreateErrorLog.createErrorRecord(e.getmessage(),objectName,e.getStackTraceString(),userName,myDateTime,e.getTypeName());
    }

}
  • May 07, 2014
  • Like
  • 0
Having a bit of an issue with an if else Trigger.

If Rejected --- marked rejected on Parent
If Submitted not all Approved -- Mark Submit
If all Approved -- Approved.


trigger ADRUserTriggerV2 on ADRUser__c (after update) {

    list<ADR__c> ListOfADRRecords;
    set<Id> PrimaryKeyId = new set<Id>();
    for(ADRUser__c ADRUserRecords :trigger.new){
 
  if(trigger.oldmap.get(ADRUserRecords.id).ApproveReject__c != 'Submit'){
     if(ADRUserRecords.ApproveReject__c =='Submit' || ADRUserRecords.ApproveReject__c =='Approved' || ADRUserRecords.ApproveReject__c =='Rejected'){
   
            PrimaryKeyId.add(ADRUserRecords.ADR__c);// you child object must having parent object field, put that field Api Name here
  }
   
    }
    }

   if(!PrimaryKeyId.isEmpty()) {
                list<ADR__c> listOfParentRecordsToUpdate = [select id, Apex_Status__c from ADR__c where Id =: PrimaryKeyId];
                ListOfADRRecords = new list<ADR__c>();
     
             
    
                 
      for(ADRUser__c ADRUserRecords :trigger.new){
    for(ADR__c ADRRecordTOUpdate : listOfParentRecordsToUpdate) {

if (ADRUserRecords.ApproveReject__c =='Rejected' ) {
    ADRRecordTOUpdate.Apex_Status__c = 'Rejected';
} else if (ADRUserRecords.ApproveReject__c =='Submit' || ADRUserRecords.ApproveReject__c =='Approved') {
  ADRRecordTOUpdate.Apex_Status__c = 'Submit';
}  else {
    ADRRecordTOUpdate.Apex_Status__c = 'Approved';
}
ListOfADRRecords.add(ADRRecordTOUpdate);


            Update ListOfADRRecords;
}
          }
   }
    }
    // }
Hi,

I am new to trigger creation and have mostly built what I wanted which is to have my trigger create a quote automatically once the sales Rep creates the opportunity. The only thing that is missing si to have the trigger also open up that quote that was just created, so the structure would be: Open new Opportunity -> input data -> Click save -> Trigger executes and creates a new quote from that opportunity -> the sales rep lands within the quote ready to select the products (this part is missing.

Not sure if this is possible for a triggers. Here is what I have:

trigger QuoteCreator on Opportunity (after insert, after update) {
Map<Quote, Id> quoteMap = new Map<Quote, Id>();
for (Opportunity o : Trigger.new) {
Quote q = new Quote();
q.name = 'Quote-' + o.name;
q.opportunityId = o.id;
insert q;
quoteMap.put(q, o.accountId);
}
Account[] accList = [SELECT
billingStreet,
billingCity,
billingState,
billingCountry
FROM
Account
WHERE
id IN :quoteMap.values()];
for (Quote quote : quoteMap.KeySet()) {
for (Account a : accList) {
if (quoteMap.get(quote) == a.Id) {
quote.billingStreet = a.billingStreet;
quote.billingCity = a.billingCity;
quote.billingState = a.billingState;
quote.billingCountry = a.billingCountry;
}
update quote;
}
}
}


The second part is creating a test class for it so I can get it moved into production. The Trigger works great within the sandbox, but the testing is needed from what I know about trigger dev into production. Please let me know if I am even doing it right. Here is what I have:

@isTest
private class QuoteCreator {

static testMethod void QuoteCreator() {

    Map<Quote, Id> quoteMap = new Map<Quote, Id>();
       
for (Opportunity o : Trigger.new) {
Quote q = new Quote();
q.name = 'Quote-' + o.name;
q.opportunityId = o.id;
    insert q;
quoteMap.put(q, o.accountId);
    }
   
    test.startTest();

    update quoteMap;

    test.stopTest();
}
}
I have been creating a Business Hours Calculation engine in the past few weeks and I have my code working exaclty how I want it and now have moved on to test code. As Bob Buzzard Pointed out, although not well documented Business Hour Data is available in Test Code Context. Holidays, however are not, you have to create your own. This can be verified by this simple test below

@isTest
private class BusinessHoursMathTest {

    static void SimpleTest(){

        List<BusinessHours> bhs = [select id from BusinessHours where IsDefault=true];
        System.assert(bhs.size() == 1);

        List<Holiday> holidays = [Select Id From Holiday];
        system.assert(holidays.size() == 0);

        List<Account> accs = [select id from Account];
        System.assert(accs.size() == 0);
    }  
}


So I would think that it would be as simple as Querying for Default business Hours, creating a new Holiday, and associating that Holiday with the Business Hours. Something like this

BusinessHours defaultBH = [Select Id From BusinessHours Where IsDefault = True];
Holiday hol = new Holiday();
hol.Name='Test holiday';
hol.activitydate = System.Today();
insert hol;


The holiday is inserted, but there is no affiliation of that Holiday with the Business Hours. I have found that there is no way to affiliate the Holiday with the business hours with Apex. This means I can't properly test my class. I can still get the code coverage I need to deploy, but I can't properly test all logic branches this way. If I wanted to package this that would be a big no no.

MY QUESTION

Does anyone know of a workaround for this. How can I properly test business hour logic without being able to create holidays and associate them with business hours in the test class. Has anyone come up with a way to do this or can you let me know if I have missed anything or not going about this the proper way. I'm pulling my hair out with this one.

Does anyone know a way to detect console mode from a home page component (VF Page)? We have a visual force page, added as a wide home page component. Within the page JS, we are trying to detect whether the page is in console using "sforce.console.isInConsole()". But this does not seem to work. Any suggestions?

  • November 28, 2013
  • Like
  • 0