• James Loghry
  • ALL STAR
  • 11003 Points
  • Member since 2010
  • Architect
  • Demand Chain Systems


Badges

  • Chatter
    Feed
  • 311
    Best Answers
  • 6
    Likes Received
  • 12
    Likes Given
  • 5
    Questions
  • 2075
    Replies
I need a validation in the Biliing Post Code code field to prevent users from typing and entering City and Coutry into the Post Code field the way it is displayed in the followng image
User-added image
Please advise how such validation can be achieved?
Hi,
I am working with an org which has the NPSP and a few other packages installed.
Using the "old" development cycle, I created a sandbox from the org, made my changes in eclipse and pushed the changes to production.
Now I want to use scratch orgs.
So I created a scratch org, used my package.xlm file from Eclipse to retrieve the config from the sandbox, converted it to the new format and attempted to push it to the scratch org.
However the config is dependent on fields that are part of the NPSP, so do I have to install all the packages that are in the sandbox manually into the scratch org before I can start development?
This seems to break the idea of a fast turnround - am I missing something?
Hi All,

Can you please help me with any sample code which will display records of account object on vfpage with pagination jquery grid(http://js-grid.com/demos/) having below options.
*sorting
*filtering
*with pagination buttons and page numbers

In the above i am having a controller will get the list of accounts(AccList) in constructor, i have to display 20 records per page. each next button of page number is clicked it should not go to controller all the processing should be done in jquery itself.

Please let me know if any possibility for the above. please refer the link for clear idea "http://js-grid.com/demos/"
Thanks in advance,
Mohammad Yaseen
 
Hi Friends,

                 I am getting following Issue when try to retrieve code using force.com migration tool."Access is denied". Can any one suggest me what is this Issue.I have copied the force.com migration tool in F drive. I used the following command to retieve 
C:\Users\lenovo>F:

F:\>cd F:\Ant>ant retrieveCode
Access is denied.

F:\>
I'm trying to write a trigger on task that when a new task is created, two fields on the opportunity are updated (opportunity 'Last Sales Activity' = task.createdDate, and opportunity 'Last Sales Activity Type = task.Type

How can I point it to the opportunity fields? Do I have to query for parent data first?  This is what I have:

trigger updateOpportunityActivityFieldsFromTask on Task (before insert) {
    
    for(task t:trigger.new) {
        if(t.whatid != null && t.whatid.getsobjecttype() == opportunity.sobjecttype) {
            t.WhatId.Last_Sales_Activity__c=t.CreatedDate;
            t.whatid.Last_Sales_Activity_Type__c=t.Type;
        }
    }
   
}
I am trying to build a pick list of countries from the Contact.MailingCountry field in a very large community (200,000+ members).
SOQL does not provide the SQL SELECT DISTINCT statement and there are several alternatives found on the web.
The following query fails with 'Too many query rows: 50001’ :
SELECT n.Member.Contact.MailingCountry c,  COUNT_DISTINCT(n.Member.Id) FROM NetworkMember n WHERE n.Member.IsActive = TRUE GROUP BY n.Member.Contact.MailingCountry LIMIT 50
Is there a better way to build a list of unique entries for a specific field in a large database that is optimized and performant?
I tried deploying this Trigger to my production this morning. It is a simple trigger to convert any names to Propper case, first and last. It seems like another APEX Class is interfeering with the deployment. The error points to a managed package I am not able to edit. Any ideas on how to get around this error? 

Full Error: 
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Proper: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.Proper: line 5, column 1: [] 
Stack Trace: Class.dlrs.RollupService.testHandler: line 277, column 1 Class.dlrs_LeadTest.testTrigger: line 11, column 1

APEX Trigger:
trigger Proper on Lead (before insert) {
  for(Lead l : Trigger.new){
    if(l.FirstName != null)
      l.FirstName =  l.FirstName.subString(0 ,1).ToUpperCase() + l.FirstName.subString(1);
      l.LastName =  l.LastName.subString(0 ,1).ToUpperCase() + l.LastName.subString(1);
  }
}

 
Hi there everyone,

I have a requirement to build a report that has sub totals and grand totals in it. Since I can't seem to figure out how to do this in the Salesforce reporting functionality, I'm doing it with a Visual force form. My thought was that I would process through a Object and group the entries by 'Activity'. When the activity changed, I would do a 'Sub total' for the activity. My thinking was that i would take the rows out of the 'SourceEntries' list, and add them to the 'TimeEntrires' list. When the Activity changes, then I would add an extra row to the list that serves as a 'Subtotal' like. Though I have some of the psuedo code in there and commented out, I'm finding that I can't even take information from one list to another.

Can anyone guide me on what I might be doing wrong. I am getting 'Attempt to de-reference a null object'.
The problem is with the statement 'TimeEntries.add(a);
The value of the debug statement is: DEBUG|Time_Entry__c:{Id=a04r0000002303wAAA, Activity__c=Research, Date_Worked__c=2017-04-14 00:00:00, Hours_Worked__c=1, Minutes_Worked__c=00, Work_Description__c=This is the first v1.2 time entry record for create time entry.}

The code involved is the following:
public class TERepController {

    //This is the list for handling the group of time entries related to the parent object. 
    public list<Time_Entry__c> SourceEntries {get;set;}
    //This is the list that will handle the detail with the totals added too it. 
    public List<Time_Entry__c> TimeEntries;

    //Used to get the parent request object ID from the Visual force page to the controller. 
    public string ReqID {get;set;}
    
    //Used to identify when there is an activity change for total generation. 
    public string strOldActivity = 'None';
    
    //Used to detect if a Row entered without selecting an action. 
    public TERepController(ApexPages.StandardController controller) 
    {
        //Obtain the parent object Id from the the visualforce form. 
        ReqId = Apexpages.currentPage().getparameters().get('Id');
        //Call the loaddata method to laod the time entries related to the parent object. 
        LoadData();
     }
    public void LoadData()
    {
        //Obtain the first 15 bytes of the Parent Object ID to use for record selection. 
        ReqId = 'a03r0000000rwC0';
        string RequestID = ReqId.substring(0, 15);
        //Load the related time entry records from the database. 
        SourceEntries = [select id, Activity__c, Date_Worked__c, Hours_Worked__c, Minutes_Worked__c, Work_Description__c from Time_Entry__c WHERE Related_Object__c=:RequestID order by Activity__c, ID]; 
        for(Time_Entry__c a : SourceEntries)
        {
//            if(a.Activity__c == strOldActivity)
//            {
//            	TimeEntries.add(new SourceEntries(a));
//            }
//            	else if(strOldActivity == 'None')
//                    {
                        System.debug(a);
             			TimeEntries.add(a);
//                        strOldActivity = a.Activity__c;
//                    }
//                    	else
//                        {
//                            Time_Entry__c b = new Time_Entry__c(Activity__c=strOldActivity, Work_Description__c='Activity Total', Hours_Worked__c='8', Minutes_Worked__c='30');
//                            TimeEntries.add(new SourceEntries(b));
//             				TimeEntries.add(new SourceEntries(a));
//                        	strOldActivity = a.Activity__c;
//                        }
        } 
        insert TimeEntries;
        return;
    }

}
I'd welcome any assistance anyone can provide me.

Thanks!

Eric Anderson

 
Hello,

Do all the users with same role but different profile can see each others account, opportunit and quote.

The user is able to see them, but i dont find any other reason other than this.

thanks for suggestion 
I have completed this challege, and ran the unit test, and it passes.  I have verified that the name value is being populated correctly and being compared appropriately.  So, all should be good, right?

However, when I click the Check Challenge button, I get an error:
Challenge Not yet complete... here's what's wrong:
There was an unexpected error in your org which is preventing this assessment check from completing:
System.CalloutException: Invalid HTTP method: Get

I can post my code if someone wants to verify it, but I don't think the issue is in the code as it appears to be working correctly.  Has anyone seen this kind of thing before?
 
  • January 26, 2017
  • Like
  • 0
We have a custom new contact visualforce page which uses visualforce component.
Recently we planned on implmenting Duplicate Matching rules to show Duplicate records(if any) up on saving a new record. 

we used the following link provided by Salesforce to write our custom visualforce logic to show duplicate matching records.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Datacloud_DuplicateResult.htm

We wrote the code in the custom component and component controller. The problem is that upon save it is not rendering the duplicateresult table(This table shows the duplicate records if any). 

Contact Visaulforce Page
<apex:page standardController="Contact" extensions="NewContactPageWithAddressController">
    <apex:sectionHeader title="New Contact"/>
    Contacts not associated with accounts are private and cannot be viewed by other users or included in reports.
    
    <c:ContactForms contact="{!contact}" redirect="true"/>
</apex:page>
Contact Controller
public with sharing class NewContactPageWithAddressController {
    public Contact contact{get;set;}
    public ApexPages.StandardController standardController {get;set;}
    
    public NewContactPageWithAddressController(ApexPages.StandardController controller) {
        standardController = controller;
        this.contact = new contact();
        this.contact.accountId = ApexPages.currentPage().getParameters().get('accid');
    }   
}

Visualforce Component: Contactform 
 
<apex:component controller="ContactFormsCont" allowDML="true">
	<apex:attribute name="contact" assignTo="{!mainContact}" description="The contact to be edited" type="Contact" required="true" />
	<apex:attribute name="redirect" assignTo="{!redirectPage}" description="Set true if the page should redirect to the contact after saving" type="Boolean" />
	<apex:attribute name="onSave" description="Javascript to be executed when record successfully saves" type="String" />
  <apex:attribute name="rerenderable" description="Hides fields that can't be rerendered, i.e.: rich text fields" type="Boolean" />
    <apex:form >
        <apex:pagemessages id="messages"/> 
         <apex:pageBlock title="Duplicate Records" rendered="{!hasDupResult}" id="DupRecords" >
            <apex:pageMessages />
            <apex:pageBlockTable value="{!duplicateRecords}" var="item">
                <apex:column >
                    <apex:facet name="header">Name</apex:facet>
                    <apex:outputLink value="/{!item['Id']}">{!item['Name']}</apex:outputLink>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">Owner</apex:facet>
                    <apex:outputField value="{!item['OwnerId']}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">Last Modified Date</apex:facet>
                    <apex:outputField value="{!item['LastModifiedDate']}"/>
                </apex:column>
            </apex:pageBlockTable> 
        </apex:pageBlock>
        
        
        <apex:pageBlock title="Contact Edit">
            
            <apex:pageBlockSection title="Contact Information" collapsible="False">
               <!-- <apex:outputLabel value="Contact Owner {!$User.FirstName}"></apex:outputLabel> -->
           <apex:pageBlockSectionItem >
               <apex:outputlabel value="Contact Owner"/>
               <apex:outputText value="{!$User.FirstName &' '& $User.LastName}"/>
               <!--<apex:outputLabel value=""> </apex:outputLabel>-->
              </apex:pageBlockSectionItem>
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.Contact_Information}" var="ContactInformation">
                   <apex:inputField value="{!mainContact[ContactInformation]}" required="{!ContactInformation.required}"/>
               </apex:repeat>
            </apex:pageBlockSection>
            
			<apex:pageBlockSection Id="ContactAddress" Title="Address Infromation">
                <apex:pageBlockSectionItem >
                    <apex:OutputLabel value="Address"/>
                    
                    <apex:actionRegion >
                        <apex:InputField value="{!contactAddress.Address__c}" required="false">
                            <apex:actionSupport event="onchange" immediate="false" action="{!selectAddress}" rerender="ContactAddress"/>
                        </apex:InputField>
                    </apex:actionRegion>    
                    
                </apex:pageBlockSectionItem>
                
                <apex:OutputField value="{!address.Name}" rendered="{!contactAddress.Id != null}"/><apex:outputField value="{!address.OwnerId}" />
                
                <apex:InputField value="{!address.Address_Name__c}" rendered="{!!addressSelected}"/>                
                <apex:outputField value="{!address.Address_Name__c}" rendered="{!addressSelected}"/>    <apex:OutputField value="{!contactAddress.Contact__c}"/>    
                <apex:InputField value="{!address.Address_Line_1__c}" rendered="{!!addressSelected}" />  
                <apex:OutputField value="{!address.Address_Line_1__c}" rendered="{!addressSelected}"/>  <apex:outputField value="{!contactAddress.Active__c}" />
                <apex:InputField value="{!address.Address_Line_2__c}" rendered="{!!addressSelected}"/>          
                <apex:OutputField value="{!address.Address_Line_2__c}" rendered="{!addressSelected}"/>  <apex:InputField value="{!contactAddress.Physical__c}"/>
                <apex:InputField value="{!address.Address_Line_3__c}" rendered="{!!addressSelected}"/>  
                <apex:OutputField value="{!address.Address_Line_3__c}" rendered="{!addressSelected}"/>  <apex:InputField value="{!contactAddress.Mail_To__c}"/>
                <apex:InputField value="{!address.Address_Line_4__c}" rendered="{!!addressSelected}"/>  
                <apex:OutputField value="{!address.Address_Line_4__c}" rendered="{!addressSelected}"/>  <apex:outputField value="{!contactAddress.Primary_Mail_To__c}"/>
                <apex:InputField value="{!address.City__c}" rendered="{!!addressSelected}" />            
                <apex:OutputField value="{!address.City__c}" rendered="{!addressSelected}"/>            <apex:OutputPanel />
                <apex:InputField value="{!address.Country__c}" rendered="{!!addressSelected}" />         
                <apex:OutputField value="{!address.Country__c}" rendered="{!addressSelected}"/>         <apex:OutputPanel />
                <apex:InputField value="{!address.State_Province__c}" rendered="{!!addressSelected}" />  
                <apex:OutputField value="{!address.State_Province__c}" rendered="{!addressSelected}"/>  <apex:OutputPanel />
                <apex:InputField value="{!address.Postal_Code__c}" rendered="{!!addressSelected}"/>     
                <apex:OutputField value="{!address.Postal_Code__c}" rendered="{!addressSelected}"/>     <apex:OutputPanel />
                
                <apex:pageBlockSectionItem rendered="{!address.Id != null}">
                    <apex:OutputLabel value="Address Last Modified Date"/>
                    <apex:OutputField value="{!address.LastModifiedDate}" />
                </apex:pageBlockSectionItem>
                <apex:pageblockSectionItem rendered="{!address.Id != null}">
                    <apex:OutputLabel value="Address Last Modified By"/>
                    <apex:OutputField value="{!address.LastModifiedBy.Name}" />
                </apex:pageblockSectionItem>
			</apex:PageBlockSection>
            
             <apex:pageBlockSection title="Strategic Account Management">
                <apex:repeat value="{!$ObjectType.Contact.FieldSets.Strategic_Account_Management}" var="StrategicAccountManagement">
                   <apex:inputField value="{!mainContact[StrategicAccountManagement]}"/>
               </apex:repeat>
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Additional Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.Additional_Information}" var="AdditionalInformation">
                   <apex:inputField value="{!mainContact[AdditionalInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            <apex:pageBlockSection title="DCW Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.DCW_Information}" var="DCWInformation">
                   <apex:inputField value="{!mainContact[DCWInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            <apex:pageBlockSection title="Intelligent Equipment User Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.Intelligent_Equipment_User_Information}" var="IntelligentEquipmentUserInformation">
                   <apex:inputField value="{!mainContact[IntelligentEquipmentUserInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            <apex:pageBlockSection title="System Information">
               <apex:repeat value="{!$ObjectType.Contact.FieldSets.System_Information}" var="SystemInformation">
                   <apex:inputField value="{!mainContact[SystemInformation]}"/>
               </apex:repeat>
            </apex:pageBlockSection>    
            
            
            <apex:PageBlockButtons >
                <apex:commandButton value="Save" action="{!save}" reRender="DupRecords" status="actStatusId" oncomplete="if({!recordSaved}){{!onSave}}"/>
                <apex:actionStatus id="actStatusId" >
                <apex:facet name="start" >
                  <img src="/img/loading.gif" />                    
                </apex:facet>
            </apex:actionStatus>
                <apex:commandButton value="Save & New" action="{!SaveandNew}" reRender="DupRecords" status="actStatusId2" rendered="{!redirectPage}"/>
                  <apex:actionStatus id="actStatusId2" >
                <apex:facet name="start" >
                  <img src="/img/loading.gif" />                    
                </apex:facet>
            </apex:actionStatus>
                <apex:commandButton value="Cancel" action="{!sc.Cancel}" reRender="messages" immediate="True" rendered="{!redirectPage}"/>
            </apex:PageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:component>

Component Controller
public with sharing class ContactFormsCont {
    public Contact_Address__c contactAddress{
    	get{
    		if(contactAddress == null){
    			contactAddress = new Contact_Address__c(Primary_Mail_To__c = true, Active__c = true);
    		}
    		return contactAddress;
    	}
    	set;
    }
    public Address__c originalAddress{
    	get{
    		if(originalAddress == null){
    			originalAddress = new Address__c();
    		}
    		return originalAddress;
    	}
    	set;
    }
    public Address__c address{
    	get{
    		if(address == null){
    			address = new Address__c();
    			addressSelected = false;
    		}
    		return address;
    	}
    	set;
    }
    public boolean addressSelected{get;set;}

    public boolean redirectPage{
    	get{
    		if(redirectPage == null) return false;
    		else return redirectPage;
    	}
    	set;
    }

    public Boolean recordSaved {
    	get{
    		return recordSaved == null? false : recordSaved;
    	} set;
    }

	public ApexPages.StandardController sc{
		get{
			return new ApexPages.StandardController(new Contact());
		}
	}
    
    private List<Contact> duplicateRecords = new List<Contact>();
    
    public List<Contact> getDuplicateRecords(){
        return duplicateRecords;
    }
	
	Public Boolean hasDupResult{
        get{if(duplicateRecords.isEmpty()){
            return FALSE;
        } else {
            return TRUE;
        } 
           }
        set;

    }    

    public Contact mainContact{
    	get;
    	set{
	    	if(value != null && value.Id != null){
	    		if(mainContact != null && mainContact.Id == value.Id ) return;
                try{
    		    	mainContact = Database.query('SELECT ' + String.escapeSingleQuotes(queryFields) + ' FROM Contact WHERE Id = \''+value.Id+'\' LIMIT 1');
                } catch (QueryException e){return;}
		    	loadAddressData(mainContact.Id); 	
	    	} else if(value != null && value.Id == null){
                Boolean isChanged = mainContact != value;
	    		mainContact = value;
                if(isChanged){
                    contactAddress = null;
                    address = null;
                }
	    	} else {
	    		mainContact = value;
	    	}
        }
    }

    // Pulls primary contact address and it's corresponding address object from database
    public void loadAddressData(Id contactId){
    	List<Contact_Address__c> ctcAddrs = [SELECT Id, Name, Contact__c, Address__c, Active__c, Mail_To__c, Physical__c, Contact__r.AccountId, Primary_Mail_To__c, 
											    	Address__r.Address_Line_1__c, Address__r.Address_Line_2__c, Address__r.Address_Line_3__c, Address__r.Address_Line_4__c, 
											    	Address__r.City__c, Address__r.Country__c, Address__r.State_Province__c, Address__r.Postal_Code__c, Address__r.Name, 
											    	Address__r.OwnerId, Address__r.Address_Name__c, Address__r.Id, Address__r.DCW_ID__c, Address__r.Warehouse_Id__c, 
											    	Address__r.IE_ID__c, Address__r.State_Province_ISO_Code__c, Address__r.Country_ISO_Code__c, 
											    	Address__r.LastModifiedBy.Name, Address__r.LastModifiedDate, LastModifiedBy.Name, LastModifiedDate
											 FROM Contact_Address__c
											 WHERE Contact__c = :contactID AND Primary_Mail_To__c = true];
		if(ctcAddrs.size() == 1) contactAddress = ctcAddrs[0];
		else {contactAddress = null; return;}
		address = contactAddress.Address__r;
		addressSelected = true;
		originalAddress = new Address__c(  Address_Line_1__c = contactAddress.Address__r.Address_Line_1__c
										  , Address_Line_2__c = contactAddress.Address__r.Address_Line_2__c
										  , Address_Line_3__c = contactAddress.Address__r.Address_Line_3__c
										  , Address_Line_4__c = contactAddress.Address__r.Address_Line_4__c
										  , City__c = contactAddress.Address__r.City__c
										  , Country__c =  contactAddress.Address__r.Country__c
										  , State_Province__c = contactAddress.Address__r.State_Province__c
										  , Postal_Code__c = contactAddress.Address__r.Postal_Code__c
										  , Address_Name__c = contactAddress.Address__r.Address_Name__c
									  	  , IE_ID__c = contactAddress.Address__r.IE_ID__c
									  	  , DCW_ID__c = contactAddress.Address__r.DCW_ID__c
									  	  , Warehouse_Id__c = contactAddress.Address__r.Warehouse_Id__c
										  , State_Province_ISO_Code__c = contactAddress.Address__r.State_Province_ISO_Code__c
										  , Country_ISO_Code__c = contactAddress.Address__r.Country_ISO_Code__c
										  , Id = contactAddress.Address__r.Id
										  );


    }

    // Gets all fields used in the page for querying
    public String queryFields{
    	get{
    		if(queryFields == null){
    			queryFields = ''; // Fields not in fieldsets can be added here, separated by commas
    			List<Schema.FieldSetMember> allFieldSets = new List<Schema.FieldSetMember>();
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Contact_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Strategic_Account_Management.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Additional_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.DCW_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.Intelligent_Equipment_User_Information.getFields());
    			allFieldSets.addAll(SObjectType.Contact.FieldSets.System_Information.getFields());
    			for(Integer i = 0; i < allFieldSets.size(); i++){
    				if(!String.isEmpty(queryFields)) queryFields += ', ';
    				queryFields += allFieldSets[i].getFieldPath();
    			}
    		}
    		return queryFields;
    	}
    	set;
    }
    
    public PageReference selectAddress()
    {
        if(contactAddress.Address__c != null)
        {
            address = [select Address_Line_1__c
                            , Address_Line_2__c
                            , Address_Line_3__c
                            , Address_Line_4__c
                            , City__c
                            , Country__c
                            , State_Province__c
                            , Postal_Code__c
                            , Name
                            , OwnerId 
                            , Address_Name__c
                            , DCW_Id__c
                            , Warehouse_Id__c
                            , IE_ID__c
                            , State_Province_ISO_Code__c
                            , Country_ISO_Code__c
                            , LastModifiedBy.Name
                            , LastModifiedDate
                        from Address__c
                       where Id = :contactAddress.Address__c];
                       
            addressSelected = true;
            contactAddress.Active__c = true;
        }
        else
        {
            addressSelected = false;
            address = new Address__c();
            contactAddress = null;
        }
        
        return null;
    }
    
    public PageReference Save(){
	    PageReference pg;
        Id prevContId = mainContact.Id;
        Contact_Address__c prevContAdd = contactAddress.clone(true, true);
        Address__c prevOrigAdd = originalAddress.clone(true, true);
        Address__c prevAdd = address.clone(true, true);
        Savepoint sp = Database.setSavepoint();
        
         
		    recordSaved = false;
			
            If(mainContact.Id != NULL){
                update mainContact;
                if(addressSelected == false) originalAddress = null;
                if(contactAddress.Contact__c == null) contactAddress.Contact__c = mainContact.Id;
    
                AddressHelper.saveContactAddress(  new List<ContactAddressDetail.ContactAddressWrapper>()
                                                   , new List<ContactAddressDetail.AccountAddressWrapper>()
                                                   , originalAddress
                                                   , address
                                                   , contactAddress
                                                   , addressSelected);
    
                pg= new ApexPages.StandardController(mainContact).view();
                pg.setRedirect(true);
                recordSaved = true;
            
            
            	return redirectPage? pg : null;
            } else{
                Database.DMLOptions dml = new Database.DMLOptions(); 
                dml.DuplicateRuleHeader.allowSave = true;
                dml.DuplicateRuleHeader.runAsCurrentUser = true;
                Database.SaveResult saveResult = Database.insert(mainContact, dml);
                
                system.debug('mainContact is: '+ mainContact);
                system.debug('save result is: '+ saveResult);
                
            	if (!saveResult.isSuccess()) {
                	for (Database.Error error : saveResult.getErrors()) {
                	// If there are duplicates, an error occurs Process only duplicates and not other errors (e.g., validation errors)
                	if (error instanceof Database.DuplicateError) {
                        // Handle the duplicate error by first casting it as a DuplicateError class
                        // This lets you use methods of that class  (e.g., getDuplicateResult())
                        Database.DuplicateError duplicateError = (Database.DuplicateError)error;
                        Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();
                        
                        // Display duplicate error message as defined in the duplicate rule
                        ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.Severity.ERROR, 'Duplicate Error: ' + duplicateResult.getErrorMessage());
                        ApexPages.addMessage(errorMessage);                        
                        // Get duplicate records                        
                        //duplicateRecords = new List<Contact>();
                        //hasDupResult = False;
                        // Return only match results of matching rules that find duplicate records
                        Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();
                        System.debug('Match Results: ' + matchResults);
                        // Just grab first match result (which contains the duplicate record found and other match info)
                        Datacloud.MatchResult matchResult = matchResults[0];
                        System.debug('Match Result: ' + matchResult);
                        Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
                        System.debug('matchRecords: ' + matchRecords);
                        // Add matched record to the duplicate records variable
                        for (Datacloud.MatchRecord matchRecord : matchRecords) {
                        System.debug('MatchRecord: ' + matchRecord.getRecord());
                        duplicateRecords.add((Contact)matchRecord.getRecord());
                        System.Debug('Final Duplicate Records: '+ duplicateRecords);
                    } 
                    this.hasDupResult = TRUE;
                    System.Debug('hasDupResult: '+ this.hasDupResult);
                    System.Debug('Final Duplicate Records: '+ duplicateRecords);
                }
                        
            
            }
            
            
        }
                //If there’s a duplicate record, stay on the page
                return null;
            }

            
    }
    
    public PageReference saveAndNew() {
        PageReference pg =  Page.NewContactPageWithAddress;
        pg.setRedirect(true);
        return save() == null ? null : pg;
    }
}

Please see the highlighted code which needs to rerender the page block in Visualforce component id = DupRecords.

Thanks for your help.
  • January 24, 2017
  • Like
  • 0
My apexmessages aren't showed! Can someone help me out? 

Visualforce:
<apex:pageMessages></apex:pageMessages>
    
    <apex:form>
    <apex:actionFunction name="showSuccess" action="{!showSuccess}" rerender="messages">
        <apex:param name="message" assignTo="{!message}" value="" />
        <apex:param name="messageType" assignTo="{!messageType}" value="" />
    </apex:actionFunction>
    </apex:form>
Javascript:
showSuccess('Logo uploaded succesfull', 'SUCCESS');
Apex:
public string message{get; set;}
    public string messageType{get; set;}


 public void showSuccess(){
        if(messageType == 'SUCCESS'){
system.debug('TestMessage' + message);
            ApexPages.Message alertMsg = new ApexPages.Message(ApexPages.Severity.CONFIRM,'TESTSUCCESS');
			ApexPages.addMessage(alertMsg); 
        	///ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, message));
        }else if(messageType == 'WARNING'){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, message));
        }else if(messageType == 'ERROR'){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, message));
        }

  	}
My system.debug is visible in the debug logs but the apex message doesn't appear.
Im using it in chatter (VF Chatter Action)

Thanks,

Sergio

 
Hi all,

I need to write a query which shows opportunity information and opportunitylineitem information. Underneath you find my query so far. I tried putting in OpportunityLineItem.Product2.Name but I got an error. Is there somebody that can help me? I am using the Developer Console to check my query, afterwards I will export the information trough the data loader. 

SELECT Name, StageName, Substage__c, Closedate, Opportunity_number__c, Navision_Order_Number__c, Installer__r.Name, Payment_Account__r.Name, Payment_Account__r.PaymentAccountNumber__c, Payment_Account__r.Billing_Country__c, Shipping_Country__c, Opportunity_Product.Product2.Name, Payment_Account__r.id, id FROM Opportunity WHERE Closedate > 2015-01-01 AND Closedate < 2017-01-01 AND StageName != 'Closed Lost' AND StageName != 'Intake'
Hello
I have a process builder process which executes on a field update. After the first criteria evaluation I execute 3 actions

1.1 Invoke Email by Invocable Apex
1.2 Standard Field Update
1.3 Standard Email Alert

After the 1st criteria the process does not stop it evaluates the 2nd critera and it should execute 3 actions

2.1 Invoke Email by Invocable Apex
2.2 Standard Field Update
2.3 Standard Email Alert

User-added image

If I do the field update to meet criteria 1 but not criteria 2
all actions are executed which belong to the criteria (1.1,1.2,1.3)
Works fine!

If I do the filed update to meet criteria 2 but not criteria 1
all actions are executed which belong to the criteria (2.1,2.2,2.3)
Works fine!

If the field update meets criteria 1 AND 2 then the standard actions are executed (1.2,1.3,2.2,2.3) but ONLY ther first apex criteria is launched (1.1) and the second is completely ignored (2.1).

The apex action is only executed once which is wrong.

In the debug log there is NO apex exception.

And as the standard field updates/email alerts are executed it is sure that both criterias are met and considered by SF.

The problem is that the apex invoke is only launched once.
Has anyone had this problem before?
Please help.




 
Hi i got a custom WSDL file and when ever i try to request data from salesforce from external application through wsdl it is asking me session id , Is there any way where i can access the salesforce data through wsdl file with out entering session id each and every time or like anything where we can include authentication in the same apex class and then generate the wsdl file where the authentication will take pace internally or something like that.
  • January 05, 2017
  • Like
  • 0
I have a web service in java running in my local machine. I need to know , if this can be called from salesforce apex code?
This is a strange one. I cannot log into developer.salesforce.com on my PC. I am sending this from my iPad. Has anyone else experienced this?
I am attempting to automate the deactivation of User accounts for terminated employees. In order to streamline the process I am attempting to use Email Services to kick off some code which will look up an account and mark it deactivated upon receiving an email with "Termination" in the subject and the employee ID in the body. 

Here is some code I have which I cannot get to work : 
 
global class InboundEmailHandler implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        if ( email.subject == 'Termination' ) {
            TerminateController.getInstance().terminate(email.plainTextBody);
        }
        return result;
    }
}
 
public class TerminateController() {
     @TestVisible private static final TerminateController INSTANCE = new TerminateController();
    public static TerminateController getInstance() {
        return INSTANCE;
    }
    public void terminate(String commaSeparatedString) {
        String[] employeeids = commaSeparatedString.split(',');
        List<User> users = [SELECT isActive FROM User WHERE employee_Id__c IN: employeeids and isActive = true];
        for ( User u : users ) {
            u.isActive = false;
        }
        update users;
    }

I can't get the controller to save properly. I continuously get an error : "expecting left curly bracket, found '(' at line 1 column 32 "

Any ideas on this ? 

Thank you.
  • November 17, 2016
  • Like
  • 0
I have an API set up currently to login to Salesforce using 'https://login.salesforce.com/services/Soap/u/34.0'. If I want to have an option to login to a Sandbox, do I need to hard code that URL to 'https://test.salesforce.com/services/Soap/u/34.0'? Or is there another option so I don't have to hard code two different URLs?
Hello,

I am trying to run a flow that will use a field in a Lead record (specifically, the Lead record that initiates the Process Builder that references this flow).  I have tried using a Lookup field and I've tried creating a variable, but nothing seems to work.

Basically, I am trying to check if the email address in a Lead matches the email address in any existing Contact.  If so, update a field on the Lead with that Contact ID

I am currently working with 
User-added imageUser-added image
Last week, it was brought to my attention that security reviews and audits are now asking ISVs to check for Field Level Security (FLS) and Object CRUD permissions prior to any DML outside of standard controllers.  

This is a fairly radical change that impacts a lot of managed package applications across the board. I and others have several concerns about this change in the security review process:
  1. Why the sudden change in security review policy?  
    • None of the ISVs I have talked to were informed of the change prior to being either audited or submitting any apps for security review.  The only official documentation I can find on the change is a blurb in the Security Scanner help page here: http://security.force.com/security/tools/forcecom/scannerhelp.  
    • As ISVs, it would be greatly appreciated to have an official Security Review Guide, that is updated well in advance to when policy changes like this take place.  Some ISVs have several packages, others lots of customizations, and we all need time to prepare for the security review.
  2. Has the security scanner been updated to enforce this rule yet?
    1. I have not run an app through the Security Review process recently, so I am curious if this rule has been implemented already in the security scanner. (http://security.force.com/security/tools/forcecom/scanner)
  3. Why force FLS and CRUD checks on every DML transaction?
    • I am a fan of using standard controllers when necessary, but several apps, including one my company develops rely heavily on Custom Controllers.  In most cases where FLS comes into play, typically it's a simple fix of a profile permission or permission set that resolves the issue.  Instead, now, we have to implement FLS and CRUD checking prior to each DML transaction.  This adds complexity on top of existing DML calls.  
    • If need be, can the FLS and CRUD checking be done on a one-time run in an install script?
    • Does Salesforce have any plans of either adding FLS checking for custom controllers or adding methods to Apex for checking credentials similar to the Force.com EASPI library? (https://code.google.com/p/force-dot-com-esapi/)
Thanks, I look forward to hearing any feedback on this issue.

Is it possible to deploy field labels (e.g. Setup->Customize->Tab names and labels->Rename Tabs and Labels) into a managed package?

I see no option to specify these in a managed package.  Custom labels are supposed to get picked up and packaged automatically, but when I go to install the package, the org does not show the field labels being set properly.

 

Regards,

- James

 

I've come across an app called postcode anywhere that provides a lookup link next to the standard Postal code field on the New Account page. http://appexchange.salesforce.com/listingDetail?listingId=a0330000002dQlnAAE

The New Account page is not overriden in this case, and is the standard out of the box New Account page.

 

I've tried creating a custom inline VF page that provides that same functionality, but the page layout only dictates what is displayed on the detail page, and not the edit nor the new pages.  That is , as far as custom VF, buttons, and links are concerned.

 

My question is, how is it possible to display the custom link on the new page, short of overriding the new button to display a custom VF page.  I'm assuming the postcode anywhere app is using javascript wizardry, but perhaps I'm missing something here.

 

Thanks,

- James.

Is it possible to enable fields for a Knowledge article that is previewed when PublishStatus='Draft' ?

 

I have the following link where hardly any of the fields are populated for the Article preview.  The exception being lastmodified date I believe.

 

https://tapp0.salesforce.com/knowledge/publishing/articlePreview.apexp?id={id}&popup=true&pubstatus=d&preview=true

 

When I change the link to include an online article instead, the fields populate fine.

 

https://tapp0.salesforce.com/knowledge/publishing/articlePreview.apexp?id={0}&popup=true&pubstatus=o&preview=true

 

Why are certain fields hidden from draft articles in preview state vs. online articles?  Can I get around this, or will I be forced to implement a custom VF solution?

 

Thanks.

Hi All,

 

We have a client who needs the ability to delete a Product2 object in Salesforce.com, with the ability of it showing up in an opportunity if it once existed there.

 

If the Product2 object is part of an opportunity when it is deleted via the UI in salesforce, it asks if you would like to archive the Product2.  Is there a way to accomplish this from the command line?

 

Another option would be to set the Product2 to isActive = false.  However, you can just 'Activate' the Product2 from the Products tab / view in Salesforce (The activate link on the tab ignores Validation rules, fyi).

 

Any ideas or help would be much appreciated.

Last week, it was brought to my attention that security reviews and audits are now asking ISVs to check for Field Level Security (FLS) and Object CRUD permissions prior to any DML outside of standard controllers.  

This is a fairly radical change that impacts a lot of managed package applications across the board. I and others have several concerns about this change in the security review process:
  1. Why the sudden change in security review policy?  
    • None of the ISVs I have talked to were informed of the change prior to being either audited or submitting any apps for security review.  The only official documentation I can find on the change is a blurb in the Security Scanner help page here: http://security.force.com/security/tools/forcecom/scannerhelp.  
    • As ISVs, it would be greatly appreciated to have an official Security Review Guide, that is updated well in advance to when policy changes like this take place.  Some ISVs have several packages, others lots of customizations, and we all need time to prepare for the security review.
  2. Has the security scanner been updated to enforce this rule yet?
    1. I have not run an app through the Security Review process recently, so I am curious if this rule has been implemented already in the security scanner. (http://security.force.com/security/tools/forcecom/scanner)
  3. Why force FLS and CRUD checks on every DML transaction?
    • I am a fan of using standard controllers when necessary, but several apps, including one my company develops rely heavily on Custom Controllers.  In most cases where FLS comes into play, typically it's a simple fix of a profile permission or permission set that resolves the issue.  Instead, now, we have to implement FLS and CRUD checking prior to each DML transaction.  This adds complexity on top of existing DML calls.  
    • If need be, can the FLS and CRUD checking be done on a one-time run in an install script?
    • Does Salesforce have any plans of either adding FLS checking for custom controllers or adding methods to Apex for checking credentials similar to the Force.com EASPI library? (https://code.google.com/p/force-dot-com-esapi/)
Thanks, I look forward to hearing any feedback on this issue.
I need a validation in the Biliing Post Code code field to prevent users from typing and entering City and Coutry into the Post Code field the way it is displayed in the followng image
User-added image
Please advise how such validation can be achieved?
Hello all,

First post here, I am trying to learn Apex and a newbie at this. I am trying to do the following trailhead:

https://trailhead.salesforce.com/trails/force_com_dev_beginner/modules/apex_triggers/units/apex_triggers_intro

In the example, they provide the following code:
// Get the related opportunities for the accounts in this trigger Map<Id,Account> acctsWithOpps = new Map<Id,Account>( [SELECT Id,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);

I don't understand why map is declared of type Account but then the subquery (SELECT Id FROM Opportunities) returns IDs of type opportunities?

Second question:
System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities.size());
Since opportunities is a child object to account, why do we use get(a.id).opportunities because I thought the dot notation was to traverse from child to parent?

Appreciate all the help...
J




 
i dont know the meaning of the some symbols int he validation rules like ^(exponential) but this is used in the text fields. what is the meaning of this and [0-9]&[a-z] and like those some are not understanding plz give the some explanation regarding these
  • November 26, 2017
  • Like
  • 0
public with sharing class accsearchcontroller
  {
    public accsearchcontroller(ApexPages.StandardController controller) {     }   
  public String l { get; set; }
public list <quote> acc {get;set;}
public string searchstring {get;set;}
public String quoteid{get; set;}
public Boolean search{get; set;}
public Boolean result{get; set;}
public accsearchcontroller( )
  { }
public void search()
{ string searchquery='select QuoteNumber,Name,Email,Opportunity.Name,SAP_Reference_Number__c  from quote where SAP_Reference_Number__c like \'%'+searchstring+'%\' OR SAP_Reference_Number__c like \'*'+searchstring+'*\'  Limit 20'; acc= Database.query(searchquery);
}
public void clear()
{
acc.clear();
}
public PageReference processLinkClick()
 {                 
  search = false;    
    result = false;     
    //Pagereference p1 = new PageReference('https://ap7.salesforce.com/'+quoteid);     
  Pagereference p1 = new PageReference('https://swainswain-dev-ed.my.salesforce.com/'+quoteid);     
    p1.setRedirect(true);    
     return p1;    
 }
}
Getting this error

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, PfxTaxUpdateOppProposal: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.PfxTaxUpdateOppProposal: line 6, column 1: [] 
Stack Trace: Class.TestAxcessInsertTaxUpdateOpps.InsertOpp: line 20, column 1


On this test class

@isTest
Private Class TestPfxInsertTaxUpdateOpps{
static testMethod void InsertOpp(){

TaxUpdateYear__C TUY = new TaxUpdateYear__c(
name = 'UpdateYear',
year__c = '2018');
insert TUY;


Account A = new Account(
            Name = 'myAcct', 
            BillingStreet='25 Upland Drive',
            BillingPostalCode='94127',
            BillingCountry='United States',
            BillingCity='San Francisco',
            Pfx_Tax_Update_Counter__c = 0 );
        insert A;
        
        Account_x_reference__c xref = new account_x_reference__c(
name = '990026',
applicationid__c = '990026', 
application__c = 'AMS', ams_special_agreement__c = 'X', ams_consolidation_code__c = '028',
account__c = a.id);
insert xref;
        
        A.Pfx_Tax_Update_Counter__C = 1;
        a.Tax_Update_Account_Number__c = xref.id;
        
        update a;
        
        
   
        }
        }  

on this trigger

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
trigger AxcessTaxUpdateOppProposal on Account (after update) {
    for (Account A:trigger.new){
    TaxUpdateYear__C TUY = TaxUpdateYear__c.getInstance('UpdateYear');
    String Year = TUY.year__c;
           Account oldAccount = Trigger.oldMap.get(A.Id);
        if(oldAccount.Axcess_Tax_Update_Counter__C <>  A.Axcess_Tax_Update_Counter__C){
          Opportunity O = new Opportunity(
          accountId = A.Id,
          name = a.name +' - '+Year+' Tax Update Order',
          amount = 150.00,
          StageName = '5. Time to Buy',
          ForecastCategoryName = 'High Probability',
          Forecast_Type__c = 'High(>90%)',
          Primary_contact_for_proposal__c = a.tax_update_contact__c,
          primary_contact_email__c = a.tax_update_contact_email__c,
          primary_contact_phone__C = a.tax_Update_Contact_phone__c,
          product_category__c = 'Small Firm Software',
          product_sub_category__c = 'Tax',
          type = 'New to Existing',
          RecordTypeId = '01231000001NWytAAG',
          closedate = system.Today(),
          OwnerId = UserInfo.getUserId()); 
          insert O;
            
            apttus_proposal__proposal__c P = new apttus_proposal__proposal__c(
            apttus_proposal__account__c = A.Id,
            apttus_proposal__proposal_name__c = O.name,
            apttus_proposal__approval_stage__c = 'Approved',
            apttus_proposal__opportunity__c = O.Id,
            quote_total__C = 150.00,
            RecordTypeId = '012i0000001EOtSAAW',
            apttus_QPConfig__PriceListId__c = 'a1fi0000000y6L4AAI',
            OwnerId = UserInfo.getUserId(),
            annual_start_date__c = system.Today()
          ,erp_account__c = A.Tax_Update_Account_number__c );            
            insert P;
            
            apttus_Config2__ProductConfiguration__c C = new apttus_Config2__ProductConfiguration__c (
            name = p.name,
            ownerId = UserInfo.getUserId(),
            Apttus_Config2__BusinessObjectId__c = P.Id,
            Apttus_Config2__BusinessObjectType__c = 'Proposal',
            Apttus_Config2__EffectivePriceListId__c = 'a1fi0000000y6L4AAI',
            Apttus_Config2__PriceListId__c = 'a1fi0000000y6L4AAI',
            Apttus_QPConfig__Proposald__c = P.Id,
            Apttus_Config2__Status__C = 'Finalized',
            Apttus_Config2__VersionNumber__c = 1,
            Proposal_ID__c = P.Id);
            Insert C;
            
             Apttus_Config2__LineItem__c CLI = new Apttus_Config2__LineItem__c(
                Apttus_Config2__ConfigurationId__c = C.Id,
                Apttus_Config2__ChargeType__c = 'One Time Fee',
                Apttus_Config2__BasePrice__c = 150.00,
                Apttus_Config2__BaseExtendedPrice__c = 150.00,
                Apttus_Config2__ExtendedPrice__c = 150.00,
                Apttus_Config2__IsPrimaryLine__c = true,
                Apttus_Config2__ItemSequence__c = 1,
                Apttus_Config2__LineNumber__c = 1,
                Apttus_Config2__ListPrice__c = 150.00,
                Apttus_Config2__LineStatus__c = 'New',
                Apttus_Config2__NetPrice__c = 150.00,
                Apttus_Config2__PriceListId__c = 'a1fi0000000y6L4AAI',
                apttus_config2__PriceListItemId__c = 'a1e0S0000007RYK',
                Apttus_Config2__PriceType__c = 'One Time',
                Apttus_Config2__ProductId__c = '01t0S000000krh9',
                Apttus_Config2__Quantity__c = 1,
                Apttus_Config2__SellingFrequency__c = 'Yearly',
                Apttus_Config2__SyncStatus__c = 'Synchronized',
                Apttus_Config2__PricingStatus__c = 'Complete',
                Apttus_Config2__PrimaryLineNumber__c = 1);
                Insert CLI; 
            
             
              apttus_proposal__proposal_line_item__c PLI = new apttus_proposal__proposal_line_item__c(
              apttus_proposal__proposal__c = p.Id,
                apttus_proposal__product__c = '01t0S000000krh9',
                apttus_qpconfig__quantity2__c = 1,
                apttus_qpconfig__linenumber__c = 1,
                apttus_qpconfig__itemsequence__c = 1,
                apttus_qpconfig__listprice__c = 150.00000,
                apttus_qpconfig__netprice__c = 150.00,
                apttus_qpconfig__linestatus__c = 'New',
                apttus_qpconfig__lineType__c = 'Product/Service',
                apttus_proposal__description__c = 'CCH AXCESS TAX UPDATE SEMINAR - MTS',
                apttus_qpconfig__PriceListItemId__c = 'a1e0S0000007RYK');
                insert PLI;
             Template_Line_item__C TLI = new Template_Line_Item__C(
                OwnerId = UserInfo.getUserId(),
                name = 'QLI-Record',
                ams_product_Category__c = 'Tax Professional & Client Services',
                Product__c = '01t0S000000krh9',
                Quote_Proposal__C = p.Id,
                display_ams_product_category__c = 'Tax Professional & Client Services',
                proposal_line_item__C = PLI.Id);
                
                insert TLI;
                
                  P.quote_total__c = 150.00;
                Update P;
                
                opportunitylineitem OLI = new opportunitylineitem(
                opportunityId = O.Id,
                product2Id = '01t0S000000krh9',
                Quantity = 1,
                TotalPrice = 150.00,
                Item_Number__C = '1',
                BasePrice__c = 150.00,
                PriceBookEntryId = '01u0S000001Lr93');
            
                
                insert OLI;   
               
                
   }
}
}


Trigger has 100% coverage in test.
Not sure why it is failing during deployment.
 
Hi,

I'm looking for a good pattern to be able to log:
  • Inbound REST requests - capture details of request and response
  • Outbound REST requests - capture details of request and response.  Needs to be able to log request priort to call out and then log response post call out.
  • Exception logging
  • Custom settings to control levels of logging - can be basic at the moment as in on/off
  • Log clean up/purge jobs 
I have no doubt you guys have already done this a million times in salesforce! 
Thanks! 
  • November 25, 2017
  • Like
  • 0
I've got some code that's throwing errors that provide no information of value.  I wrapped it in a try/catch block to catch the exception at the source so I can isolate and correct it, but its now throwing CPU time outs.

So I've gotta ask - are try/catches super processor intensive? 

Also - tips for working around this would be greatly appreciated...

Thanks,
We have been working on a custom softphone implementation for Lightning Service Console. The Lightning component we created has been added to Console as Utility Bar’s custom Lightning component. This means that we did not wrap the component with a Visualforce page and we did not create a Call Center.
 
Problem is with click2dial functionality. We’ve found this tutorial: https://developer.salesforce.com/docs/atlas.en-us.api_cti.meta/api_cti/sforce_api_cti_enableclicktodial_lex.htm
 
When we added ‘/support/api/40.0/lightning/opencti_min.js’ to the Lightning component we get a Javascript error ‘Failed to initialize Open CTI. Ensure that it is loaded from the right frame with correct URL parameters’.
We have found following discussion: https://developer.salesforce.com/forums/?id=9060G000000MOplQAG
Unfortunately we do not have a Visualforce to add ‘sfdcIframeOrigin’ parameter to URL.
 
Is it possible to use click2dial functionality within Lightning components which are not wrapped in Visualforce?
Hi,
I am working with an org which has the NPSP and a few other packages installed.
Using the "old" development cycle, I created a sandbox from the org, made my changes in eclipse and pushed the changes to production.
Now I want to use scratch orgs.
So I created a scratch org, used my package.xlm file from Eclipse to retrieve the config from the sandbox, converted it to the new format and attempted to push it to the scratch org.
However the config is dependent on fields that are part of the NPSP, so do I have to install all the packages that are in the sandbox manually into the scratch org before I can start development?
This seems to break the idea of a fast turnround - am I missing something?
hi
sir, plz help me with the code i m very fresh to codeing and salesforce 
Campaigns should contain both Leads and Contacts as Campaign Members.
Either Lead or Contact of Campaign Members cumulative amount whichever is greater should be updated in Campaign object - Cumulative Amount of Leads or Contacts.
 
I have a below requirement  ,Need to create a custom object "Custom A"  which will have 2 look fields Account Name and Contact Name
.I need to create a vf page such that if I click on account name it shows me 10 records and a search box that
let me search account by putting 3 alphabets and same funcationality in contact name but it should search contact only related  to selected
account.

I have created a basic code .
Apex class
public class create_employee_mv {
    public List<String> listofAccountName {get;set;}
    public List<String> listofContactFirstName {get;set;}
    public Set<Id> AccId;
    public create_employee_mv(ApexPages.StandardController stdcntrl)
    {
        listofAccountName = new List<String>();
        Accid = new Set<Id>();
        for(Account a : [Select Id, Name,(select Employee_Designation__c from Employee_MVs__r)
                         from Account])
        {
         listofAccountName.add(a.name);
         Accid.add(a.id);
        }
        
        
    }

}

VF page
<apex:page standardController="Employee_MV__c" extensions="create_employee_mv" docType="html-5.0">
    <apex:form>
        
        <apex:inputText list="{!listofAccountName}"  /> &nbsp;
        <apex:inputField value="{!Contact_Name__c}"/>
        
    </apex:form>
</apex:page>



 
Hi All,

Can you please help me with any sample code which will display records of account object on vfpage with pagination jquery grid(http://js-grid.com/demos/) having below options.
*sorting
*filtering
*with pagination buttons and page numbers

In the above i am having a controller will get the list of accounts(AccList) in constructor, i have to display 20 records per page. each next button of page number is clicked it should not go to controller all the processing should be done in jquery itself.

Please let me know if any possibility for the above. please refer the link for clear idea "http://js-grid.com/demos/"
Thanks in advance,
Mohammad Yaseen
 
User-added image

I`m create the "cases" report.

User-added image

after saving and validating the error happens

User-added image
User-added image
I'm trying to write a trigger on task that when a new task is created, two fields on the opportunity are updated (opportunity 'Last Sales Activity' = task.createdDate, and opportunity 'Last Sales Activity Type = task.Type

How can I point it to the opportunity fields? Do I have to query for parent data first?  This is what I have:

trigger updateOpportunityActivityFieldsFromTask on Task (before insert) {
    
    for(task t:trigger.new) {
        if(t.whatid != null && t.whatid.getsobjecttype() == opportunity.sobjecttype) {
            t.WhatId.Last_Sales_Activity__c=t.CreatedDate;
            t.whatid.Last_Sales_Activity_Type__c=t.Type;
        }
    }
   
}
Hello,

I am getting the following exception. Can anybody help me out?

Subject: Developer script exception : trgMatter : trgMatter: execution of AfterUpdate caused by: System.UnexpectedException: Salesforce System Error: 1844620699-11039 (-984542339) (-984542339) Class.cache.PlatformCacheDelegateWrapper.g...

Apex script unhandled trigger exception by user/organization: 005o00000023ef4/00Do0000000ASe3r

trgMatter: execution of AfterUpdate

caused by: System.UnexpectedException: Salesforce System Error: 1844620699-11039 (-984542339) (-984542339)

Class.cache.PlatformCacheDelegateWrapper.getSessionDefault: line 16, column 1
Class.cache.Session.getDefault: line 99, column 1
Class.cache.Session.getPartitionInstance: line 108, column 1
Class.cache.Session.get: line 49, column 1
Class.CacheManager.get: line 17, column 1
Class.MatterTriggerHandler.handleAfterUpdate: line 10, column 1
Trigger.trgMatter: line 5, column 1
I am trying to create a visualforce email template for the welcome email of my community.

<messaging:emailTemplate subject="Bienvenido al Portal de empleo" recipientType="User" relatedToType="Community">
<messaging:plainTextEmailBody >

To get started, go to {!Community_Url}

Thanks,
{!Organization.Name}
</messaging:plainTextEmailBody>
</messaging:emailTemplate>

I get the following error:

Error: Unknown property 'core.email.template.EmailTemplateComponentController.Community_Url'

Are recipientType="User" and relatedToType="Community" the right things to use? Where can I see the mergefields I can use?
Any help welcome!

Thanks!
 
Hi

I am working on Communities, where I wanted to replace the Salesforce Standard title tag's text: Home with my custom text. 
I have made changes to "Head Markup" from Advanced settings in Community Builder by adding title tag with Custom text, but even, I am getting Home as Browser's tab.

I can see, the tab loads with my custom text, but after completion of the loading, it is changing back to Home text.
Where can I remove or change preference to not to use this Head title?

Please respond to me with even a question, that way I can move forward with my progress.

Thanks
Hi all,

I'm stuck in the Apex Integration Services - Apex SOAP Callouts challenge with the following message "The Apex class 'ParkLocator' does not appear to be calling the SOAP endpoint.".

Could you please advise ?
As a certified Salesforce consulting partner, PDO, and ISV, ForceBrain.com builds cloud & mobile apps. We've been a salesforce partner for over 6 years and you'll be joining a super fun team of true rockstars. We're seeking a Technical Architect who will work-from-home as a full-time employee, assisting Project Leads in designing and building solutions for multiple projects (zero travel required).

RESPONSIBILITIES
• Lead the design, architecture, and development for salesforce CRM solutions for multiple projects in a deadline-focused and fast-paced environment
• Perform detailed evaluation of business requirements and produce clear technical & design specifications, defining customer's business objectives and needs
• Mentor team members on the overall implementation strategy and solutions
• Deliver excellent presentation, technical design, and architecture documentation
• Assist sales engineers in building and demonstrating prototypes in Salesforce
• Participate in scoping development projects and estimate resource requirements
• Oversee onshore and offshore teams in executing technical solutions on complex development projects

REQUIREMENTS
• You have a minimum of 3 years of Force.com Development experience.
• You have architected, designed, and developed over 5 Force.com projects, including ui design, functional design, data modeling, security, etc…
• Proficient with the Force.com Developer Toolkit including: Apex, Visualforce, Force.com IDE, Force.com Migration Tool, Web Services/SOA, & Metadata APIs.
• Expert knowledge of how to work within the the limitations of the Salesforce.com platform, including governor limits, code coverage, etc...
• Experience integrating the Salesforce platform with other systems, whether it is using the web services API, restful API, or http post.
• You are comfortable giving direction to more junior consultants and mentoring.
• You have expertise in understanding the business processes, and systems involved in
running organizations.
• You thrive in a startup organization / entrepreneurial environment.

PREFERRED SKILLS
• XML, CSS, HTML, Javascript, J-Query, etc... 
• Understanding of the entire SDLC and various methodologies.
• You have a good sense of humor, tough-skinned, and handle stress well.

INTERESTED?
• Send your resume to jobs(at)forcebrain.com
• Answer the questions on this form: http://goo.gl/forms/QtaEm7aeQJ

GENERAL STATS
• Full Time Employee
• Location: Remote, Work & Live Anywhere
• Salary with bonus and generous benefit package
• Applicant must be willing to work 8am PST - 5pm PST shift
• Principals only. No recruiters please.

ABOUT FORCEBRAIN.COM
• Established in 2008, ForceBrain.com manages an all-star team of Salesforce Consultants, Force.com Developers, and Technical Architects to design, develop, deploy, and support cloud & mobile solutions . 
• We offer a competitive salary and benefits package, opportunity for continuous education, flexible working hours, and tools for working remotely.
• In 2010, ForceBrain.com became certified as a B-Corporation, recognizing the transparency in which we run our organization and our accountability in giving back.
I'm trying to authenticate with an external webservice in an apex class using a callout, and I'm getting this callout exception: "System.CalloutException: Received fatal alert: handshake_failure".  I can make the call using REST Console on my chrome browser.  Sending a POST HttpRequest to the following path:
https://{server}/auth?username={username}&password={password}

This should return json containing a sessionId, but when I execute this request i get the CalloutException.  I've registered the server in the remote sites in my SFDC instance.  I'm not sure why i'm getting this handshake failure.

Help!!!!!!

Hi,

I'm a PHP and Wordpress developer, new to SF.

I created a new custom object, called "referrals".

Every record in this object has a couple of fields and also an "email" field.

In my accounts object, I created a new field - "number of referrals".

In this field, I want to get the total number of referrals that has the same email address as the account.

What's the best way to do that?

Thanks!
Hello Everyone,

I think except for standard and custom objects we can not reuse the salesforce listview component. i have some set of records from a web service call which i have to show in a listview. Since not to miss the salesforce listview with pagination and other features, i have planned to use listview of salesforce with standardsetcontroller. But unfortunately sales force can show only the data of existing standard and custom objects only. What if the data is temporary and just required to be shown  to the user, where he can make his selections and then proceed. To do this do i need to create a listview using all the visualforce coding, handling the pagination. can not i use the salesforce listview to show data with out custom or standard objects?

regards,
Bujji

Hello - I need some assistance from the great minds in the SFDC dev community.  I've been asked to automatically add the count of Opportunity Team Members to a field on the Opportunity (basically just a roll-up).  For the most part this can't be done declaratively, so created a trigger.  The Non-Bulkified version of the trigger is very simple.  However, I can't see a way with collections (maps, lists, etc.) to bulkify it and keep my SOQL out of the For Loop.  Can anyone offer any ideas or suggestions as to how I could bulkify and keep the query out of a loop?  Here is my trigger code.


Thank you very much!
Jason

trigger CountOppTeam on OpportunityTeamMember (after insert, after delete)
{
List<Opportunity> oppList = new List<Opportunity>();
set<Id>oppIds = new set<Id>();

if(Trigger.isInsert || Trigger.isUpdate)
{
  List<id> oppId = new List<id>();
  for (OpportunityTeamMember oppTm: trigger.new)
  {
   oppIds.add(oppTm.OpportunityId);
  }

  for(Opportunity o: [Select id, CountTeamMembers__c From Opportunity Where id IN: oppIds])
  {
   List<OpportunityTeamMember> oppTmList = [Select id, Opportunityid From OpportunityTeamMember Where Opportunity.id =: o.id];
   o.CountTeamMembers__c = oppTmlist.Size();
   oppList.add(o);
  }

  update oppList;
}
else if (Trigger.isDelete)
{
  List<id> oppId = new List<id>();
  for (OpportunityTeamMember oppTm: trigger.old)
  {
   oppIds.add(oppTm.OpportunityId);
  }

  for(Opportunity o: [Select id, CountTeamMembers__c From Opportunity Where id IN: oppIds])
  {
   List<OpportunityTeamMember> oppTmList = [Select id, Opportunityid From OpportunityTeamMember Where Opportunity.id =: o.id];
   o.CountTeamMembers__c = oppTmlist.Size();
   oppList.add(o);
  }

  update oppList;
}
}
  • August 02, 2014
  • Like
  • 1
Hi I have spent around 40 hours trying to write a test class and when I remove one error I get another.  

I have set up a simple APEX class that is an extension for a Visualforce page. The VF page has a commandButton that saves and takes you to a different page called "Congratulations.vfp"

When I save my test I get this error:

Error: Compile Error: Variable does not exist: controller.Account.Joe_Test__c at line 15 column 9

Here is my Code:

APEX CLASS --

public class linkToVFP {
private ApexPages.StandardController controller;
public linkToVFP(ApexPages.StandardController controller) {
this.controller = controller;
}

  public PageReference saveAndCongrat() {
  controller.save(); // This takes care of the details for you.
  PageReference congratsPage = Page.Congratulations;
  congratsPage.setRedirect(true);
  return congratsPage;
}
}


VF Page --

<apex:page standardController="Account" extensions="linkToVFP">
    <apex:form >
        <apex:inputCheckbox value="{!Account.Joe_Test__c}" selected="" />
        <apex:commandButton value="Go To New Page" action="{!saveAndCongrat}"/>
    </apex:form>
</apex:page>

Test --

@isTest
public class linkToVFP_TEST {

    public static testMethod void testMyClass(){
        Account a = new Account(Name = 'Test Account', Joe_Test__c = false);
        insert a;

        PageReference pg = Page.Congratulations;
        Test.setCurrentPage(pg);

        ApexPages.StandardController stdController = new ApexPages.StandardController(a);
        linkToVFP customController = new linkToVFP(stdController);

        system.assertEquals(false, a.Joe_Test__c);
        controller.Account.Joe_Test__c = true;
        PageReference newPage = controller.saveAndCongrat();

        Account newAccount = [Select Id, Joe_Test__c From Account Where Id =: a.Id];
        system.assertEquals(true, a.Joe_Test__c);

        system.assertEquals(Page.Congratulations, newPage);
    }
}

It is probably something simple that I am missing but I havent been working with Apex for long and I have come from a HTML/CSS/PHP background so you might need to dumb it down a little for me.

Thank you.
I have a vf page have a custom list view now in custom controller class i want to access those records which are selected on vf page.
Hi

when we are refreshing a fullcopy sandbox from production does profile gets migrated to full copy sandbox after refresh.

please suggest

Regards
Dilip
All of the documentation I have been reading (which seems to be the latest version) uses API version 31.0
I am tring to login as described here:

https://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_quickstart_login.htm

And just get this result.
<faultcode>sf:UNSUPPORTED_API_VERSION</faultcode><faultstring>UNSUPPORTED_API_VERSION: Invalid Api version specified on URL</faultstring>

Am tring to login to the sandbox environment so using these URLs:
Same result for both URLs:

https://test.salesforce.com/services/Soap/u/31.0
https://test.salesforce.com/services/Soap/c/31.0

When I change it to version 30.0, it works ok.

I'm worried by reading the 31.0 documentation and using api version 30.0, I will end up wasting time trying to get something to work when it never will.

Please help

Hi All,

  i am trying  to fetch the Targetobjectid from SendEmailResult  object but i am not able to get that value.

 my functionality is :

I need to  send  Bulk Emails to different Contacts  using Send Email method like below:

 Messaging.sendEmail(emails,false); // Here emails is a List.

  Example :  Lets say i am sending 50 mails at a time  in that  48 mails are successfully sent and  2 are failed to send.

    Here i need to find what are the Mails failed and  it's related records (in this Scenario  case is my Object)

 for getting the SendEmailresults  code is below :

List<Messaging.SendEmailResult> sendEmailResults = Messaging.sendEmail(emails,false);
  for(Messaging.SendEmailResult sendEmailResult: sendEmailResults){

                 if(!sendEmailResult.isSuccess()){
                    system.debug(sendemailresult);
                }
                   
              }

 The sendEmailresult for  Failure records is       Messaging.SendEmailResult[getErrors=(Messaging.SendEmailError[getTargetObjectId=null;]);isSuccess=false;]

 The send Email Result for Successful Records is      Messaging.SendEmailResult[getErrors=();isSuccess=true;]

but in both ways  iam not able to get the  TargetObjectid .
 
i red in Salesforce docs  as below:

an error occurs that prevents sendEmail() from sending the email to one or more targets, each TargetObjectId for those targets has an associated error in SendEmailResult. A TargetObjectId that does not have an associated error in SendEmailResult indicates the email was sent to the target. If SendEmailResult has an error that does not have an associated TargetObjectId, no email was sent. 


  let me know am i doing anything wrong here and one morething   failure email    are due to  bouncing emails not because of  email address empty in contact.   
Thanks in Advance.

 

Hello, 

 

I am trying to prevent a duplicate record from being inserted so I am using the sObject.addError() method in a before insert trigger. The trigger was written to handle bulk operations. In my test class When I insert a duplicate record, I catch the exception from the addError() call. When I run a bulk test,  the behavior is not what I expected.

 

This is an example, not the actual code:

Case newCase = new case(Subject = 'Subject1', SuppliedEmail='test@test.com'; Origin="Email to Case'));

insert new Case;

 

List<Case> caseList = new List<Case>();

caseList.add(new case(Subject = 'Subject1', SuppliedEmail='test@test.com'; Origin="Email to Case'));

caseList.add(new case(.Subject = 'Subject2', SuppliedEmail='testx@test.com'; Origin="Email to Case'));

caseList.add(new case(Subject = 'Subject3', SuppliedEmail='testy@test.com'; Origin="Email to Case'));

caseList.add(new case(Subject = 'Subject4', SuppliedEmail='testz@test.com'; Origin="Email to Case'));

insert caseList;

 

When the insert caseList is executed, I am expecting the first record to fail due to the addError call that will be executed because it is a duplicate of the case created in the first insert operation. But I am also expecting the other three cases to be created.

 

When I query the Case object for the other 3 cases, my assertion fails because I am expecting 1 record to exist for 'Subject2' but the actual is 0.

 

I didn't think addError caused a rollback on all records in a bulk transaction. Am I missing something?

 

Thanks in advance,

 

Jim