• Gigi.Ochoa
  • NEWBIE
  • 385 Points
  • Member since 2010
  • Manager
  • Strategic Growth Inc


  • Chatter
    Feed
  • 12
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 56
    Replies
The below code works fine.  However you will notice that I do have a SOQL inside of a loop.
In an attempt to avoid issues down the line, I need to move this outisde the loop.  Any ideas on how to do this an still reference  the current b.Candidate__c(which is the contactID attached to the current Book_of_Business__c record.     Thanks in Advance

trigger BOBChange on Book_of_Business__c (before insert, before update) {
 
List<Quintile__c> Quintiles = new List<Quintile__c> ();
List<Book_of_Business__c> bob=[SELECT Id,Name,Candidate__c  from Book_of_Business__c ];
List<Contact> Contacts = new List<Contact> ();

Quintiles = [Select Quintile__c, T12_Min__c,T12_Max__c, LOS_Min__c, LOS_Max__c
             FROM      
                Quintile__c
             WHERE
                start_date__c <= today AND
                End_date__c > today];
               
              
    If (bob.size() > 0){
        for (Book_of_Business__c b : Trigger.new) {
            system.debug('BOB ------------- > ' + b.Id);
            system.debug('CandidateID ------------- > ' + b.Candidate__c);
            Contacts = [Select ID, Quintile_LOS__c, Total_years_as_a_rep__c, Producer_LOS__c,FirstName, LastName from Contact where ID =: b.Candidate__c];                 
            for (Contact c : Contacts){
             system.debug('C  ID ------------- > ' + c.Id);
                for (Quintile__c q : Quintiles) {
                 if(b.Candidate__c == c.ID &&
                  q.T12_Min__c <= b.Post_Haircut_T_12__c &&
                        q.T12_Max__c > b.Post_Haircut_T_12__c &&
                        q.LOS_Min__c <= c.Quintile_LOS__c &&
                        q.LOS_Max__c > c.Quintile_LOS__c) {
                             b.Quintile__c = q.Quintile__c;   // update BOB Quintile Field
                       System.debug(' Q.Quintile__c --------- >' + Q.Quintile__c);
                             }
                }

            }
        }
    }
}
  • September 05, 2014
  • Like
  • 0
Hello

I have written a trigger but I am now trying to unit test it.  However I am getting the following error message with my apex class.  Can anyone see what I have done wrong?

User-added image

Thanks

Sonya
I have a page that on load pulls from an outside webservice.  This webservice may have issue and therefore won't display data.  I display an error to the user but I want to create a case that is assigned to a group of people in the compnay so it can be worked on.  I am unable to create a case when the page is being loaded due to DML restrictions. 

My Idea: create a checkbox and have it check so that when the error is caught it is cheked and initiates the action method.  This doesn't seem to work as I had planned.

Is anyone doing this and how?
Hi All, 

I wrote a custom controller and now trying to increase the code coverage. It is stuck at 39%. I'm not sure what am I missing? 

public String SelectPrimaryAccount { get; set; }
    public boolean SameAsCaller { get; set; }

 
    public List<SelectOption> getPrimaryAccount() {
        List<SelectOption> primaryAccount = new List<SelectOption>();
        primaryAccount.add(new SelectOption('','-None-'));
        primaryAccount.add(new SelectOption('Caller Account','Caller Account'));
        primaryAccount.add(new SelectOption('Project Site Contact', 'Project Site Contact'));
        primaryAccount.add(new SelectOption('Insurance', 'Insurance'));
 
        return primaryAccount;
    }

    public PageReference Save() {
    
        //Job Account and contact   
            Id acctid = Job.Account__c;
            id conid;
            
            job_Contact__c c1; job_Account__c a1;
            for(Contact con : [select id, accountid from Contact where id =:Job.Account__c]){
                c1 = new job_Contact__c(contact__c = con.id);
                a1 = new Job_Account__c(account__c = con.accountid);
                conid = con.id;
                Job.Account__c = con.accountid;
                
                if(SelectPrimaryAccount == 'Caller Account'){
                            job.account__c = con.accountid;
                }
            }
            
            job_Contact__c c2; job_Account__c a2; Contact con2;
            if(SameAsCaller != true && job.Project_Site_Contact_Name__c != null){
            
                con2 = [select id, accountid from Contact where id =:job.Project_Site_Contact_Name__c limit 1];
                job.Project_Site_Contact_Account__c = con2.accountid;
                
                c2 = new job_Contact__c(contact__c = con2.id);
                a2 = new Job_Account__c(account__c = con2.accountid);
                
                if(SelectPrimaryAccount == 'Project Site Contact'){
                        job.contact__c = job.Project_Site_Contact_Name__c;
                        job.account__c = con2.accountid;
                }
            }
            else {
                job.Project_Site_Contact_Name__c = conid;
                job.Project_Site_Contact_Account__c = job.account__c;
                //job.account__c = conid.accountid;
            }
            
            job_Contact__c c3; job_Account__c a3; Contact con3;
            if(job.Insurance_Adjuster_Broker__c != null){
                con3 = [select id, accountid from Contact where id =:job.Insurance_Adjuster_Broker__c limit 1];
                c3 = new job_Contact__c(contact__c = con3.id);
                a3 = new Job_Account__c(account__c = con3.accountid);
                   
                if(SelectPrimaryAccount == 'Insurance'){
                        job.contact__c = job.Insurance_Adjuster_Broker__c;
                        job.account__c = con3.accountid;
                }
            }
            
            if(acctid != null){
                a3 = new Job_Account__c(account__c = acctid);
                if(SelectPrimaryAccount == 'Insurance'){
                    job.account__c = job.account__c;
                    job.contact__c = null;}
            
            }
            
        
        insert job; 
        
           if(c1!=null){
            c1.job__c = job.id;
            a1.job__c = job.id;
            jcon.add(c1);jacct.add(a1);}
            
            if(c2!=null){
                c2.job__c = job.id;
                a2.job__c = job.id;
                jcon.add(c2); jacct.add(a2);
            }
        
            if(acctid!=null){
                a3.job__c = job.id;
                jacct.add(a3);
                if(c3!=null){
                    c3.job__c = job.id;
                    jcon.add(c3);
                }
            }
          
            insert jCon;
            insert jAcct;

It's getting coverage on the queries and the confitional statements. But that's about it. 

Here's my test class:

@isTest (seealldata = true)
                    
public class CreateNewJobInquiry_Test {

    public static testMethod void TestCreateNewJobInquiry () {
        //PageReference pageRef = page.NewRecord;
        //Test.setCurrentPage(pageRef);
      
        Contact contact = new Contact();
        Account account = new account(billingStreet = contact.mailingstreet, billingcity = contact.mailingCity, billingstate = contact.mailingcity, billingpostalcode = contact.mailingpostalcode, phone = contact.phone);
        account.name = 'CIG';
        insert account;
        
        Contact.contact_type__c = 'Adjustor';
        contact.firstname = 'semira';
        contact.Lastname = 'roy';
        contact.accountid = account.id;
        insert contact;
    
        Contact contact2 = new Contact();
        Contact2.contact_type__c = 'Adjustor';
        contact2.Lastname = 'noname';
        contact2.firstname = 'noname';
        contact2.accountid = account.id;
        insert contact2;
        
        
    Job__c job = new Job__c(account__c = account.id, Job_Name__c = 'test', Project_Site_Address__c = contact.mailingstreet, Project_Site_City__c = 'Los Angeles', Project_Site_state__c = 'CA', Project_Site_zipcode__c ='90027', County__c = 'LA', City_of_LA__c = 'Yes');
    job.contact__c = contact.id;
    job.Project_Site_Contact_Name__c = contact2.id;
    job.Insurance_Adjuster_Broker__c = contact.id;
    
    
    ApexPages.currentPage().getParameters().put('qp', job.id);
    CreateNewJobInquiry testObj2 = new CreateNewJobInquiry();
    testObj2.Sameascaller = false;
    testObj2.SelectPrimaryAccount = 'caller account';
    
        testObj2.save();
    }
}


I have a custom object Pint, I want it create new pint again automatically once a pint's status is Closed.  I got an error message while creating a trigger, please help.

Error Error: Compile Error: Duplicate variable: p (attempt to re-create the variable with type: Pint__c) at line 4 column 32

trigger CreatePin on Pint__c (after update) {
       for (Pint__c p : Trigger.new) {
               if (p.Status == 'Closed') {
                       Pint__c p = new Pint__c();
                       p.Account__c = c.AccountId;                  
               insert p;
        }
        }
        }
This is my third time trying to post this question... Third time's the charm?

Hello all,

I'm having an issue trying to display an image in a PDF rendered Visualforce Page. The image's URL is stored in a field on the object controlling the page.

I've tried using <apex:image...> and <img src...>. Using the actual URL works just fine and displays the image. Removing the renderAs="pdf" displays all images correctly.

Any help would be much appreciated.

Thank you!

Code snippet:

<apex:page standardController="Order__c" showheader="false" standardStylesheets="true" renderAs="PDF">

<apex:pageBlock >
<apex:image value="ImageStoredAsDocument" width="98%"/> <!-- this displays fine -->

        <img src="{!Order__c.CustomField_URL__c}" /> <!-- this does not display when rendered as PDF -->
        <img src="ActualURL" /> <!-- this displays fine -->
</apex:pageBlock>


Hi folks,
          Can anyone tell me how to pass the group id and record id from trigger to apex class
like my apex class is 
Public static passMethod(Id recordId,Id groupId)

Please Help!
I'm trying to utilize some code from the apex guide to share records. I'm getting the too many DML statements error when I run my bulk tests. The bulk test is just inserting a list of 200 objects. The code I modified is here:http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_bulk_sharing_creating_with_apex.htm

Error: System.LimitException: Too many DML statements: 151
Stack Trace: Class.IncidentSharing.manualShareRead: line 25, column 1
Trigger.IncidentTrigger: line 39, column 1

Line 25 column 1 is Database.SaveResult sr = Database.insert(incShr,false);

I realize the insert is running on every call but I don't know how to fix it. Should I pass a map to the class? Can I build a list inside the class and then insert it? I tried building a list and then inserting it but then how do I process the return? Thanks

Trigger Code 
FOR( BMCServiceDesk__Incident__c i : [SELECT id, BMCServiceDesk__Client_Manager__c FROM BMCServiceDesk__Incident__c WHERE (Equipment_Request__c= true OR Manager_Approval__c = true) AND Id IN: trigger.new ]) {
                IncidentSharing.manualShareRead(i.id,i.BMCServiceDesk__Client_Manager__c);
            }
Apes sharing class 
public class IncidentSharing {
   
   public static boolean manualShareRead(Id recordId, Id userOrGroupId){
   //public static boolean manualShareRead(map<Id,Id>){
      // Create new sharing object for the custom object Incident.
      BMCServiceDesk__incident__Share incShr  = new BMCServiceDesk__incident__Share();
       
      // Set the ID of record being shared.
      incShr.ParentId = recordId;
        
      // Set the ID of user or group being granted access.
      incShr.UserOrGroupId = userOrGroupId;
        
      // Set the access level.
      incShr.AccessLevel = 'Read';
        
      // Set rowCause to 'manual' for manual sharing.
      // This line can be omitted as 'manual' is the default value for sharing objects.
      incShr.RowCause = Schema.BMCServiceDesk__incident__Share.RowCause.Manual;
        
 
      // Insert the sharing record and capture the save result. 
      // The false parameter allows for partial processing if multiple records passed 
      // into the operation.
      Database.SaveResult sr = Database.insert(incShr,false);
      
 
      // Process the save results.
      if(sr.isSuccess()){
         //Indicates success
         return true;
      }
      else {
         // Get first save result error.
         Database.Error err = sr.getErrors()[0];
         
         // Check if the error is related to trival access level.
         // Access levels equal or more permissive than the object's default access level are not allowed. 
         // These sharing records are not required and thus an insert exception is acceptable. 
         if(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION  &&  
                  err.getMessage().contains('AccessLevel')){
            // Indicates success.
            return true;
         }
         else{
            //Indicates failure.
            return false;
         }
         
		}
   }	
}


Hi, currently the trigger is creating two duplicate Opportunity records instead of a single one. I have disabled all other triggers on the Opportunity object, but I still can't see to see why this would be creating two instead of one on Stage change.

Would love to see if someone could take a quick look and point me in the right direction

trigger insertNewOpp2 on Opportunity (after update) {

//create list of Opps
List<Opportunity> listOpp = new List<Opportunity>();

for(Opportunity opp : Trigger.new)
{
       
//if Opp is changed to Closed Won
   if(opp.StageName == 'Closed Won')
       {
           //Create a new opp with the following attributes
          Opportunity oppNew = new Opportunity (AccountID=opp.AccountID, StageName='Prospecting', Primary_Contact__c=opp.Primary_Contact__c, LeadSource=opp.LeadSource, ForecastCategoryName='Omitted', Name=opp.Name + 'New', CloseDate=opp.CloseDate, RecordTypeId = '012d0000000SocP'); 
           //Add to the list
          listOpp.add(oppNew);
       }
       }
     if (listOpp.size() > 0)
     insert listOpp;
}


I found several articles on building a custom login controller and custom login page for SalesForce Communities. My issue now is that I am missing the 75% code coverage mark by 2 - 3% so I am unable to deploy my new controllers to Production.

I have a CustomLogin controller with the following code:

global with sharing class CustomLoginController {
    global String username {get; set;}
    global String password {get; set;}
    global CustomLoginController () {}
    global PageReference login() {
        return Site.login(username, password, null);
    }
}

I am needing to write a unit test that will test against this code and should get me above or at least to the 75% code coverage requirement. Can someone please help me out here?

I am extremely green when it comes to programming and I have been thrust into this role at my new job.

Thanks
Hi Experts,

I know that this is not a standard functionality. However, can anyone share a sample code for sending email alert when a new attachment has been added to the custom object.

Here is the specific scenario:

When a new file or multiple files has been added for a custom object, I would like a specific set of users to be notified.

Any assistance is greatly appreciated. Thanks.
Here is my VF page for lead conversion. not able to figure out what else needs in my test class to increase the coverage. PLease help.

<apex:page standardController="Lead" extensions="XXCSRLeadConvertClass"   title="Convert Lead" id="pgConvertLead">

<apex:form id="frmConvert">

    <apex:actionFunction name="afOpportunity" action="{!doNothing}" rerender="pbsConvert" immediate="true" />

    <apex:pageBlock title="Convert Lead" mode="edit">
   
        <apex:pageBlockButtons >
            <apex:commandButton id="cmdConvert" action="{!convertLead}" value="Convert" />
            <apex:commandButton id="cmdCancel" action="{!cancel}" value="Cancel" />
        </apex:pageBlockButtons>
       
        <apex:messages ></apex:messages>
       
        <apex:pageBlockSection id="pbsConvert" title="Convert Lead" columns="1">
                       
            <apex:inputField id="ifOwnerId" value="{!ldSource.OwnerId}" />
            <apex:selectList id="soAccount" value="{!strAccountId}" label="Account Name" size="1">
                <apex:selectOptions value="{!lstCompanyInfo}" />
            </apex:selectList>
            <apex:selectList id="soContact" value="{!strContactId}" label="Contact Name" size="1">
                <apex:selectOptions value="{!lstContactInfo}" />
            </apex:selectList>
                      
        </apex:pageBlockSection>
   
    </apex:pageBlock>

</apex:form>

</apex:page>

Here is extension class

public class XXCSRLeadConvertClass {
public Lead ldSource {get;set;}
public Boolean bolCreateOpp {get;set;}
public String strAccountId {get;set;}
public String strContactId {get;set;}



//////////////////////////
// Constructors / GETers
//////////////////////////
public XXCSRLeadConvertClass(ApexPages.StandardController scMain) {



ldSource = [SELECT Id, FirstName, LastName, OwnerId, Company, Street, City, State, PostalCOde, Country, Phone, Fax,Status,ApprovalStatus__c FROM Lead WHERE Id = :scMain.getId()];
bolCreateOpp = false;

    
}

public List<SelectOption> getlstCompanyInfo() {

String strCompanyWildcard = '%' + ldSource.Company + '%';
List<Account> lstAcct = [SELECT Id, Name, Owner.Name FROM Account WHERE Name LIKE :strCompanyWildcard];

List<SelectOption> lstCompanies = new List<SelectOption>();

// Add New Account if not found
lstCompanies.add(new SelectOption('1','Create New Account: ' + ldSource.Company));

// Add found Accounts to SelectList
for(Account a : lstAcct) {
lstCompanies.add(new SelectOption(a.Id, 'Attach to Existing: ' + a.Name + ' (' + a.Owner.Name + ')'));
}

return lstCompanies;      
}

    public List<SelectOption> getlstContactInfo(){
       
       string strContactFirst = '%'+ldSource.FirstName+'%';
        string strContactLast = '%'+ldSource.LastName+'%';
        List<Contact> lsContact = [select Id ,FirstName,LastName,AccountId,Owner.Name from Contact where (FirstName like : strContactFirst and LastName like :strContactLast)
                                   and AccountId = :[select Id from Account where Name like :ldSource.Company]];
       List<SelectOption> lstContact = new List<SelectOption>();
       
        // Add New Contact if not found
lstContact.add(new SelectOption('1','Create New Contact: ' + ldSource.FirstName+''+ldSource.LastName));

// Add found Accounts to SelectList
for(Contact c : lsContact) {
lstContact.add(new SelectOption(c.Id, 'Attach to Existing: ' + c.FirstName +' '+c.LastName+ ' (' + c.Owner.Name + ')'));
    }
return lstContact;         
    }
//////////////////////////
// Action Methods
//////////////////////////

public void doNothing() {  }

public PageReference convertLead() {

//check if status = qualified and Approved
if (ldSource.Status == 'Qualified' && ldSource.ApprovalStatus__c == 'Approved'){


// Create LeadConvert object
Database.LeadConvert lc = new Database.LeadConvert();

        
lc.setLeadId(ldSource.Id);
lc.setOwnerId(ldSource.OwnerId);
if(strAccountId.length() > 1) { lc.setAccountId(strAccountId); }
if(strContactId.length() > 1) { lc.setContactId(strContactId); }
lc.setDoNotCreateOpportunity(bolCreateOpp);

// Set Opportunity Name
if(bolCreateOpp == true) { lc.setOpportunityName(ldSource.Company); }

// Set Lead Converted Status
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);



// Convert!
Database.LeadConvertResult lcr = Database.convertLead(lc);

// Mop up Opportunity
if(bolCreateOpp == true) {
Opportunity o = new Opportunity(Id=lcr.getOpportunityId());
update o;
}
// Redirect...
PageReference prResult;
if(lcr.isSuccess()) {
prResult = new PageReference('/' + lcr.getAccountId());
prResult.setRedirect(true);
return prResult;  
} else {
return null;
}
}else{
ldSource.addError('Lead cannot be converted without Lead status Qualified and Approved !'); 
      ldSource.addError('Please Go back to Lead screen to change status'); 
    }
   
return null;}
}


Here is my test code

@IsTest(seealldata=true)
private class TestXXCSRLeadConvertClass{

        static testMethod void TestXXCSRLeadConvertClass() {
      
       test.startTest();
           Boolean bolCreateOpp;
           String strAccountId;
     String strContactId;
            Lead l = new Lead();
            l.FirstName = 'CRM Testing First';
            l.LastName = 'CRM Testing Last';
            l.Company = 'CRM Testing INCtest';
            l.description = 'Test descr';
            l.city = 'test';
            l.street = 'test';
            l.state = 'CA';
            l.country = 'United States';
            l.status = 'Qualified';
            l.email = 'test@testnetgear.com';
            l.website = 'www.testcrm.com';
            l.ApprovalStatus__c='Approved';
            l.RecordTypeId='012110000004b9Q';
             
        
            insert l;
       
      Id leadId = l.Id;
  bolCreateOpp = false;
  //Create a reference to the VF page
  PageReference pageRef = Page.XXCSR_LEAD_CONVERT;
        Test.setCurrentPageReference(pageRef);

     //Create an instance of the controller extension and call the autoRun method.
  //autoRun must be called explicitly even though it is "autoRun".
  ApexPages.StandardController sc = new ApexPages.standardController(l);
  XXCSRLeadConvertClass leadconvt = new XXCSRLeadConvertClass(sc);
   String nextPage = sc.save().getUrl();
 
      
       List<SelectOption> testacct = new List<SelectOption>();
       testacct = leadconvt.getlstCompanyInfo();
        system.debug(testacct);
    
       
  List<SelectOption> testcon = new List<SelectOption>();
       testcon = leadconvt.getlstContactInfo();
        system.debug(testcon);
 
   leadconvt.doNothing();
 
             //Retrieve the converted Lead info and the opps and roles.
   l = [select Id, IsConverted, ConvertedAccountId, ConvertedContactId ,Status, ApprovalStatus__c,
    Company,OwnerId,firstname,lastname,city,country from Lead where Id = :leadId];
         
          system.assert(!l.IsConverted,'Lead Converted' ); 
          test.stopTest();
        


        }
  
        

}

Thanks
Pallavi
Hi, I have some code that creates Community Users using SIte.CreatePortalUser().  I create a contact or find an existing contact, and the User selects an Account (for a Drop Down List).  When I run Site.CreatePortalUser(user, accountId, password) usually it works, but sometimes it returns NULL.  

I have tried troubleshooting why it return NULL, but cannot find anything.  I am using forceSSL=true on the VF page, I ensure the Username (email) does not already exist in the User table, I've ensure the Account is owned by someone with a Role, I've ensure that if I find an existing contact it is not already associated to a Community User, and all required fields on the User are filled.  

Am I missing anything else?

Also, I read somewhere that if Site.CreatePortalUser() does not work, it is suppose to send an email to the Site Administrator.  I have yet to see that email.

Any suggestions would be greatly appreciated.

 
Hi, I have some code that creates Community Users using SIte.CreatePortalUser().  I create a contact or find an existing contact, and the User selects an Account (for a Drop Down List).  When I run Site.CreatePortalUser(user, accountId, password) usually it works, but sometimes it returns NULL.  

I have tried troubleshooting why it return NULL, but cannot find anything.  I am using forceSSL=true on the VF page, I ensure the Username (email) does not already exist in the User table, I've ensure the Account is owned by someone with a Role, I've ensure that if I find an existing contact it is not already associated to a Community User, and all required fields on the User are filled.  

Am I missing anything else?

Also, I read somewhere that if Site.CreatePortalUser() does not work, it is suppose to send an email to the Site Administrator.  I have yet to see that email.

Any suggestions would be greatly appreciated.

 
Hi folks,

I am getting problem with test coverage.
I am getting test coverage of 0%
Actually i don't know how to link the test class with the Apex class.

Here is my APEX Code

global class RenewalOpportunity implements Schedulable {
       global void execute(SchedulableContext SC) {
           
                RenewalOpp R= new RenewalOpp();
           
           
       }
    
    public class RenewalOpp{

RenewalOpp(){
Date d = Date.Today();


for(Account a:[select id,Name,Service_End_Date__c,Customer_Success_Manager__c,ARR__c
    from Account acc
    where
     (Id NOT IN (select AccountID from opportunity
    where AutoCreatedFlag__c = true ))])
{
    if(a.Service_End_Date__c!=NULL){
        
    // Difference between Service End date and Current date    
    Integer numberDaysDue= d.daysBetween(a.Service_End_Date__c);
    
    if(numberDaysDue<=60)  {  
        
    // Creating a new opportunity  
    Opportunity O= new Opportunity();
    o.Name=a.Name;
    o.StageName='Legal';
    o.Amount=a.ARR__c;
    o.AccountId=a.ID;
    o.CloseDate=Date.today();
    o.Customer_Success_Manager__c=a.Customer_Success_Manager__c;
    o.NextStep='Won';
    o.OwnerID='005d0000001Kt9D';
    o.AutoCreatedFlag__c = true;
        insert o;
        
       // Create a Pricebook Entry for Product
        
        List<OpportunityLineItem> oliList = new List <OpportunityLineItem>();
        Pricebook2 stdpb = [SELECT Id FROM Pricebook2 WHERE IsStandard = true]; // Select Price Book
        List<PriceBookEntry> entryList = new List<PriceBookEntry>();
        PriceBookEntry pe= new PriceBookEntry();
        pe.Pricebook2Id=stdpb.Id;
        pe.Product2Id='01tJ0000003qkr0';
        pe.UnitPrice=10;  // Standard Price
        pe.IsActive=true;
        Integer counter = [select count()  FROM PriceBookEntry where Product2.Id='01tJ0000003qkr0' And
        PriceBook2.isStandard=true AND UnitPrice=10];
        
        entryList.add(pe);
        if(counter==0){
        insert entryList;
        }
        
        List<PriceBookEntry> priceBookList = [select Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry where Product2.Id='01tJ0000003qkr0' And
        PriceBook2.isStandard=true LIMIT 1 ]; // Get the Price Book entry ID that we entered in the previous step
        OpportunityLineItem oli = new OpportunityLineItem(); // Create new Opportunity Product
        oli.OpportunityId = o.Id;                           
        oli.PricebookEntryId=priceBookList[0].Id;       // PricebookentryID of the existing pricebook entry for the specific product
        oli.UnitPrice =a.ARR__c;                       // Sales Price (or List Price)
        oli.Quantity=1;
        insert oli;
                          
              }
    }
}
 }
 
 }
    
    
    
    }



My Test Code

@isTest (seeAllData=true)  

public class RenewalTest{
    
    static testmethod void RenewalTest() {
    
    Date d = Date.Today();
    Date dueDate = date.newInstance(2015, 3, 20);
   // CSM__c csm= new CSM__c(Name='Chidanand',Customer_Success_Manager__c='Chidanand',Email='Chidanand@knstek.com');  
   // insert csm;
    Campaign c = new Campaign(Name='Chidanand');
    insert c;
    
    Product2 prod = new Product2(Name = 'Laptop X200',
            Family = 'Hardware');
        insert prod;
        
        
    
    
    Account a = new Account(Name='KNS',Service_End_Date__c=dueDate,Customer_Success_Manager__c='Jeff Tucker',ARR__c=500);
    insert a;
    Opportunity o = new Opportunity(Name='abc',AccountId=a.Id,CampaignId=c.Id,
                    StageName='Legal',Amount=5000,CloseDate=d,NextStep='Open',AutoCreatedFlag__c=false);
                    
    for(Account acc:[select id,Name,Service_End_Date__c,Customer_Success_Manager__c,ARR__c
    from Account acc
    where
     (Id NOT IN (select AccountID from opportunity
    where AutoCreatedFlag__c = true ))]){
    
    if(a.Service_End_Date__c!=NULL){
    
        Integer numberDaysDue= d.daysBetween(a.Service_End_Date__c);
        
        if(numberDaysDue<=60)  {
        
            Opportunity Op= new Opportunity();
            op.Name=a.Name;
            op.StageName='Legal';
            op.Amount=a.ARR__c;
            op.AccountId=a.ID;
            op.CloseDate=Date.today();
            op.Customer_Success_Manager__c=a.Customer_Success_Manager__c;
            op.NextStep='Won';
            op.OwnerID='005d0000001Kt9D';
            op.AutoCreatedFlag__c = true;
            insert op;
            
           // Id pricebookId = Test.getStandardPricebookId();
           List<PriceBookEntry> entryList = new List<PriceBookEntry>();
           Pricebook2 stdpb = [SELECT Id FROM Pricebook2 WHERE IsStandard = true]; // Select Price Book
           PricebookEntry standardPrice = new PricebookEntry(
           Pricebook2Id = stdpb .Id, Product2Id = prod.Id,
           UnitPrice = 10, IsActive = true);
          // entryList.add(standardPrice );
           
           
           Integer counter = [select count()  FROM PriceBookEntry where Product2.Id=:prod.Id And
        PriceBook2.isStandard=true AND UnitPrice=10];
        
        entryList.add(standardPrice );
        if(counter==0){
        insert entryList;
        }
           
           
           
          // insert entryList;
           
           String z=prod.Id;
           
           
           List<PriceBookEntry> priceBookList = [select Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry
           where (Product2.Id=:z) And (PriceBook2.isStandard=true) LIMIT 1 ]; // Get the Price Book entry ID that we entered in the previous step
        OpportunityLineItem oli = new OpportunityLineItem(); // Create new Opportunity Product
        oli.OpportunityId = op.Id;                           
        oli.PricebookEntryId=priceBookList[0].Id;       // PricebookentryID of the existing pricebook entry for the specific product
        oli.UnitPrice =10;                       // Sales Price (or List Price)
        oli.Quantity=1;
        insert oli;
           
           
        
        }
    
    }
    
    
    }
    
    
    
    
    
    
    
    
    
    
    
    }
    
    }



 
Hey guys,
I've run into a requirement for my org based on the Idea sObject. I've created a cObject called "Review" also. I need to accomplish the following flow:

User creates "Idea" entry-> Trigger copies it to "Review" and deletes it from "Idea"

Any ideas? Could I accomplish this in one trigger or do I need two?

Thanks for any and all help!

The below code works fine.  However you will notice that I do have a SOQL inside of a loop.
In an attempt to avoid issues down the line, I need to move this outisde the loop.  Any ideas on how to do this an still reference  the current b.Candidate__c(which is the contactID attached to the current Book_of_Business__c record.     Thanks in Advance

trigger BOBChange on Book_of_Business__c (before insert, before update) {
 
List<Quintile__c> Quintiles = new List<Quintile__c> ();
List<Book_of_Business__c> bob=[SELECT Id,Name,Candidate__c  from Book_of_Business__c ];
List<Contact> Contacts = new List<Contact> ();

Quintiles = [Select Quintile__c, T12_Min__c,T12_Max__c, LOS_Min__c, LOS_Max__c
             FROM      
                Quintile__c
             WHERE
                start_date__c <= today AND
                End_date__c > today];
               
              
    If (bob.size() > 0){
        for (Book_of_Business__c b : Trigger.new) {
            system.debug('BOB ------------- > ' + b.Id);
            system.debug('CandidateID ------------- > ' + b.Candidate__c);
            Contacts = [Select ID, Quintile_LOS__c, Total_years_as_a_rep__c, Producer_LOS__c,FirstName, LastName from Contact where ID =: b.Candidate__c];                 
            for (Contact c : Contacts){
             system.debug('C  ID ------------- > ' + c.Id);
                for (Quintile__c q : Quintiles) {
                 if(b.Candidate__c == c.ID &&
                  q.T12_Min__c <= b.Post_Haircut_T_12__c &&
                        q.T12_Max__c > b.Post_Haircut_T_12__c &&
                        q.LOS_Min__c <= c.Quintile_LOS__c &&
                        q.LOS_Max__c > c.Quintile_LOS__c) {
                             b.Quintile__c = q.Quintile__c;   // update BOB Quintile Field
                       System.debug(' Q.Quintile__c --------- >' + Q.Quintile__c);
                             }
                }

            }
        }
    }
}
  • September 05, 2014
  • Like
  • 0
Hi,

I have a custom object called Style__c which has a Lookup field to Product2 table called.

When I run a SOQL command inside the controller of my Visualforce template, ReturnFormStyleInfo, the name value doesn't report.

When I choose the template which refers to the controller, the data populates the email template but you can see it is missing the Product Name:

template output, doesn't include product2 lookup Style name field

Running a SOQL query directly, you can see that the name should be available for output via the component.

direct query on Style__c records aligned to case, showing that the name field is being pulled

Here is the getStyleInfo method from the class ReturnFormStyleInfo
public string getStyleInfo()
{
        string ret = '\nStyle\t\tPrice\tQty\n';
        for(Style__c s : [SELECT Style__r.Name, Price__c,Quantity__c FROM Style__c WHERE Case__r.CaseNumber=:thecase])
        {
            ret += s.Style__r.Name + '\t$' + s.Price__c + '\t' + s.Quantity__c + '\n';
        }
        return ret;
}

Which is referenced in this component.
<apex:component access="global" controller="ReturnFormStyleInfo">
<apex:attribute name="casenum" description="This is the CaseNumber of the case." type="string" assignTo="{!thecase}" />
{!StyleInfo}
</apex:component>
Hi All,

This trigger has been running just fine with no no errors, then yesterday starting throwing back "UpdateLeadOwner: System.LimitException: Too many SOQL queries: 101"

Here's the code:

trigger UpdateLeadOwner on Lead (before insert,before update) {
    for (Lead leadInLoop : Trigger.new) {
   
if (leadInLoop.LeadSource != 'Contact Us' && leadInLoop.LeadSource != 'Reprint') {
    // Retrieve owner from Account record based on email domain name
    list <Account> acct = [Select OwnerId from Account WHERE Domain__c = :leadInLoop.Domain__c AND Owner.UserRoleId != '00E50000000t0Bf' Limit 2];
        if (acct.size() == 1) {

    System.debug('account owner id is: ' + acct[0].OwnerId);
    leadInLoop.OwnerId=acct[0].OwnerId;
        }
    }
}

Any idea how to track down what changed so I can fix?  Thanks!
Hello

I have written a trigger but I am now trying to unit test it.  However I am getting the following error message with my apex class.  Can anyone see what I have done wrong?

User-added image

Thanks

Sonya
I have a page that on load pulls from an outside webservice.  This webservice may have issue and therefore won't display data.  I display an error to the user but I want to create a case that is assigned to a group of people in the compnay so it can be worked on.  I am unable to create a case when the page is being loaded due to DML restrictions. 

My Idea: create a checkbox and have it check so that when the error is caught it is cheked and initiates the action method.  This doesn't seem to work as I had planned.

Is anyone doing this and how?
Hi All, 

I wrote a custom controller and now trying to increase the code coverage. It is stuck at 39%. I'm not sure what am I missing? 

public String SelectPrimaryAccount { get; set; }
    public boolean SameAsCaller { get; set; }

 
    public List<SelectOption> getPrimaryAccount() {
        List<SelectOption> primaryAccount = new List<SelectOption>();
        primaryAccount.add(new SelectOption('','-None-'));
        primaryAccount.add(new SelectOption('Caller Account','Caller Account'));
        primaryAccount.add(new SelectOption('Project Site Contact', 'Project Site Contact'));
        primaryAccount.add(new SelectOption('Insurance', 'Insurance'));
 
        return primaryAccount;
    }

    public PageReference Save() {
    
        //Job Account and contact   
            Id acctid = Job.Account__c;
            id conid;
            
            job_Contact__c c1; job_Account__c a1;
            for(Contact con : [select id, accountid from Contact where id =:Job.Account__c]){
                c1 = new job_Contact__c(contact__c = con.id);
                a1 = new Job_Account__c(account__c = con.accountid);
                conid = con.id;
                Job.Account__c = con.accountid;
                
                if(SelectPrimaryAccount == 'Caller Account'){
                            job.account__c = con.accountid;
                }
            }
            
            job_Contact__c c2; job_Account__c a2; Contact con2;
            if(SameAsCaller != true && job.Project_Site_Contact_Name__c != null){
            
                con2 = [select id, accountid from Contact where id =:job.Project_Site_Contact_Name__c limit 1];
                job.Project_Site_Contact_Account__c = con2.accountid;
                
                c2 = new job_Contact__c(contact__c = con2.id);
                a2 = new Job_Account__c(account__c = con2.accountid);
                
                if(SelectPrimaryAccount == 'Project Site Contact'){
                        job.contact__c = job.Project_Site_Contact_Name__c;
                        job.account__c = con2.accountid;
                }
            }
            else {
                job.Project_Site_Contact_Name__c = conid;
                job.Project_Site_Contact_Account__c = job.account__c;
                //job.account__c = conid.accountid;
            }
            
            job_Contact__c c3; job_Account__c a3; Contact con3;
            if(job.Insurance_Adjuster_Broker__c != null){
                con3 = [select id, accountid from Contact where id =:job.Insurance_Adjuster_Broker__c limit 1];
                c3 = new job_Contact__c(contact__c = con3.id);
                a3 = new Job_Account__c(account__c = con3.accountid);
                   
                if(SelectPrimaryAccount == 'Insurance'){
                        job.contact__c = job.Insurance_Adjuster_Broker__c;
                        job.account__c = con3.accountid;
                }
            }
            
            if(acctid != null){
                a3 = new Job_Account__c(account__c = acctid);
                if(SelectPrimaryAccount == 'Insurance'){
                    job.account__c = job.account__c;
                    job.contact__c = null;}
            
            }
            
        
        insert job; 
        
           if(c1!=null){
            c1.job__c = job.id;
            a1.job__c = job.id;
            jcon.add(c1);jacct.add(a1);}
            
            if(c2!=null){
                c2.job__c = job.id;
                a2.job__c = job.id;
                jcon.add(c2); jacct.add(a2);
            }
        
            if(acctid!=null){
                a3.job__c = job.id;
                jacct.add(a3);
                if(c3!=null){
                    c3.job__c = job.id;
                    jcon.add(c3);
                }
            }
          
            insert jCon;
            insert jAcct;

It's getting coverage on the queries and the confitional statements. But that's about it. 

Here's my test class:

@isTest (seealldata = true)
                    
public class CreateNewJobInquiry_Test {

    public static testMethod void TestCreateNewJobInquiry () {
        //PageReference pageRef = page.NewRecord;
        //Test.setCurrentPage(pageRef);
      
        Contact contact = new Contact();
        Account account = new account(billingStreet = contact.mailingstreet, billingcity = contact.mailingCity, billingstate = contact.mailingcity, billingpostalcode = contact.mailingpostalcode, phone = contact.phone);
        account.name = 'CIG';
        insert account;
        
        Contact.contact_type__c = 'Adjustor';
        contact.firstname = 'semira';
        contact.Lastname = 'roy';
        contact.accountid = account.id;
        insert contact;
    
        Contact contact2 = new Contact();
        Contact2.contact_type__c = 'Adjustor';
        contact2.Lastname = 'noname';
        contact2.firstname = 'noname';
        contact2.accountid = account.id;
        insert contact2;
        
        
    Job__c job = new Job__c(account__c = account.id, Job_Name__c = 'test', Project_Site_Address__c = contact.mailingstreet, Project_Site_City__c = 'Los Angeles', Project_Site_state__c = 'CA', Project_Site_zipcode__c ='90027', County__c = 'LA', City_of_LA__c = 'Yes');
    job.contact__c = contact.id;
    job.Project_Site_Contact_Name__c = contact2.id;
    job.Insurance_Adjuster_Broker__c = contact.id;
    
    
    ApexPages.currentPage().getParameters().put('qp', job.id);
    CreateNewJobInquiry testObj2 = new CreateNewJobInquiry();
    testObj2.Sameascaller = false;
    testObj2.SelectPrimaryAccount = 'caller account';
    
        testObj2.save();
    }
}


I have a custom object Pint, I want it create new pint again automatically once a pint's status is Closed.  I got an error message while creating a trigger, please help.

Error Error: Compile Error: Duplicate variable: p (attempt to re-create the variable with type: Pint__c) at line 4 column 32

trigger CreatePin on Pint__c (after update) {
       for (Pint__c p : Trigger.new) {
               if (p.Status == 'Closed') {
                       Pint__c p = new Pint__c();
                       p.Account__c = c.AccountId;                  
               insert p;
        }
        }
        }
Hello-

Yesterday, I installed an apex trigger titled 'Change Lead Status' with the intent that anytime a Lead has a completed activity logged, it changes the Lead Status to 'Working - Contact Made'. While that functionality works just fine, my users have noticed an error message whenever they try and log an activity (manually) on an Account without a Contact included on the Name field in the Task page layout. The error will not let them log the Task without a Contact associated with it. I don't understand what is happening, and I'm confused as to why a Lead based apex trigger is affecting Accounts/Contacts.

I have two questions A) is there any way to modify this code so that this data is not required to log a Task manually? The apex trigger works fine other than this error. B) If not, how would I go about removing this apex trigger? I looked at some documentation around this, and they direct me to the sandbox to remove the trigger, but the trigger does not appear in my sandbox. 

Here is the code: 

trigger changeLeadStatus on Task (before insert, before update) {
    String desiredNewLeadStatus = 'Working - Contacted';

    List<Id> leadIds=new List<Id>();
    for(Task t:trigger.new){
        if(t.Status=='Completed'){
            if(String.valueOf(t.whoId).startsWith('00Q')==TRUE){//check if the task is associated with a lead
                leadIds.add(t.whoId);
            }//if 2
        }//if 1
    }//for
    List<Lead> leadsToUpdate=[SELECT Id, Status FROM Lead WHERE Id IN :leadIds AND IsConverted=FALSE];
    For (Lead l:leadsToUpdate){
        l.Status=desiredNewLeadStatus;
    }//for
   
    try{
        update leadsToUpdate;
    }catch(DMLException e){
        system.debug('Leads were not all properly updated.  Error: '+e);
    }
}//trigger

Any help would be greatly appreciated, I have received several complaints over the past day. 

Thank you,

Ryan

The code is as follows: 
Hi

I am trying to write a trigger that will update the lookup field called Most_recent_nomination_tenancy__c field on a custom object called Referral__c when a new Nomination/Tenancy is created.  However at present rather than updating the field with the name of the new Nomination/Tenancy it is turning the field blank.   Does anyone know why this trigger is turning the field blank and not updating it?

trigger UpdateReferralWithNewNomTen on Nomination_Tenancy__c (before insert, before update) {

  for(Nomination_Tenancy__c newRecord : Trigger.new)  {        
      Referral__c Referral = [Select Id, Most_recent_nomination_tenancy__c from Referral__c WHERE Id = :newRecord.Referral__c ];
        Referral.Most_recent_nomination_tenancy__c = newRecord.Name;
        update Referral;               
    }

}

Many Thanks,

Mike
Hi, 

I have a problem that I'm finding hard to figure out. Any help on the issue would be most welcome. 

I have a custom object called Bonus, this has a lookup relationship with another custom object called Payments. 

Using a VF page and standard controller with extension, I have a button on the Bonus page layout that will create 4 payment records for a single Bonus record when pressed. 

This all works fine, however if I refresh the page immidiately after creating the Payment records, I get 4 more. If I close the page, open it again and then refresh I do not get any duplicates. 

Has anyone ever experienced this before? ...or have any suggestions for how I can troubleshoot?

Many thanks!
This is my third time trying to post this question... Third time's the charm?

Hello all,

I'm having an issue trying to display an image in a PDF rendered Visualforce Page. The image's URL is stored in a field on the object controlling the page.

I've tried using <apex:image...> and <img src...>. Using the actual URL works just fine and displays the image. Removing the renderAs="pdf" displays all images correctly.

Any help would be much appreciated.

Thank you!

Code snippet:

<apex:page standardController="Order__c" showheader="false" standardStylesheets="true" renderAs="PDF">

<apex:pageBlock >
<apex:image value="ImageStoredAsDocument" width="98%"/> <!-- this displays fine -->

        <img src="{!Order__c.CustomField_URL__c}" /> <!-- this does not display when rendered as PDF -->
        <img src="ActualURL" /> <!-- this displays fine -->
</apex:pageBlock>


I want to add a second "Log a Call "button to the Account/Contact/Oppty pages that will have a different default subject than the out of the box "Call".
I want the button to read "Log a Demo" and the default subject value to be "Demo".
Can this be done?

Thanks, kb

Hi Force devs

Can we lock the record order from the apex code. not from approval process.

Rgrds
SR