• Balaji Bondar
  • SMARTIE
  • 1226 Points
  • Member since 2012
  • Sales force Developer

  • Chatter
    Feed
  • 39
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 2
    Questions
  • 284
    Replies
Hi,

I have the following class where i am trying to write test class for it which covers only 35% , i am wondering how to cover the following lines , Kindly help me pls

 
MY APEX CLASS :


public class IarCloneAttachment implements Queueable {
	public Id attachmentId;
	public Id newParentId;
	public Set<String> oldIdList;
	public Map<String,String> oldParentId_newParentId_Map;
	public IarCloneAttachment() {
		
	}

	public void execute(QueueableContext context) {
		cloneAttachments();
	}

	public void cloneAttachments() {
        SkipingHelper.skipTriggerIARAttachmentTrigger  = true;
        SkipingHelper.SkippAllTriggersFromAttachment();
        for(Attachment attch :[SELECT Id,ParentId,BodyLength  FROM Attachment WHERE ParentId in:oldIdList]) {
            System.debug('Attachment xxx Heap Size:'+Limits.getHeapSize() + ' Limit:'+Limits.getLimitHeapSize());
        	System.debug('Attachment xxx Id:' + attch.Id + ' size:' + attch.BodyLength);
        	//Note: The following SOQL is inside a for loop. This is by design. Retrieving all the attachments in one soql will throw the heap size limit error.
			List<Attachment> attachmentList = [SELECT Body,ParentId,CreatedDate,ContentType,OwnerId,CreatedById,LastModifiedDate,IsPrivate,Description,Name,LastModifiedById FROM Attachment WHERE Id=:attch.Id];
			if (attachmentList.size()>0) {
				Attachment sAttachment = attachmentList[0].clone(false);
				sAttachment.ParentId = oldParentId_newParentId_Map.get(attachmentList[0].ParentId);
				sAttachment.ownerId = attachmentList[0].OwnerId;
				insert sAttachment;
				sAttachment.Body = null;
            }
        }
	}
}
MY TEST CLASS :

@isTest
public class IarCloneAttachment_Test {  
    static testmethod void IarCloneAttachment_TestMethod()
    {
        User Uu3 = IARTestUtilities.createStandardUser('WrkTs');
        System.RunAs(Uu3) {
            IARTestUtilities.createCustomSettingsForPRMSFDCVDMSGSAM();            
            Account acc = IARTestUtilities.createTestAccount();  
            system.debug('acc:'+acc); 
            
            Opportunity op = IARTestUtilities.createTestOpportunity(acc.id);                     
            system.debug('op:'+op);
            
            Test.startTest();
            IAR_Main__c IAR = IARTestUtilities.createNewTestIARwithSHForms(acc.Id,op.id,'EMS');        
            system.debug('IAR:'+IAR);
            
            
            Blob b = Blob.valueOf('Test Data');
            Attachment attachment = new Attachment();
            attachment.ParentId = acc.Id;
            attachment.Name = 'TestAttachmentforParent.xls';
            attachment.Body = b;
            insert(attachment);
            List<Attachment> attachmentList = new List<Attachment>();
            attachmentList.add(attachment);
            Set<String> oldIdList = new set<String>();
            oldIdList.add('attachment');

            Test.stopTest();  
            IarCloneAttachment iarc = new IarCloneAttachment();
            iarc.cloneAttachments();
            
        }
    }
}
LINES NOT GETTING COVERED:


public void execute(QueueableContext context) {
		cloneAttachments();
	}






**********************************************************************

List<Attachment> attachmentList = [SELECT Body,ParentId,CreatedDate,ContentType,OwnerId,CreatedById,LastModifiedDate,IsPrivate,Description,Name,LastModifiedById FROM Attachment WHERE Id=:attch.Id];
			if (attachmentList.size()>0) {
				Attachment sAttachment = attachmentList[0].clone(false);
				sAttachment.ParentId = oldParentId_newParentId_Map.get(attachmentList[0].ParentId);
				sAttachment.ownerId = attachmentList[0].OwnerId;
				insert sAttachment;
				sAttachment.Body = null;

Kindly help me how to cover those lines pls

Thanks in Advance

 
Hello, is there a way to refresh our current developer ORG back to a clean, new-like copy of a sandbox?  Thanks!, Joseph
When you are sending a email from a lead, is there any way to validate or control who the sender email is programmatically?

Thank you,
Steve
I have a trigger which uses mass email message to send to a list of leads.  It works great when leadids is populated with 5 or 6 IDs but if it is populatd with 7 or more i get the error message stating MASS_MAIL_LIMIT_EXCEEDED, Failed to send email: []

It is my understanding that we can use mass email to send to a list of up to 250 leads/contacts.  Any thoughts on why i am being limited to 6?  Below is a snippet from my code.

Also, when the emails are sent it shows up under Activity History but it does not show up under HTML Email Status so i cannot see if the email was opened by the recipient.
 
if (LeadIds != null && !LeadIds.isEmpty())
            {
                	Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();

                	string etidasstring = a.ezwf__Email_Template_ID__c;
                     
                    mail.setSenderDisplayName(UserInfo.getName());
                    mail.setReplyTo(UserInfo.getUserEmail()); 
                    
                    mail.setTargetObjectIds(LeadIds); 
                    mail.setTemplateId(etidasstring);
                    mail.setSaveAsActivity(true); 
                     
                    Messaging.sendEmail(new Messaging.MassEmailMessage[] {mail});
            }

 
Hi,

I have a code which is causing issues while deploying . Pb is it is fine in UAT and not in Production,
TestOppLineItemControllerExtension testChangeLOB System.LimitException: Too many SOQL queries: 101 
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testChangeLOB: line 231, column 1
TestOppLineItemControllerExtension testInsertOLI System.LimitException: Too many SOQL queries: 101 
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testInsertOLI: line 57, column 1
TestOppLineItemControllerExtension testPageMessages System.LimitException: Too many SOQL queries: 101 
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testPageMessages: line 169, column 1
TestOppLineItemControllerExtension testcancelMethod System.LimitException: Too many SOQL queries: 101 
Stack Trace: Class.OppLineItemControllerExtension.<init>: line 131, column 1 Class.TestOppLineItemControllerExtension.testcancelMethod: line 202, column 1
 
static testMethod void testChangeLOB() 
    {
        //Create test data
        Opportunity opp = new opportunity();
        opp = createTestData();
        // Set the current page to OpportunityLineItemEdit VF Page  
        PageReference servicesPage = new PageReference('apex/OpportunityLineItemEdit?opp_id='+opp.id);
        Test.setCurrentPage(servicesPage);
        //Create an object of the OppLineItemControllerExtension class
        OppLineItemControllerExtension oliCE = new OppLineItemControllerExtension ();
                        
        //The values of service Line and sub-service are not null
        system.assertnotEquals(null, oliCE.selFamily);
        system.assertEquals(null, oliCE.selService);
        
        //re-populate the value of LOB and invoke the changeLOB method
    
        oliCE.changeLOB();
        //Retrieve the values of service line and sub-service
      
        // The service line will be none because the LOB has changed
        system.assertEquals('-None-', oliCE.selFamily);
         // The sub-service  will be null because the service line is NONE
        system.assertEquals(null, oliCE.selService);
                     
    }
    
     
}
 
static testMethod void testcancelMethod() 
    {
         //Create test data
        Opportunity opp = new opportunity();
        opp = createTestData();
        // Set the current page to OpportunityLineItemEdit VF Page  
        PageReference servicesPage = new PageReference('apex/OpportunityLineItemEdit?opp_id='+opp.id);
        Test.setCurrentPage(servicesPage);
        //Create an object of the OppLineItemControllerExtension class
        OppLineItemControllerExtension oliCE = new OppLineItemControllerExtension ();
        //Invoke the cancel method and verify the url of the page it navigates to
        String nextpage = oliCE.cancel().getUrl();
        PageReference p = new ApexPages.Standardcontroller (opp).view ();
        
        system.assertequals(p.getUrl(),nextpage);
       
    }
 
This is the class code part where the stack is pointing 

public OppLineItemControllerExtension() 
  {
       selLOB = '-None-'; 
       selFamily = '-None-';
       
       if ((ApexPages.currentPage().getParameters().get('opp_id') != null)&&(ApexPages.currentPage().getParameters().get('opp_id').length() > 0))
       {
         System.debug ('*****Opp in URL: '+ ApexPages.currentPage().getParameters().get('opp_id').length());
         this.oli = new OpportunityLineItem();
         oli.OpportunityId = ApexPages.currentPage().getParameters().get('opp_id');
       
           opp = [select Name, Account.name, CurrencyIsoCode,IsClosed ,ServiceEdit__c from Opportunity where id=:oli.OpportunityId];
       accountName = opp.Account.Name;    
       oppName = opp.Name;
       oppCurrencyIsoCode = opp.CurrencyIsoCode;
       
       
    for (pricebookentry pbe : [SELECT product2.recordtype.name,  product2.family, product2.Sub_Service__c, product2Id from pricebookentry where pricebook2.name like 'OPP%' and isActive = TRUE and pricebookentry.CurrencyIsoCode =: oppCurrencyIsoCode order by product2.recordtype.name, product2.family, product2.Sub_Service__c])
    {
      if (LOBName != pbe.product2.recordtype.name)
      {
        LOBName = pbe.product2.recordtype.name;
        System.debug('LOB NAME::::'+LOBName);
        LOBServicesMap.put (LOBName, new Map <String, Map <ID, String>> ());
      }
      
      if (Family != pbe.product2.family)
      {
        Family = pbe.product2.family;
        LOBServicesMap.get (LOBName).put (Family, new Map <ID, String> ());
      }
      
      LOBServicesMap.get (LOBName).get (Family).put (pbe.id, pbe.product2.Sub_Service__c);
        
    }
    displayOLIDetails = true;
   }
   //PU:03/04/2011 - When the Opportunity Id is null the below error message has to be displayed.
      
   else
   {
       displayOLIDetails = false;
       ApexPages.addMessage(new ApexPages.Message (ApexPages.Severity.Error, Label.oppLI_ErrMsgOppRequired));
                
   }
   
   wrappers=new List<OcrWrapper>();
   for (Integer idx=0; idx<1; idx++)
   {
           List<selectOption> opt = LOBNames();
           wrappers.add(new OcrWrapper(nextIdent+1,opt));
   }
 }

Thanks 
Akhil
  • September 04, 2015
  • Like
  • 0
i want to implement a pagination in a pageblocktable. and i have a list 'product' as table value. how can i impemnt it. i have tried using standardsetcontroller class but when using Apexpages.standardsetcontroller(product), it gives an error. as argument1 can not be null .
need help anyone please. 

Scenario:
In this example (not a batch process) I have a list of 100 contact records:  List <Contact> contactsToUpdate = new List <Contact> ();
// contactsToUpdate.size() = 100

I loop through these using a for loop,  I update a few records. Then I upsert them using DML.  Result:  a few records have been updated and a few are new & are inserted.  
if (contactsToUpdate.size() > 0) 
        {
            try 
            {
                upsert contactsToUpdate;
            } 
            catch(DmlException e) 
            {
                system.debug('The following exception has occurred: ' + e.getMessage());
            } 
        }

Here are my questions:

1)  If only 1 of those 100 records cannot be inserted do to something like a validation rule failing, will the entire insert fail or just the one record?
2)  Is there a way in the Catch that I could email myself only the records that fail and the reason - can I use the database.upsert in a try catch?
 

Thank you!
Brandon

how to get the field values using controllers only without getter and setter methods in salesforce?
How can I render and unrender the commandbutton "button1" based on my action support field being set to ToggleSelect='Personal Auto' ? Thanks. 

<apex:page standardController="Audit__c" showHeader="true">
<apex:variable var="audit" value="{!Audit__c}" />
<apex:variable var="ToggleSelect" value="{!audit.Audit_Sample_Type__c}" />
<apex:form id="form1">
<apex:pageBlock id="block1" title="Audit Sample Selection">
<apex:pageBlockButtons location="top">
<apex:commandButton value="Edit" action="{!Edit}"/>
<apex:commandButton value="Save" action="{!Save}"/>
<apex:commandButton value="Cancel" action="{!Cancel}"/> 
<apex:commandButton action="{!urlfor("/apex/PROD_Audit_Auto_PolicySample", null, [AccId=Audit__c.Id])}" value="New Sample" style="background:lightblue;color:blue" id="button1" rendered="{!audit.Audit_Sample_Type__c='Personal Auto'}"/>
</apex:pageBlockButtons>

<apex:PageblockSection columns="1" > 
<apex:PageBlockSectionItem > 
<apex:outputLabel value="Audit Type"/>
<apex:actionRegion >
<apex:inputField value="{!Audit__c.Audit_Sample_Type__c}">
<apex:actionSupport event="onchange" reRender="ajaxrequest, button1" /> 
</apex:inputField>
</apex:actionRegion>
</apex:PageBlockSectionItem>
</apex:PageblockSection>

<apex:outputPanel styleClass="sample" id="ajaxrequest">
<apex:pageBlockSection columns="1" id="section1" showHeader="false" title="General Auto Audit Information Section" rendered="{!ToggleSelect='Personal Auto'}">
<apex:inputField value="{!audit.Personal_Auto_Product__c}" />
</apex:pageBlockSection>

</apex:outputPanel> 
</apex:pageBlock>
</apex:form>
</apex:page>
Hello Y'all

I am new to APEX and Salesforce in general; but I've been tasked with creating a trigger, like what is described in the title. I've been working on this for a couple days now and can't seem to get this to work. Any and all advice would be appreciated.

I am trying to have the field: Data_Conversion_Task_List_If_Needed__c on Object: New_Office_Setup__c update itself to match the field: Status__c on Object: Analytics__c whenever Analytics__c is updated.

What I have so far, is copied from old post that I have subbed the objects and field from my salesforce into:
===========================================================================

trigger UpdateTriggerTest on Analytics__c (before insert, before update) 
{
  //get a list of all the object 2 ID's contained in the records
  //to be updated.
  List<New_Office_Setup__c> NOSIDs = new list<New_Office_Setup__c>();
  //List<List<Analytics__c>> AnaIDs = new List<list<Analytics__c>> ([select id, Open_Projects_Analytics__c from Analytics__c]);
  for (Analytics__c Ana: trigger.new)  
      
  {
   NOSIDs.add(Ana.Open_Projects_Analytics__c );
  }
    
  //now get a list of all the records for object 2 that contain the
  //above IDs
  List <New_Office_Setup__c> NOS = new List <New_Office_Setup__c> ([select id, Data_Conversion_Task_List_If_Needed__c from New_Office_Setup__c where id in: NOSIDs]);

  //now loop again for all the records being updated and then for each
  //one loop through all the object 2 records retrieved above.
  for (Analytics__c Ana: trigger.new){
  
    //we do this for loop differently so that it has an inherent check
    //to ensure that our query above returned some records
    for (integer i = 0; i < NOS.size(); i++){

      //now we make sure the record IDs match
      if (Ana.Open_Projects_Analytics__c == NOS[i].id){

        NOS[i].Data_Conversion_Task_List_If_Needed__c = Ana.Status__c;
      }
    }
  }
  //update all the object 2 records
  update NOS;
}
======================================================================

I would also appreciate any advice on how to construct the test class for this. The test class seems to be the hardest code for me to write so far. At least for the handful of codes I've written before this.

Best,
Sam. S.
Hi All,

We are working on requirement where we need to automate the creation of Customer community users. We are taking care of creating a Account, Contact and then creating the User record. The issue that
  • We are facing is that the user can belong to any country. We want to default that country's locale and timezone etc. 
  • How do we handle the duplicate nick name and alias while creating new users in the code?
We want least user interference here. Hence we are automating the entire process. Any suggestions on this is highly appreciated. 

Thanks,
Raghu
trigger PropOwned on Contact (after update) {
for (Contact c : Trigger.new){
McLabs2__Ownership__c ownNew= new McLabs2__Ownership__c();
Contact oldContact = Trigger.oldMap.get(c.id);
if (c.One_Prop_Owned__c != oldContact.One_Prop_Owned__c && c.One_Prop_Owned__c != null){
ownNew.McLabs2__Contact__c = c.id;
ownNew.McLabs2__Property__c = c.One_Prop_Owned__c;
insert ownNew;
}
}
}

This is the trigger, I need to move it into production. I was able to write a test class that created a new ownership, but then I realized that was not correct.  I have tried a million different things and none have worked.  This was my original, that obviously didn't work I realize it is because I need to create a contact record and then update it, just don't know how.

Thank you very much in advance.

@isTest
public class TestOwnership {
    static testMethod void createOwnership() {
     McLabs2__Ownership__c ownNew= new McLabs2__Ownership__c();
     ownNew.McLabs2__Contact__c = 'Michael Webb';
     ownNew.McLabs2__Property__c = '131 West 33rd Street';
     insert ownNew;
     }
    }

Thanks again!
So I am writing a test class that is covering the below trigger but it only works if it is created from the New Opportunity button when it is clicked. I am not sure if it is possible but in my test class if I create a contact can I call the button action and check the results from the opportunity is created and inserted? I have not overrode the button or anything, I can't find any information on this. 

trigger fillLeadSource on Opportunity (before update) {
   Set<Id> oppsToFill = new Set<Id>();
    for(Opportunity o : trigger.new){
        if(o.LeadSource == null) {
            oppsToFill.add(o.Id);
        }
    }

    // Now we'll select all possible contacts wasting only 1 query.
    if(!oppsToFill.isEmpty()){
        List<OpportunityContactRole> roles = [SELECT OpportunityId, Contact.Name, Contact.LeadSource, Contact.Lead_Source_Name__c
            FROM OpportunityContactRole
            WHERE isPrimary = true AND Contact.LeadSource != null AND OpportunityId IN :oppsToFill];

        if(!roles.isEmpty()){
            for(OpportunityContactRole ocr : roles){
                Opportunity oppToBeFilled = trigger.newMap.get(ocr.OpportunityId);
                System.debug('Changing lead source on ' + oppToBeFilled.Name + ' from ' + oppToBeFilled.LeadSource + ' to ' + ocr.Contact.LeadSource + ' (thx to ' + ocr.Contact.Name + ' being the Primary Contact).');
                oppToBeFilled.LeadSource = ocr.Contact.LeadSource;
              }
        }
    }
}
hello everyone;

In the code below I am trying to put a contract owner in the opportunity team record and i want to grand him read/write permission in that record 
My issue is that when i try to save that record, I get an error message saying 

Error: Compile Error: Field is not writeable: OpportunityTeamMember.OpportunityAccessLevel at line 27 column 1


can you please help, many thanks 

 
trigger OpportunityBeforeUpdate1 on Opportunity (before update) {
string oppName;
opportunity oppId;
SVMXC__Service_Contract__c smc= new SVMXC__Service_Contract__c();
for (opportunity opp: trigger.new)
oppName=opp.name;
oppId=[select Id, name from opportunity where name=:oppname limit 1];
integer res=oppName.indexof(' - ');
String ConName=oppName.left(res);
smc=[select name, OwnerId from SVMXC__Service_Contract__c where name=:ConName limit 1];
OpportunityTeamMember oppt = new OpportunityTeamMember();
oppt.OpportunityId=oppId.Id;
oppt.userid=smc.ownerid;
oppt.OpportunityAccessLevel='edit';
oppt.TeamMemberRole='Service Sales Contributor';

insert oppt;
}


 
Hi,

I have a situation where I have a record type that wants to include an amend type of functionality.  Basically, a record will be created and completed.  Sometimes, a user will have to amend the information to the record, but the user wants to leave the old record alone and just reference back to the old record with a Lookup field.  The functionality I am trying to create is a trigger that would update a field on the parent record to 'Amended' when the child record becomes 'Activated.'

I have attempted to create a trigger to accomplish this, but when I test it, nothing happens.  Can someone help me figure out where I've gone wrong?  

Object: Apttus__APTS_Agreement__c
Field to update on parent record: Apttus__Status_Category__c
Field on child record to look at: Apttus__Status__c

So when Apttus__Status__c = 'Activated' on the child record, I want Apttus__Status_Category__c = 'Amended' on the parent record.
 
trigger AR_Variance_Status_Update on Apttus__APTS_Agreement__c (before insert, before update) {
 
    Map<ID, Apttus__APTS_Agreement__c> parentAgmts = new Map<ID, Apttus__APTS_Agreement__c>();
    List<Id> listIds = new List<Id>();
    
    for (Apttus__APTS_Agreement__c childObj : Trigger.new) {
    	listIds.add(childObj.Variance_For__c);
    }
    
    parentAgmts = new Map<Id, Apttus__APTS_Agreement__c>([SELECT id, Name FROM Apttus__APTS_Agreement__c WHERE ID IN :listIds]);   
    
    for (Apttus__APTS_Agreement__c agmt :trigger.new)
    {
        Apttus__APTS_Agreement__c myParentAgmt = parentAgmts.get(agmt.Variance_For__c);
        
        if(agmt.Apttus__Status__c == 'Activated' && agmt.Variance_For__c <> null)  {
            myParentAgmt.Apttus__Status_Category__c = 'Amended';
        }
    }
}

Thanks!
Matt
I'm trying to pull a single value from a row in a table contained within a wrapper class so I can just execute a method based on that user selected item but I'm having an issue.  My VF markup for the table is as follows:
<apex:pageBlockTable value="{!pendList}" style="border:1px solid black;" var="p" rendered="{!NOT(ISNULL(pendList))}">
          		<apex:column style="border:1px solid black; text-align:center;  font-weight:bold; color:blue;" value="{!p.pIssue.Name}" headerValue="Claim Number"/>
          		<apex:column style="border:1px solid black; text-align:center; width:105px"  value="{!p.pIssue.MAG_Claim__r.Contract_Holder__r.Policy_Type__c}" headerValue="Policy Type"/>
          		<apex:column style="border:1px solid black; text-align:center; width:105px"  value="{!p.pIssue.CreatedDate}" headerValue="Date Opened"/>
          		<apex:column style="border:1px solid black; text-align:center; width:105px"  value="{!p.pIssue.RecordType.Name}" headerValue="Claim Type"/>
          		<apex:column style="border:1px solid black; text-align:center; width:105px"  value="{!p.pIssue.Damage_Type__c}" headerValue="Type of Loss"/>
          		<apex:column style="border:1px solid black; text-align:center; width:105px;  font-weight:bold; color:blue;" value="{!p.pIssue.Component_Status__c}" id="note" headerValue="Status"/>
          		<apex:column headerValue="Check/Add Attachments" style="border:1px solid black; text-align:center;" width="50px">
          			<apex:param assignTo="{!issID}" value="{!p.pIssue.ID}"/>
          			<apex:commandLink style="align:center" action="{!checkAttach}" rendered="{!p.pIssue.Component_Status__c == 'Pending'}">Check/Add</apex:commandLink>
          		</apex:column>
          	</apex:pageBlockTable>
And the method checkAttach(), which I'm trying to utilize on whichever row the user clicks the command link on looks like this so far:
public pageReference checkAttach(){
		    system.debug(issID);
		    fileList = [SELECT Name, ContentType, Description FROM Attachment WHERE Parent.ID =: issID];
    		if((!fileList.isEmpty())){
            	FOUND = true;
                this.message = null;
                return page.CM_WebClaimFileCheck;
                }
    		else{
            	this.message = 'No files attached.';
                return page.CM_WebClaimFileCheck;
                }	
              	return null;
    			}
I was hoping the <apex:param assignTo="{!issID}" value="{!p.pIssue.ID}"/> would take care of assiging that particular table item's ID to the ID variable I created, but it doesn't seem to assign the value as my debug statement claims it remains null.

Any help would be appreciated.

 
Hi,

I am trying to write a String SOQL query in a Batch class. I need to query records with a particular condition as written below:

 String Soql = 'SELECT id,StageName FROM Opportunity Where StageName in (\'Quoted\',\'Bound\',\'Working\')' ;

Here StageName is a Picklist field . So I need to query record with above those three picklist values, but this query is not working. Please let me know how to construct a String with this "Where" condition.

Thanks


 
  • November 04, 2014
  • Like
  • 0
Not able to query the standard field 'subtotal' from quoteLineItem. 
Query: select subtotal from quotelineitem where id = 'xxxxx'
Error:No such column 'subtotal' on entity 'QuoteLineItem'. If you are attempting to use a custom field, be sure to append the '__c'

Can anyone help me on this?
  • November 03, 2014
  • Like
  • 0

Not getting the desired code coverage, need a trick to play around with this
I have a VF page that is providing a custom button on Standard Opportunity Page layout, and 
a custom controller that handles the click event (a method)
Here is the VF page and part of controller code

VF page
====== 
<apex:page showHeader="false" standardController="Opportunity" extensions="ctrlMultiClone" action="{!createClone}" />

Controller
======

public PageReference createClone(){          
        oppid = ApexPages.currentPage().getParameters().get('id');

        if(oppid != null)
        {
            List<Amenity_Billing__c> cons = new List<Amenity_Billing__c>();
            Opportunity opp = [SELECT ID, StageName, Profit_Center__c,CloseDate,Name,Notice_Status__c,AccountId, LeadSource, Rate_Type__c  FROM Opportunity WHERE Id = : oppid];
            
            Opportunity oppCopy = opp.clone(false,true);
            oppCopy.Name = oppCopy.Name +' '+ date.today(); 
            insert oppCopy;
       }
}

===============

Now when I  m running the functionlaity everything works as desired... i.e.
I click on Custom, it calls the method createClone() in custom controller, this line get the current opportunity Id of the page
oppid = ApexPages.currentPage().getParameters().get('id');
and creates the clone....

But... when I m running created a code coverage I make a call to createClone() from test class..
as I have no way to pass this oppid when called from test class 

requesting to please guide me a way out get "oopid" while creating a test class

thanks in advance
Sunny

is there any way to reset password for salesforce internal users on Community?currently internal salesforce users(not community users) users are not receiving emails.
Is there any way to check using Metadata API if standard object allow to create custom fields? Example: we cannt create custom fields on Attachment object....
hey im getting following error while deploying can anyone please help 


1.  objects/Contact.object (Contact.LP_Priority__c) -- Error: The formula references fields across 16 relationships while only 15 are allowed. 
Please contact support at salesforce.com for more assistance. (line 3, column 13)

Thanks
 
I am facing this error in REST API webservice callout. Could you any one help to resolve this?

Note: I tried in giving req.setTimeout(20);

req.setEndpoint(toolingendpoint);
req.setMethod('GET');
Http h = new Http();
req.setTimeout(20);
HttpResponse res = h.send(req);
Hi all,

Are there any step-by-step manuals of how to create Outbound / Call Outs in Salesforce to get Third-Party data by REST API?
First of all i am looking for the basic steps, what you need to prepare / configure in Salesforce for the connection. Also i would like to know how you can do a simple test to see if the connection works to the REST API URL on the Third-Party side.

If i correctly understand you need APEX code to write the APEX Classes to get the real data?

Thanks in advance!

Hi,

We have been facing one issue while carrying out the Profile Deployment from Sandbox (Partial Copy) to the Production Environment. Below is the error which we are getting.

In field: field - no CustomField named Account.SalesforceCustomer found

We verified that the Account.SalesforceCustomer field does exist in the Source environment and not in the Production environment however it's not a Custom Field but a Standard Field.

Can anyone please let us know on which feature in Salesforce creates this Standard Field. Also, how to overcome this problem to ensure a seamless deployment.

Hi,

I have the following class where i am trying to write test class for it which covers only 35% , i am wondering how to cover the following lines , Kindly help me pls

 
MY APEX CLASS :


public class IarCloneAttachment implements Queueable {
	public Id attachmentId;
	public Id newParentId;
	public Set<String> oldIdList;
	public Map<String,String> oldParentId_newParentId_Map;
	public IarCloneAttachment() {
		
	}

	public void execute(QueueableContext context) {
		cloneAttachments();
	}

	public void cloneAttachments() {
        SkipingHelper.skipTriggerIARAttachmentTrigger  = true;
        SkipingHelper.SkippAllTriggersFromAttachment();
        for(Attachment attch :[SELECT Id,ParentId,BodyLength  FROM Attachment WHERE ParentId in:oldIdList]) {
            System.debug('Attachment xxx Heap Size:'+Limits.getHeapSize() + ' Limit:'+Limits.getLimitHeapSize());
        	System.debug('Attachment xxx Id:' + attch.Id + ' size:' + attch.BodyLength);
        	//Note: The following SOQL is inside a for loop. This is by design. Retrieving all the attachments in one soql will throw the heap size limit error.
			List<Attachment> attachmentList = [SELECT Body,ParentId,CreatedDate,ContentType,OwnerId,CreatedById,LastModifiedDate,IsPrivate,Description,Name,LastModifiedById FROM Attachment WHERE Id=:attch.Id];
			if (attachmentList.size()>0) {
				Attachment sAttachment = attachmentList[0].clone(false);
				sAttachment.ParentId = oldParentId_newParentId_Map.get(attachmentList[0].ParentId);
				sAttachment.ownerId = attachmentList[0].OwnerId;
				insert sAttachment;
				sAttachment.Body = null;
            }
        }
	}
}
MY TEST CLASS :

@isTest
public class IarCloneAttachment_Test {  
    static testmethod void IarCloneAttachment_TestMethod()
    {
        User Uu3 = IARTestUtilities.createStandardUser('WrkTs');
        System.RunAs(Uu3) {
            IARTestUtilities.createCustomSettingsForPRMSFDCVDMSGSAM();            
            Account acc = IARTestUtilities.createTestAccount();  
            system.debug('acc:'+acc); 
            
            Opportunity op = IARTestUtilities.createTestOpportunity(acc.id);                     
            system.debug('op:'+op);
            
            Test.startTest();
            IAR_Main__c IAR = IARTestUtilities.createNewTestIARwithSHForms(acc.Id,op.id,'EMS');        
            system.debug('IAR:'+IAR);
            
            
            Blob b = Blob.valueOf('Test Data');
            Attachment attachment = new Attachment();
            attachment.ParentId = acc.Id;
            attachment.Name = 'TestAttachmentforParent.xls';
            attachment.Body = b;
            insert(attachment);
            List<Attachment> attachmentList = new List<Attachment>();
            attachmentList.add(attachment);
            Set<String> oldIdList = new set<String>();
            oldIdList.add('attachment');

            Test.stopTest();  
            IarCloneAttachment iarc = new IarCloneAttachment();
            iarc.cloneAttachments();
            
        }
    }
}
LINES NOT GETTING COVERED:


public void execute(QueueableContext context) {
		cloneAttachments();
	}






**********************************************************************

List<Attachment> attachmentList = [SELECT Body,ParentId,CreatedDate,ContentType,OwnerId,CreatedById,LastModifiedDate,IsPrivate,Description,Name,LastModifiedById FROM Attachment WHERE Id=:attch.Id];
			if (attachmentList.size()>0) {
				Attachment sAttachment = attachmentList[0].clone(false);
				sAttachment.ParentId = oldParentId_newParentId_Map.get(attachmentList[0].ParentId);
				sAttachment.ownerId = attachmentList[0].OwnerId;
				insert sAttachment;
				sAttachment.Body = null;

Kindly help me how to cover those lines pls

Thanks in Advance

 
Hello all,
I need to display 10 records in a page where records residing in output panel.
Can anyone help me with this?
Thank you in advance !
Sumanth Kumar
Hi,
I have created the record in custom object in the related list nots and attachments i need to attach only one attachment not more than one.Can anybody Suggest how to achieve this either validation rule or trigger.
Hi All,

First off thank you to everyone for taking the time to read and help me out. With no prior experience I was put into a Salesforce Admin roll about two years ago. Now, with limited resources I have been tasked with a project that I believe will require Apex. Below I will try my best to explain what we would like to do.

I have two custom objects CMD Project (CMD_Project__c) and CMD Project Bidder (CMD_Project_Bidder__c)
CMD Project Bidder is a related list of CMD Project
 
CMD Project holds construction project information and CMD Project Bidder are the companies bidding to complete the projects.
 
Our potential clients (Accounts/Leads) are the companies bidding these projects.
 
The source of the project and bidder information provides a unique Company Id
 
I am hoping to use this unique Company Id to relate projects to Accounts and Leads, so that we will be able to see who is activly bidding construction projects. I would like for this to be automated so that anytime a CMD Project, CMD Project Bidder, Lead, Account is created or updated the projects companies are bidding will show up on a related list.

Once again thank you to all for taking the time to help out, please let me know if you have any questions for me or need additional information.
 
I am looking for the best way of looping through all of the accounts in our salesforce instance.

Where no contact is associated with that account, I would like to create a contact, pulling specific information from the account to populate the fields of the contact.

Could someone point me in the right direction.
what is the sysntax for catching errors in apex ?
What is exception handling in apex ?
Hello, 
I try to write a trigger which count the number of Custom Object (Naterbox Call) linked to a Lead. 

I dont have any error in the code, but I don't have results neither. 
Can someone help me ?

Best
Elsa

trigger NatterboxUpdateLead on Natterbox_Call_Reporting_Object__c (after delete, after insert, after undelete, after update) {

Set<ID> LeadIds = new Set<ID>();

//We only care about tasks linked to Leads.

String leadPrefix = Lead.SObjectType.getDescribe().getKeyPrefix();

//Add any Lead ids coming from the new data

if(trigger.new!=null){
    for (Natterbox Call Reporting Object, t : Trigger.new) {
     if (t.WhoId!= null && string.valueof(t.WhoId).startsWith(leadPrefix) ) {

if(!LeadIds.contains(t.WhoId)){
//adding unique lead ids since there can be many tasks with single lead
LeadIds.add(t.WhoId);
}
}
      }
}
 
//Also add any Lead ids coming from the old data (deletes, moving an activity from one Lead to another)

if(trigger.old!=null){
    for (Natterbox Call Reporting Object t2 : Trigger.old) {
     if (t2.WhoId!= null && string.valueof(t2.WhoId).startsWith(leadPrefix) )
         {
if(!LeadIds.contains(t2.WhoId)){
//adding unique lead ids since there can be many tasks with single lead
LeadIds.add(t2.WhoId);
}
}
      }
}

     if (LeadIds.size() > 0){



List<Lead> leadsWithNatterbox Call Reporting Objects = [select id,Natterbox_activity_Count__c,(select id from Natterbox Call Reporting Objects) from Lead where Id IN : Leadids];

List<Lead> leadsUpdatable = new List<Lead>();

for(Lead L : leadsWithNatterbox Call Reporting Objects){

L.Activity_Count__c = L.Natterbox Call Reporting Objects.size();
leadsUpdatable.add(L);

}

if(leadsUpdatable.size()>0){

update leadsUpdatable;
//update all the leads with activity count

}

    }
}
I have a class that is updating the owner of a record when the Submit to Legal button on the "Agreement Request" object is pressed. I am running into the "List has no rows for assignment to SObject" error when pressing the button and i'm not sure why. Below is my code: 

public with sharing class classSubmitToLegal {

    public Agreement_Request__c a{get;set;}
    public classSubmitToLegal() {
     a = new Agreement_Request__c ();
     a = [select Business_Unit__c from Agreement_Request__c Where Id=: ApexPages.currentPage().getParameters().get('Id')];
    }
    
    public void someMethod() {
      if(a.Business_Unit__c == 'EIS') {
         a.Business_Unit__c = 'EIS Queue';
         update a;
          Apexpages.Message errorMessage = new Apexpages.Message(ApexPages.Severity.Info,'You have changed the owner');
          Apexpages.addMessage(errorMessage);
      } else {
          Apexpages.Message errorMessage = new Apexpages.Message(ApexPages.Severity.Info,'You cannot update');
          Apexpages.addMessage(errorMessage);
      }
    }

}
Hello, is there a way to refresh our current developer ORG back to a clean, new-like copy of a sandbox?  Thanks!, Joseph
It's been a long while since I looked into written Apex triggers. I successfully created one a year ago but neglected to creat a test class for it which has now come to bite me in th ARS. If someone can have pitty on me and help me create a test class that would be greatly appreciated
 
trigger updateAccountStatus on Opportunity (after insert, after update) 
{ 
list<Id> accIds = new list<Id>(); 

/* list<Account> accounts = new list<account>(); */ 
Map<Id, Account> accounts = new Map<Id, account>(); 
for(opportunity o:trigger.new){ 

accIds.add(o.accountId); 

} 

for(account a:[select Id, Status__c from account where Id IN :accIds]){ 

for(opportunity opp:trigger.new){ 

a.Status__c = opp.Status__c; 
a.Approval_Progress__c = opp.StageName; 

/*accounts.add(a);*/ 
accounts.put(a.Id, a); 
/* if(opp.Status__c=='Active'){ 

a.Status__c='Active'; 

accounts.add(a); 

} 
*/ 
} 

} 
update accounts.values(); 
/* update accounts;*/ 
}

 
I have a formula field that contains a button and when the button is pressed depending on the value of another field, i would like the owner to change to a queue. I'm having trouble writing the class that goes along with this button. can anyone help? I would like it to be similar to the button below (within the field)
User-added image
User-added image

 
Dear Salesforce Community,

I am currently working on a report and was wondering if there is a way where we could make a customized column for account numbers. For instance if one looks at the picture below I have the columns for the account name date modified etc.I would like to create a column for "Account Numbers" that corresponds to each account name. Request if you could pelase assist and advise.
 For each of the account names there is an account number affiliated.

Thank You.
I have a custom Object Target. It is related to opportunity by lookup. Opportunity is child and Target is parent and Target have custom field Target Amount and want to sum of all opportunities amount related that target in this field. I know i have to write a trigger for that please help me to solve this.


Thanks in Advance
Hi. We have Parent opportunities that could have multible child opportunities. We are trying to sum the values of product costs form the child opportunities related to that parent ooportunitiy only if it was not lost. The filed name in child is tool_cost_c, the parent name is tool_cost_parent.

please advice.

 
Hi,

I have been working on approval process....................
I have 3 fields in loan object.....1. asst manager 2. senior manager 3. regional manager 
Based on the managers i need to pull dynamically in approval process for every loan record.
  • October 19, 2015
  • Like
  • 0
Hi
I have a requirement to displays records in pageblock based on "OnClick" event on the pageblock button with render attribute,
That mean when ever the pageblock button is clicked records should be displayed within that pageblock, i am failing to acheive this,
help will be appreciated,

Below is my controller and Vf page code for the reference:

Controller:

public with sharing class DisplayQueryList{ 
public List<Account> Records {get; set;}
public DisplayQueryList(){ 
Records = 
[select Name, AccountNumber, CleanStatus from Account where CleanStatus='Pending']; 

}

VF Page:

<apex:page controller="TestDisplayQueryList">
  <apex:form > 
    <apex:pageBlock title="Tabular display with facet"> 
        <apex:pageBlockTable value="{!Records}" var="Record"> 
            <apex:column > 
                <apex:facet name="header">Account Name</apex:facet> 
                <apex:outputText value="{!Record.Name}"/> 
            </apex:column> 
            <apex:column > 
                <apex:facet name="header">Account Number</apex:facet> 
                <apex:outputText value="{!Record.AccountNumber}"/> 
            </apex:column> 
            <apex:column > 
                <apex:facet name="header">Clean Status</apex:facet> 
                <apex:outputText value="{!Record.CleanStatus}"/> 
            </apex:column> 
        </apex:pageBlockTable> 
    </apex:pageBlock> 
    <apex:pageBlock title="Tabular Display without facet">
    <apex:pageBlockTable value="{!records}" var="record">
        
        <apex:column value="{!record.Name}"/>
        <apex:column value="{!record.AccountNumber}"/>
        <apex:column value="{!record.CleanStatus}"/> 
              
      </apex:pageBlockTable>
    </apex:pageBlock>
   </apex:form>     
</apex:page>
  • October 19, 2015
  • Like
  • 0
When you are sending a email from a lead, is there any way to validate or control who the sender email is programmatically?

Thank you,
Steve