• netspider
  • NEWBIE
  • 95 Points
  • Member since 2011

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 35
    Replies

Hi folks,

 

New to Apex development. I've written an Apex method to check data (zipcode) on new cases. If they're in the U.S. and there's a match with a group of accounts, it fills in a lookup field. It's called by a simple trigger that passes on all cases before insert & update.

 

I've learned in doing this that Apex does not even create an empty variable for an empty field, whether it's passed in from Trigger.new (the cases) or a SOQL query (the accounts). Most of the fields this method uses aren't and can't be required. So both in looping through accounts that may not have zipcodes filled in, and in dealing with cases that don't have the information I'm testing for filled in, this method has a big problem with running into null pointer exceptions due to empty fields.

 

For now, I'm simply catching any null pointer errors to make sure this doesn't stop any records from being saved and edited, but this seems like a terrible way of doing things. Does Apex have a way of testing if a field/variable exists? Or is there some other way of dealing with this I'm missing? I suppose I could simply set up try/catch for each individual variable as a way of setting "this variable exists" booleans, but again, I'm used to the idea that there should be a better way.

 

Thanks,

 

-Ben

  • February 26, 2013
  • Like
  • 0

Hi,

 

Do you know if it is possible to get values from a map starting at a particular position in a map, until the end of the map?

 

Kind of like a substring function but instead to create a new submap.

 

Any suggestions are welcome.

 

Thanks in advance.

Hey Guys,

I need to get Object Permissions then build a Map doing something like
'<Parent__r.ProfileId, ObjectPermissions>
         map<Id, ObjectPermissions[]>'

 

I have wriiten a piece of code below, but the error says (SELECT Id,  //Whichever other fields I may need

SELECT is an unexpected token

 

 

Also follwoing the data model on http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_erd_profile_permissions.htm

the code below seems to be not following the diagram.

 

//get objPerms  then build Map<Parent__r.ProfileId, ObjectPermissions>
         // map<Id, ObjectPermissions[]>
    //from ObjectPermissions Parent__r.ProfileId in the set
    map<Id, ObjectPermissions[]> mapProfileIdtoObjectPermissions = new map<Id, ObjectPermissions[]>();
    for(PermissionSet PS : [SELECT Id, ProfileId
    (SELECT Id,  //Whichever other fields I may need
        FROM ObjectPermissions) // could have issue with ObjectPermissions, I need to get correct child name
        FROM PermissionSet
        WHERE ProfileId IN: profileIds]){
    //we check whether the key has already been put to the map, if not, we perform a put
    if(mapProfileIdtoObjectPermissions.get(PS.ProfileId) == null)
        mapProfileIdtoObjectPermissions.put(PS.ProfileId, new list<ObjectPermissions>{PS.ObjectPermissions});
    // else, the key has already been put, so we just add all ObjectPermissions that are related to this ProfileId
    else
        mapProfileIdtoObjectPermissions.get(PS.ProfileId).addAll(PS.ObjectPermissions);
}

 

 

 

If someone could help I would appreciate there I am noew to Salesforce and its programming language.

 

 

Thanks

I setup oAuth and a Connected App with 2 Production orgs and that worked no problem. But when Im trying to connect a Production org with a sandbox in a separate org and Salesforce asks for authentication during the setup by logging into the destination org I receive an error
"We can’t log you in because of an authentication error. For help, contact your Salesforce administrator."
All credntials are correct.
Im using the Callback URL in the auth provider and entering into the connected app in the sandbox org.
Ive entered the correct Consumer Key and Consumer Secret
Ive entered the correct Authorize Endpoint URL and Token Endpoint URL

So it seems there is a problem connecting a Production org with a sandbox in a separate org

Can anyone help?
I have 3 Salesforce orgs and I want 1 org to be able to access data in another org
Lets call the orgs
Client1 - the calling org
Client2 - the calling org
Dest1 - the destination org

So in Dest1 I have set up a connected App, no problem, which has a consumer key and a Consumer secret. For the Start URL I just created a quick visualforce page. I guess when the user connects from  Client1  and Client2 orgs they are shown this page.
I then go to the Client1  and Client2 orgs and create a Auth. Provider and I pasted the Consumer Key and Consumer Secret. All the other fields I left blank. Salesforce created a bunch of URLs in the Auth. Provider , 1 was "Existing User Linking URL". So I copied this url that Salesforce created into the browser thinking that this would open up my Start URL vf page and I will now have access to Dest1 org, but instead I got


error=redirect_uri_mismatch&error_description=redirect_uri%20must%20match%20configuration

So something is going wrong
Please help
I have 3 Salesforce orgs and I want 1 org to be able to access data in another org
Lets call the orgs
Client1 - the calling org
Client2 - the calling org
Dest1 - the destination org

So in Dest1 I have set up a connected App, no problem, which has a consumer key and a Consumer secret. For the Start URL I just created a quick visualforce page. I guess when the user connects from  Client1  and Client2 orgs they are shown this page.
I then go to the Client1  and Client2 orgs and create a Auth. Provider and I pasted the Consumer Key and Consumer Secret. All the other fields I left blank. Salesforce created a bunch of URLs in the Auth. Provider , 1 was "Existing User Linking URL". So I copied this url that Salesforce created into the browser thinking that this would open up my Start URL vf page and I will now have access to Dest1 org, but instead I got


error=redirect_uri_mismatch&error_description=redirect_uri%20must%20match%20configuration

So something is going wrong
Please help
I want to know how you could write a bit of code to do true reflection programming in Salesforce

So say you have a piece of data which has the name of functions and the apex code will take this and run the function you have entered, so if a new function is deployed to Salesforce you dont need to change this class with another if statement and will still be able to run the new function
I want to know how you could write a bit of code to do true reflection programming in Salesforce

So say you have a piece of data which has the name of functions and the apex code will take this and run the function you have entered, so if a new function is deployed to Salesforce you dont need to change this class with another if statement and will still be able to run the new function

 

We are hitting limits in sending emails from Salesforce, so we need to be able to send out our emails via Gmail, but I cannot find any information on creating a bit of Apex code to send out emails from gmail

 

 

Thanks in advance for your help

 

I want multiple orgs to be able to copy my apex code from my org, so I expected the Enterprise  to be best placed for this, but could also use the Partner wsdl and the query method to query ApexClass object.

 

But when I try to import the wsdl I get errors

 

The faultPartnerSoapSforceCom sobjectPartnerSoapSforceCom class are made, but not partnerSoapSforceCom



 

Error: partnerSoapSforceCom


Error: unexpected token: 'delete' at 670:51

 

 

i have tried this trigger to match referral__id__c on lead to customer_id__c on account and then to populate account name from matched account to a lookupfield (to account) on lead.....:

here's what i have written - 
trigger update_rid on Lead (before insert, before update) {

Set<String> rid = new Set<String>();
    
    for(lead ld : trigger.new){
        if(ld.referrer_id__c != null){
    
       rid.add(ld.referrer_id__c);
        } 
}

    if(rid.size() > 0){

    map<string, account> cid2rid = new map<string, account>();
    for(account acc : [select id,name,customer_id__c from account where name IN :rid]){
        
        cid2rid.put(acc.name, acc);
    }  
        for(lead ld : trigger.new){
            if((Trigger.isInsert || trigger.oldMap.get(ld.Id).referrer_id__c != ld.referrer_id__c) && cid2rid.containsKey

(ld.referrer_id__c)){
        ld.referer_account_name__c = cid2rid.get(ld.referrer_id__c).account;
            
            }     
        }

}
}
I have 3 Salesforce orgs and I want 1 org to be able to access data in another org
Lets call the orgs
Client1 - the calling org
Client2 - the calling org
Dest1 - the destination org

So in Dest1 I have set up a connected App, no problem, which has a consumer key and a Consumer secret. For the Start URL I just created a quick visualforce page. I guess when the user connects from  Client1  and Client2 orgs they are shown this page.
I then go to the Client1  and Client2 orgs and create a Auth. Provider and I pasted the Consumer Key and Consumer Secret. All the other fields I left blank. Salesforce created a bunch of URLs in the Auth. Provider , 1 was "Existing User Linking URL". So I copied this url that Salesforce created into the browser thinking that this would open up my Start URL vf page and I will now have access to Dest1 org, but instead I got


error=redirect_uri_mismatch&error_description=redirect_uri%20must%20match%20configuration

So something is going wrong
Please help

Hi,

 

I'm having trouble coming to terms with the fact that according to the documentation: customers can disable data validation rules in a managed package.

 

http://na15.salesforce.com/help/doc/en/packaging_component_attributes.htm

 

If I'm reading this right, the validation rule can literally be turned off. This effectively "invalidates" data by permitting users to skirt rules they find annoying... As a developer of an app, I need to ensure it functions correctly with the right source data - how can I do this if the very method of validating my data is avoidable?

 

Honestly, I just can't believe this could happen, and I'm hoping I'm mis-interpreting it...

 

So, if this is the case, how am I supposed to validate my applications data?

  • October 07, 2013
  • Like
  • 1

Hi folks,

 

New to Apex development. I've written an Apex method to check data (zipcode) on new cases. If they're in the U.S. and there's a match with a group of accounts, it fills in a lookup field. It's called by a simple trigger that passes on all cases before insert & update.

 

I've learned in doing this that Apex does not even create an empty variable for an empty field, whether it's passed in from Trigger.new (the cases) or a SOQL query (the accounts). Most of the fields this method uses aren't and can't be required. So both in looping through accounts that may not have zipcodes filled in, and in dealing with cases that don't have the information I'm testing for filled in, this method has a big problem with running into null pointer exceptions due to empty fields.

 

For now, I'm simply catching any null pointer errors to make sure this doesn't stop any records from being saved and edited, but this seems like a terrible way of doing things. Does Apex have a way of testing if a field/variable exists? Or is there some other way of dealing with this I'm missing? I suppose I could simply set up try/catch for each individual variable as a way of setting "this variable exists" booleans, but again, I'm used to the idea that there should be a better way.

 

Thanks,

 

-Ben

  • February 26, 2013
  • Like
  • 0

Let's say I have a list of questions that stores an object that has a list of it's possible answers, and I need to generate all permutation pairs with no duplicates where one element of the pair is in the first list and the second one in the second list. In other words, let's say I have 2 questions, and each one has 2 answers, how many answer sets could I create with this? One last thing, the order is important. An answer from the first question could not be in the position from the 2nd question, if that makes sense.

 

I hope this is clear.

 

Thanks!

 

-- I also posted this up to the Salesforce StackExchange

Hi,

 

I'm am trying to depoy an apex trigger to production, and I am running into an error that's seemingly completely unrelated to the code I'm trying to deploy but it's preventing me from being able to do it.

 

I'm not sure why this is happening or what changes I can make to avoid this error, but any insight you have would be extremely helpful. I have no idea what else to do to fix it!

 

Here's the failure message I'm getting when I try to deploy the inbound change set and there is a failure:

 

API Name
Type
Line
Column
Problem

UnitTests_logAttempts.SingleLeadAttempts() Class 15 1 Failure Message: "System.Exception: Too many SOQL queries: 101", Failure Stack Trace: "Trigger.ActivityOppStageName2: line 15, column 1"

 

Here's the "Trigger.ActivityOppStageName2" apex code that's causing the problem:

 

trigger ActivityOppStageName2 on Task (before insert, before update){

// If related to an Opportunity, query to find out the Opportunity number

// Create collection of tasks that are related to an opp (where the opp is listed only once)
    Set<Id> opIds = new Set<Id>();
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startsWith('006') && !opIds.contains(t.WhatId)){
            opIds.add(t.WhatId);
        }
    }
    // Pull in opp ids and related field to populate task record
    List<Opportunity> taskOps = [Select Id, leadsource, lead_source_detail__c, StageName from Opportunity where Id in :opIds limit 1];
    System.assert(taskOps != null);
    Map<Id, Opportunity> opMap = new Map<Id, Opportunity>();
    for(Opportunity o : taskOps){
        opMap.put(o.Id,o);
    }
    // Update custom task field with custom opp field
    for(Task t : trigger.new){
        String wId = t.WhatId;
        if(wId!=null && wId.startswith('006')){
            Opportunity thisOp = opMap.get(t.WhatId);
            if(thisOp!=null){t.Sales_Stage__c = thisOp.StageName;} 
            if(thisOp!=null){t.Lead_source__c = thisOp.LeadSource;}
            if(thisOp!=null){t.record_type__c = 'Opportunity';}
            if(thisOp!=null){t.lead_source_detail__c = thisOp.Lead_source_detail__c;} 
        }
    }
}

 

Here's the "UnitTests_logAttempts.SingleLeadAttempts()" unit test class that's related to the problem:

 

       static testMethod void SingleLeadAttempts() {
        
        if(!runTest_SingleLeadAttempts == true) {
            System.debug('===== SingleLeadAttempts unit test is currently inactive; enable before release');
        } else {
            
            Lead l = new Lead(FirstName = 'Bob',
              LastName = 'Test',
              Company = 'TestCo',
              Email = 'btest@testco.com',
              Title = 'Captain',
              Number_of_Customers__c = 10,
              Leadsource = 'Sourced by Sales',
              Lead_source_detail__c = 'sales',
              Customer_Type__c = 'good',
              How_Do_They_Assess_Networks_Today__c = 'unknown',
              lead_stage__c = 'Suspect',
              Status='None');
              
            insert l;
            
            String sToday = Date.Today().format();
            // Insert a call task
            Task t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call ' + sToday + ' 9:45 AM',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Completed',
              
              ActivityDate = Date.Today());
              
            insert t;
            
            // Inserting a Call Task should automatically update the Lead
            l = ReGetLead(l.Id);
            
           
            
            String sId = l.Id;
            String compareResult;

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call with my mother',
              Type = 'Call',
              Status = 'Completed',          
              ActivityDate = Date.Today());
              
            insert t;
            
            l = ReGetLead(l.Id);
          

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call with my mother',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Completed',          
              ActivityDate = Date.Today());
              
            insert t;
            
            l = ReGetLead(l.Id);
            

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Completed',          
              ActivityDate = Date.Today());
              
            insert t;
            
            l = ReGetLead(l.Id);
         

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call ' + sToday + ' 9:45 AM',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Not Started',
              
              ActivityDate = Date.Today());
              
            insert t;
        
            l = ReGetLead(l.Id);            
            // This should fail as Status <> 'Completed'
           

            t = new Task(
              WhoId = l.Id,
              whatid = null,
              Subject = 'Call ' + sToday + ' 9:45 AM',
              CallType = 'Outbound',
              CallObject = '924892',
              Type = 'Call',
              Status = 'Completed',
              
              ActivityDate = Date.Today());
              
            insert t;
        
            l = ReGetLead(l.Id);            
         

            // Test Connect                         
            compareResult = logAttempts.createAttempt('Connect', 'Lead', sId);
            
            l = ReGetLead(l.Id);
            
           
            
            // Test Profile
            compareResult = logAttempts.createAttempt('Profile', 'Lead', sId);
            
            l = ReGetLead(l.Id);
            
      
           
        }
   }
   
   static testMethod void SingleLead_LiveDemoAttempt() {
    
        if(!runTest_SingleLead_LiveDemoAttempt == true) {
            System.debug('===== SingleLead_LiveDemoAttempt unit test is currently inactive; enable before release');
        } else {        
            
            Lead l = new Lead(FirstName = 'Bob',
              LastName = 'Test',
              Company = 'TestCo',
              Email = 'btest@testco.com',
              Title = 'Captain',
              Number_of_Customers__c = 10,
              Customer_Type__c = 'good',
              Leadsource = 'Sourced by sales',
              Lead_source_detail__c = 'sales',
              Lead_stage__c = 'Suspect',
              How_Do_They_Assess_Networks_Today__c = 'unknown');
              
            insert l;
            
            String sId = l.Id;
            String compareResult;
            
            // Test Live Demo
            compareResult = logAttempts.createAttempt('Live Demo', 'Lead', sId);
            
            // Query for a Task associated to the Lead
            Task newTask = 
              [Select WhoId, Type, Subject, Status, Id 
               From   Task 
               Where  WhoId = :sId
               Limit 1];
                        
          
            
        }
   }
   

 

 

If you need any further information to help, please let me know!!

 

Thank you!

 

Hi There,

 

My req. is,I've Account obj as a master and Contract(custom obj)as detail.I've created 2 custom fields on Account eg.Asset Management Calculated Status,Built Environment Calculated Status with picklist values 'Customer' and 'Ex-Customer'.and Contract have 2 recordtypes say,'Asset Management','Built Environment'.Now whenever user select Contract recordtype as 'Asset Management' with Status 'Active' then it's corresponding Account 'Asset Management Calculated Status' field should get updated as 'Customer' value. and in other case, if user select Status as 'Terminated' then it's corresponding Account 'Asset Management Calculated Status' field should be updated as 'Ex-Customer'.

 

Business wants to write trigger on Contract and call apex class from there and class will hold all the logic......

 

plus I've to use custom setting for this scenario.in future if more Contract recordtype added then no need to touch code it should run dynamically......here are details:

 

Created custom setting named Record Maping added 2 custom fields and thru manage button inserted 2 records.

Custom Setting : Record Mapping

 

Record Type Name: Asset Management

Field Name :Asset Management Calculated Status

 

Record Type Name: Built Environment

Field Name :Built Environment Calculated Status

 

here is my code:

Trigger:

trigger ContractUpdate on MITIE_Contract__c (after insert,after update) {


// Creating an object named 'obj' of class "AccountUpdate"
    AccountUpdate obj = new AccountUpdate();
    system.debug('object calling 1');
  // Calling the 'CheckCondition' function of class "AccountUpdate"
    obj.CheckCondition(Trigger.new);
}

Class:

 

Public with sharing class AccountUpdate{


List<ID> accid= New List<ID>();

public void CheckCondition(MITIE_Contract__c[] m){

List<Record_Mapping__c> mcs = Record_Mapping__c.getAll().values();
system.debug('mcs..'+mcs);


//For Asset Management recordtpe on Contract
for(integer j=0;j<mcs.size();j++){
if(m[0].Status__c =='Active' && mcs[j].RecordType_Name__c=='Asset Management' &&m[0].Organisation_Name__c != null){

accid.add(m[0].Organisation_Name__c);
List<Account> oppList = [SELECT id, Asset_Management_Calculated_Status__c FROM Account WHERE id in :accid]; 

for(integer i = 0 ; i < oppList.size(); i++){
oppList[i].Asset_Management_Calculated_Status__c ='Customer';
}
update oppList;


}
}

 

 

Amruta

 

Hi,

 

Do you know if it is possible to get values from a map starting at a particular position in a map, until the end of the map?

 

Kind of like a substring function but instead to create a new submap.

 

Any suggestions are welcome.

 

Thanks in advance.

public class SearchController
{
 public String nameQuery {get; set;}
 public List<Client__c> clients {get; set;}
  
 public PageReference executeSearch()
 {
  String queryStr='%' + nameQuery + '%';
  clients=[select id, Name
            from Client__c
            where name like :queryStr];
            
  return null;
 }
  
 public SearchController()
 {
  // if query appears in URL, execute it
  String urlQuery=ApexPages.currentPage().getParameters().get('query');
   
  if ( (null!=urlQuery) && (0!=urlQuery.length()) )
  {
   nameQuery=urlQuery;
   executeSearch();
  }
 }
}

 Please help me to write test class.....

 

Thanks in advance......

  • February 12, 2013
  • Like
  • 0

My developer edition account has begun to sport a logo at the top stating "Subscribe Now! 23 days remaining". This is a little unnerving (I don't want the account to disappear) ... but clicking on it produces an internal server error. Any idea what this is or who I should contact about it?

Thanks,
Scot

  • June 18, 2004
  • Like
  • 0