• pcon
  • ALL STAR
  • 15205 Points
  • Member since 2011
  • Principal Software Engineer
  • Red Hat


Badges

  • Chatter
    Feed
  • 446
    Best Answers
  • 0
    Likes Received
  • 10
    Likes Given
  • 1
    Questions
  • 3207
    Replies
We have clients that access Salesforce API to write data and read data using the salesforce standard APIs. How do monitor the traffic, logs for these API calls? I'm also looking for ways to know the traffic by username or clientId
  • September 24, 2019
  • Like
  • 0
ublic class MyUploadStatementController {
    public String LeadsId {get;set;}
    public List<Attachment> docs{get;set;}
    public List<Attachment> insertedDocs{get;set;}
    public string attNames{get;set;}
    
    public MyUploadStatementController(){
        LeadsId = ApexPages.currentPage().getParameters().get('Id');
        system.debug('LeadId -->'+LeadsId);
        attNames = '';
        docs = new List<Attachment>();
        insertedDocs = new List<Attachment>();
    }
    
    public pagereference prepareSFDocuments(){           
        try{     
            //system.debug('**'+leadobj);
            attNames = attNames.removeEnd('\n');
            List<string> atts = attNames.split('\n');        
            
            //sfDocs = new List<SFDocument>();       
            for(String attName:atts){
                List<string> nameSplit = attName.split('\t');
                system.debug('Attname just '+attName);
                Attachment doc = new Attachment(Name=nameSplit[0], ParentId=LeadsId );
                docs.add(doc);
                system.debug('Debug Docs '+docs);
                //SFDocument d = new SFDocument(nameSplit[0], leadobj.id,Long.valueOf(nameSplit[1]),getDisplaySize(Long.valueOf(nameSplit[1])));
                //sfDocs.add(d);
            }
            
            System.debug('Attachment List-->'+docs);
            //Integer.valueOf('***'+docs.size());
        }catch(Exception ex){ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage()+'\n'+ex.getStackTraceString());
                             ApexPages.addMessage(myMsg);}
        return null;
    }
    
    public pagereference updateDocs(){
        //Integer.valueof('pare'+parentId);
        try{
            system.debug('Dropbox docs '+docs);
            for(Attachment da : docs){
                system.debug('Inside For Loop DropBox '+da);
                da.ParentId = LeadsId;
            }
            if(docs.size()>0)
                insert docs;
            insertedDocs.addAll(docs);
            docs = new List<Attachment>();
        }catch(Exception ex){
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
                             ApexPages.addMessage(myMsg);
        }
        return null;
    }
    
    @RemoteAction
    public static void UploadAttachment(String LeadId){
        
    }
}
I'm integrating Salesforce to other application(Ruby). I'm able to sync data both ways. But while updating data from Application to salesforce, every time i have to provide access token. So is there any way to get a permanent Access token?
Thank You..
Hi.

I'm new in Salesforce.

I create a sandbox and i tried to move my change (some new fields and put that foelds in account page). I create the chage set, y validate it, i implement it and all it's ok.

I review the Account object and my changes are applied. I review the account page and my change are applied. BUT i enter in the application and I don't see my changes!!! What is that I'm doing wrong?

PD - I move from one sandbox to another sandbox

Thanks in advance

All i need to get response  from sap application through the rest callouts . When i tried to use the Chrome APP 'Advanced Rest Client' and  postman have passed the appropriate URL and Content  with  GET AND POST method I was able to retrieve the values from local server database.
For EG : If i pass request  92126 then i was able to get response  'SAN DIEGO' which is correct.

Here is the link (https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo?hl=en-US)for Advanced REST Client.

1)i had created a remotesite setting 
2) When i created this REST class in SAlesforce and tried invoking the End Point then its throwing this error.

System.HttpResponse[Status=Service Unavailable, StatusCode=503]
# as the web api url  which is provided to us is in local sql  server i.e  hosted in private,  as we know  THAT salesforce for making callouts the urls must be EXPOSED  in public... bt the url is in private only for the security reasons not hosted in public..we should achieve iT COMPULSARY THERE WILL A ANY SOLUTION FOR ALL THE QUESTIONS   .. IS any way is there to acheive it ??  ..what changeS  should be done in salesforce or LOCAL server to communicate to eachother ..and allows to make the callout ???
What this error?

KeyManagerFactory not initialized
Error is in expression '{!accessToken}' in component <apex:page> in page document407_access_token: Class.checkingAccessToken.accessToken: line 50, column 1
An unexpected error has occurred. Your development organization has been notified.


What I did so far?
1. Created a vf page and controller
2. Controller contains http callouts.
3. Custom link to call this VF page.
4. When I click the link. its showing the above error
How to parse the response 
 <?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse xmlns:ex="http://ws.apache.org/xmlrpc/namespaces/extensions"><params><param><value><array><data><value><boolean>1</boolean></value><value>OK</value></data></array></value></param></params></methodResponse>

I wanted to write logic based on Boolean value in response but am unable to parse this one 
 
I'm in the "Salesforce Connect" module and trying to complete the set up to integrate a sample as requested:

"As part of this module, you integrate sample order data with the existing account data in your Salesforce Developer Edition. To go through the steps, you need to install a test package that configures the necessary schema on the account object, creates a Customer ID field, and assigns a value for Customer ID to each account.

Follow these steps to install the package.
Open a browser, and click here to start the installation.
Select Install for Admins Only.
Click Install."

When I click on the "click here" it takes me to a SFDC log in page, where I try to select my Dev Org login in username and password (from my production enviro).  It does not work and even after trying to reset my password I never receive an email and cannot log in.

Please help! 
Thanks,
Rochelle
Our group is changing over some code in response to a change in instance.  This code follows the methods outlined in the quick start guide. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart.htm  At the moment, we acquire an auth token by hitting the login instance, and then query our numbered instance for data.

To prevent having to keep changing the configuration parameter to point to our new ID when it changes, is it possible to still query the login instance to get data back?  I've tested on my end without any luck, but I figured I'd check to see if I'm missing anything.

We're exploring setting up a custom domain, which will likely  be our alternative, but the easier solution would be better.

 
Hello - I created a pre-chat survey for my new verions of Live Agent, but in testing, clicking the link to chat now forces a login. How do I serve up the questions without logging in? Without the pre-chat quesitons, Live Agent launches just fine without a need to login and launching the visualforce page works. Any suggestions would be much appreciated! Thank you in advance!
 
I am attempting to parse MatterMark's API, but I am planning to do so selectively, picking only the value pairs that are relevant. The example JSON response is available to be viewed in MatterMark's documentation (here).

Here's my Wrapper:
 
public class MMarkWrapper {
    public class mmark_company_profile {
        public string name {get;set;}
        public string description {get;set;}
        public string employees {get;set;}
        public string employees_6_months_ago {get;set;}
        public string last_funding_amount {get;set;}
        public string last_funding_date {get;set;}
        public string country {get;set;}
        public string total_funding {get;set;}
        public string acquired_by {get;set;}
        public List<mmark_funding_round> mmark_funding_rounds {get;set;}
        
    }
    public class mmark_funding_round {
        public string amount {get;set;}
        public string transaction_currency {get;set;}
        public string series {get;set;}
        public string funding_date {get;set;}
        public string investors {get;set;}
        
    }
    
    public List<mmark_company_profile> mmark_company_profile_list {get; set;}

}

And the Parser:
 
public class MMarkParser {
    public MMarkWrapper wrapper {
        get;
        set;
    }
    
    public void parse() {
        
        //request class
        HTTPRequest request = new HTTPRequest();
        request.setEndpoint(Label.MatterMarkAPI+'/domains/'+ 'marketinvoice.com' +'/companies?key=' +'c878f447941828d91d53ffbebae068cdb7624fb257cca98e2672e8148e039c1c');  
        request.setMethod('GET');
        
        //response class
        HTTP h = new HTTP();
        HTTPResponse response = h.send(request); 
        
        
        wrapper = (MMarkWrapper) JSON.deserialize(response.getBody(), MMarkWrapper.class);
        System.debug(wrapper);
        
    }
    
}

I am trying to get it displayed on this page, but all I am getting is a blank page...
 
<apex:page controller="MMarkParser">
    <apex:form >
        <apex:pageBlock title="MMarkParserResponse">
            <apex:pageBlockButtons >
                <apex:commandButton value="submit" action="{!parse}" reRender="mmark_company_profile"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection id="mmark_company_profile" columns="1">
                <apex:repeat value="{!wrapper.mmark_company_profile_list}" var="mmark_company_profile">
                    <apex:pageBlockSection columns="2">
                        <apex:facet name="header">Company {!mmark_company_profile.name}</apex:facet>
                        <apex:pageBlockSectionItem >
                            <apex:outputLabel value="Description" for="description" />
                            <apex:outputText value="{!mmark_company_profile.description}" id="description" />
                        </apex:pageBlockSectionItem>
                        <apex:pageBlockSectionItem >
                            <apex:outputLabel value="Employees" for="employees" />
                            <apex:outputText value="{!mmark_company_profile.employees}" id="employees" />
                        </apex:pageBlockSectionItem>
                    </apex:pageBlockSection>
                    <apex:pageBlockSection columns="1">
                        <apex:facet name="header">Funding {!mmark_company_profile.name} Series</apex:facet>
                        <apex:pageBlockTable value="{!mmark_company_profile.mmark_funding_rounds}" var="item" id="mmark_funding_rounds">
                            <apex:column value="{!item.amount}" headerValue="Amount" />
                            <apex:column value="{!item.transaction_currency}" headerValue="Transaction Currency" />
                            <apex:column value="{!item.series}" headerValue="Series" />
                            <apex:column value="{!item.funding_date}" headerValue="Funding Date" />
                        </apex:pageBlockTable>
                    </apex:pageBlockSection>
                </apex:repeat>
            </apex:pageBlockSection>
        </apex:pageBlock> 
    </apex:form>
</apex:page>

I've been trying to debug it with no success, any ideas why this may be not working?
Hello,

I'm new to Apex and SOQl. I have two objects; Accounts (Master object) and Appointments (Child object) and I'm trying to write a trigger (With SOQL query) that returns the most recent appointment date (Max date) per account on a custom field (Most_Recent_Appointment_Date__c) that is built on the account (Persons account) object:
 
Object #1: (Appointments)
 
Appointment ID  Account ID,   Name,  Apt Date,   Weight....etc.
---------------------------------------------------------------------------------
Apts_001112       001                John      01/01/2017     160
Apts_001114       002                Nicole   11/05/2016      180
Apts_001113       001                John      04/05/2017     175
Apts_001115       003                Mark     05/05/2017      190   
Apts_001116       002                Nicole   12/15/2016      200
 
Object #2: (Accounts)
 
 ID,      Name....etc.
--------------------------
 001     John    
 002     Nicole   
 001     John     
 003     Mark      
 002     Nicole
-----------------------------------------------------------------------------------------------------------------------------------------------------
 
Trigger MostRecentAppointmentDate on Accounts (After update, after insert) {

List <Accounts> AccountsList = new List<Accounts>();

Set<id> AcntsID = new Set<id>();
    for(Account a:trigger.new) {
 AcntsID.add(a.ID);
}

For (Appointments Apts : Trigger.new) {
Appointments MostRecentApts = [SELECT Scheduled_date__c, Weight__c, Patient__c
                                            FROM Appointments__c
                                            WHERE Patients__c IN:AcntsID
                                            GROUP BY Patients__c
                                            ORDER BY Scheduled_date__c DESC
                                            LIMIT 1];

Set Most_Recent_Appointment_Date__c = MostRecentApts

}
Hi all

what is the apex code for sms magic

Is it possible to set the parent id on an asset other than using the constructor method?  I need to set the parent id for an asset in a trigger method.  This code does not work:

a.parentId = parentAsset.id;

Results in:  Save error: Invalid field parentId for SObject Asset

My user does have access to the object and the parent field.  I can set the parent id using the constructor method:

Asset a = new Asset(name='test component with parent',
                    hin__c = 'CRC10890L516',
                    recordtype =bc,
                    dealer_key__c = '43536.001',
                    dealer_brand_key__c = '43536.001CL',
                    parentId = '02i54000000hS4aAAE') 

Unfortunately that will not work for my use case.

Ideas?
 

Hi, 

How can I align the following to the left of the page, its a pdf. Screenshot of the issue
I want to shift all the text to the left with this formet, here is the section of code for this- 
<tr>
                <td colspan="4"> </td>
            </tr>
            <tr>
                <td colspan="4" style="font-weight: bold; border-bottom-style: solid; border-bottom-width: thick;
                    border-bottom-color: #30b55a;">
                    Campaign Information </td>
            </tr>
              
                    <tr>
                            <td style="color: #808080; border-right-style: solid; border-right-width: thin;
                                border-right-color: #30b55a;">
                                Campaign Name </td>
                            <td align="left">
                                {!Opportunity.Name} </td>
                        </tr>
                    <tr>                    
                            <td align="right" style="color: #808080; border-right-style: solid; border-right-width: thin;
                                border-right-color: #30b55a;">
                                Brand </td>
                            <td style="text-align:left">
                                {!Opportunity.Account.Name} </td>
                        </tr>
                       
            <tr>
                <td align="right" style="color: #808080; border-right-style: solid; border-right-width: thin;
                    border-right-color: #30b55a;">
                    Start Date
                </td>
                    <td style="font-weight: normal">
                        <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                        <apex:param value="{!Opportunity.Campaign_Start_Date__c}" /> 
                        </apex:outputText>
                    </td>
            </tr>
            
            <tr>
                <td align="right" style="color: #808080; border-right-style: solid; border-right-width: thin;
                    border-right-color: #30b55a;">
                    End Date
                </td>
                    <td style="font-weight: normal">
                        <apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                            <apex:param value="{!Opportunity.Campaign_End_Date__c}" /> 
                        </apex:outputText>
                    </td>
            </tr>
            
             <tr>
                <td align="right" style="color: #808080; border-right-style: solid; border-right-width: thin;
                    border-right-color: #30b55a;">
                    Duration 
                </td>
                    <td style="font-weight: normal">
                        <apex:outputText value="{0,number,0}">
                            <apex:param value="{!Opportunity.Campaign_Duration__c}"/>
                        </apex:outputText> 
                    </td>
            </tr>

Please help out. Thank you !
I'm receiving a JSON string from another system in the format below. These records already exist in Salesforce. I want to only query these records in salesforce, set a boolean field to false in all of them and update.
{ "bacctList" : 
     [{
       "RC_Account_No__c" : "RC-2",
       "A_c_Number__c" : "111",
       "Bank_code__c" : "250655"
      },
      {
       "RC_Account_No__c" : "RC-1",
       "A_c_Number__c" : "222",
       "Bank_code__c" : "198765"
      }]
   }

The below code works fine, the issue is it's not bulkified.
@RestResource(urlMapping='/dosystem/bankaccounts/*')
global with sharing class BankAccountWebservice{
   
 @HttpPatch
    global static BankAccountWrapper doPatch(List<Bank_Account__c> bacctList) {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        BankAccountWrapper response = new BankAccountWrapper();
        
        List<Bank_Account__c> bankAccountsToUpdate= new List<Bank_Account__c>();

        for(integer i=0; i<bacctList.size(); i++){
            List<Bank_Account__c> ac = [SELECT Debit_Order_A_c__c,A_c_Number__c,Bank_code__c,RC_Account_No__c  
            FROM Bank_Account__c 
            WHERE (RC_Account_No__c =: bacctList[i].RC_Account_No__c AND  A_c_Number__c =: bacctList[i].A_c_Number__c AND Bank_code__c =: bacctList[i].Bank_code__c)];
            
            for(integer j=0; j< ac.size(); j++){
                ac[j].Debit_Order_A_c__c = false;       
                bankAccountsToUpdate.add(ac[j]);
             }    
        }
        
        try {
            update bankAccountsToUpdate;

            response.bacctList = bankAccountsToUpdate;
            response.status = 'Success';
            response.message = bacctList.size()+' Records Updated successfully';
        }
        catch(Exception exc) {
            res.StatusCode = 500;
            response.bacctList = null;
            response.status = 'Error';
            response.message = 'Your request failed with the following error: ' + exc.getMessage();
        }
        
        return response;
    }
    
    global class BankAccountWrapper {
        public List<Bank_Account__c> bacctList;
        public String status;
        public String message;
        
        public BankAccountWrapper(){
            bacctList = new List<Bank_Account__c>();
        }
    }   
}

The problem is the FOR loop. I tried using the IN clause in SOQL but the problem is im not getting the ID in the JSON string.
List<Bank_Account__c> bankAccountsToUpdate= new List<Bank_Account__c>();
        integer updatedRecordCount=0;
        
        List<Bank_Account__c> ac= [select Name,Debit_Order_A_c__c,A_c_Number__c,Bank_code__c From Bank_Account__c where Id IN : bacctList];
                    
		for(integer i=0; i<ac.size(); i++){                                    
			ac[i].Debit_Order_A_c__c = false;       
			bankAccountsToUpdate.add(ac[i]);
			updatedRecordCount++;                 
		
		}

PLEASE HELP.

 
Hi folks,

I've been powering my way through Trailhead recently, I've now gone through all of the Admin (just looking through the Advanced trail currently) and also want to gain a better understanding of Programmatic side/more Development focused features.

It probably helps if I state that I've worked in Sales for most of my career so  stepping into the technical realm is a fairly big jump for me! Can anyone advise:

- Would it be best to cotinue with the advanced admin trail *before* moving onto the 'Developer - Beginner' trail, or is it worth learning the programmatic side along with declarative before tackling the final trail?

- Is there a good place to start learning APEX? I have a very basic understanding of the code from what i've managed to gleam through Trailhead, but it seems like a 'JAVA/C# for Dummies' book or something similar may be a good idea?

If anyone could spare 2 mins to give me some advice I'd really appreciate it!

Thanks in advance

Jack
Hi guys,

I'm trying to setup email to case on an org but I keep running into this issue, it's driving me insane as I had this set up already using the exact same email address and it worked fine. Can anyone help me figure out what the below error message means? I have no idea what picklist is causing this to happen all of a sudden. 

INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST : bad value for restricted picklist field: No

Last night, we started having tests fail in our dev environment.  We have the following methods (shortened)

 



public static void updateTargetDate(...) {
     Set<Id> futureIds = new Set<Id>();
     ...
     // Add Ids
     ...
     if (!futureIds.isEmpty()) {
          updateTargetDateFromMilestone(futureIds);
     }
}

@future
public static void updateTargetDateFromMilestone(Set<Id> caseIds) {
     ...
}

 

Yesterday at noon (we run all tests in dev at noon and midnight) all the tests were running without error.  At midnight most of our tests were failing with the following error:

 

System.TypeException: Invalid conversion from runtime type SET<String> to SET<Id>

 

with a referral to the method of updateTargetDateFromMilestone(Set<Id> caseIds).  This file has not been updated since June 24th 2011.

 

So the question is, has anyone else seen this error crop up?  I know that in Apex Strings and Id "should" be interchangeable, however, it doesn't matter in this case since the Set being made is of type Id and the Set parameter for the calling method is of type Id.

  • September 30, 2011
  • Like
  • 0
                String prdName=(String)prodByNumbe.get('Name');
                String prdSrlNum=(String)prodByNumbe.get('value');
                String orderItemQuer;
                 system.debug('OrderItem' +orderItemQuer);
                 if(listOrderItem.size()==0)
                  {orderItemQuer='SELECT Id FROM OrderItem WHERE OrderId='+'\''+inputMap.get('ContextId')+'\''+' AND Product2.Name='+'\''+prdName+'\'';}
                 else{orderItemQuer='SELECT Id FROM OrderItem WHERE OrderId='+'\''+inputMap.get('ContextId')+'\''+' AND Product2.Name='+'\''+prdName+'\''+' AND Id !='+'\''+listOrderItems[0].Id+'\'';}
                  listOrderItems.clear();
                  listOrderItems=Database.query(orderItemQuer);
                  listOrderItem.add(new OrderItem(Id=listOrderItems[0].Id,OrderId=(String)inputMap.get('ContextId'),Tet_Serial_Number__c=prdSrlNum));
                 }update listOrderItem;}

I am currently calling this class with a Process Builder. But I can't see the results of the code following the @Future statement. I've looked through debug logs as well as in the Apex Jobs list and cannot find them. Am I unable to see them run because they are following a @Future statement ? Or is it because it's a second method in a class being called by a Process Builder ? Or is there another way I need to try and see it run ? 

Should I be calling the methods individually from a trigger ?

 

public class UpdateContactPCRController {

    @InvocableMethod
    public static String  updateContact(String recordId){        
       
        String contactId = '';       
        
        List<Contact> contactToBeupdate = new List<Contact>();        
        
        if(String.isNotBlank(recordId)){            
            
            List<Program_Contact_Role__c> programContacList = [SELECT Id,Contact__c,Program_Name__c FROM Program_Contact_Role__c WHERE Id =:recordId AND Contact__c != null];
            contactId = programContacList[0].Contact__c;
            
            if(String.isNotBlank(contactId)){
                
                contactToBeupdate = [Select Id,Pardot_Action_Trigger__c,PCR_Register_Button_Link__c,PCR_URL_for_UI__c FROM Contact Where Id =: contactId Limit 1];                
                
                contactToBeupdate[0].Program_Contact_Role_Id__c = recordId;
            }
			List<Program_Communication_Recipients__c> programCommunicationRecs = [Select Id,Name,
					  Program_Communication__r.Program__r.Buyer__r.Name,Receipient__c,                
								  From Program_Communication_Recipients__c Where 
											   Program_Communication__r.Program__c =: programContacList[0].Program_Name__c AND 
											   Receipient__c =: programContacList[0].Id];                                           
					
	
			contactToBeupdate[0].PCR_Welcome_Message__c = String.valueOf(programCommunicationRecs[0].Program_Communication__r.Welcome_Message__c);                                                    
			
			if(contactToBeupdate.size() > 0){
				update contactToBeupdate;  
			}
			pardotCallout(contactToBeupdate[0].Id);
    
			return 'Updated Successfully';
		}
		else{
			return 'some message';
		}
    }
	
	@future(callout=true) 
	public static void pardotCallout(String contactId) {
		String returnedResponseFromPardot = Http_Utility_Pardot.pardotCreateProspect(new Set<Id> {contactId});
		// new treatment here with the returned value included DML operations.
		// further logic if any based on the response you get from Pardot
	}
}
trigger immediate_response on pba__Listing__c (before delete,after insert,before update) {
 
    String api_status = 'trigger' ;
    String url = 'https://fine-residential.com/app_sf/sf_endpt.php';

    String body;

  if(trigger.isDelete ){
 
  api_status = 'DELETED'; 
       
 for (pba__Listing__c acc : Trigger.old) {
              
              body = 'id='+acc.Id+'&method='+api_status+'&inbound_initiative_id=1';

              HTTPRequestSender.sendHTTPRequest(url, body);
       }       
 
      
  }else{   
      
//if((trigger.isInsert || trigger.isUpdate) ){
        if(trigger.isBefore && trigger.isUpdate){
         
         api_status = 'UPDATE';
         
        }
         
        if(trigger.isInsert ){
         
         api_status = 'INSERT';
         
        }
            
         
         for (pba__Listing__c acc : Trigger.new) {
                      
                      body = 'id='+acc.Id+'&method='+api_status+'&inbound_initiative_id=1';
        
                      HTTPRequestSender.sendHTTPRequest(url, body);
                      
                      
                  if(acc.api_modified_date__c  !=acc.api_modified_date_2__c )
                   acc.api_modified_date__c   = acc.lastModifiedDate;
                   else
                   acc.api_modified_date_2__c   = acc.lastModifiedDate;
                                     
                                     
                                     
                                     
               }       
  }//end of else if not isdeleted
 
 }
Help! I'm new to coding and am probably doing this all wrong. How could I optimize the code block below.

What I need to acheive is calculating the difference in business hours that a lead spends in each lead stage from New,  Working, Nurturing, and lastly, Qualified. I wrote the trigger which works but is incomplete (needs to prevent negative values)

I want the trigger (before update) to calls a class & method that does all of this whenever a lead record is updated, but I don't know how. How do I package all of the logic into an apex class that I can call with this trigger?
 
trigger LeadTracking on Lead (before update) {

    //Selecting default business hours (BH) record
    BusinessHours defaultBH = [SELECT Id FROM BusinessHours WHERE IsDefault = true Limit 1];
	//Making sure BH record exists
    if(defaultBH != NULL){
        for(Lead myLead : trigger.new ){
            
            //CALCULATE NEW calculateNewDateTime()
            ////Making sure that New Date Time and Working Date Time are not null
            if(myLead.New_Date_Time__c != NULL ) {
             	if(myLead.Working_Date_Time__c != NULL) {
				//For BH method we assign (BH record id, start time field, end time field)
				decimal result = BusinessHours.diff(defaultBH.Id, myLead.New_Date_Time__c, myLead.Working_Date_Time__c );
				//Result from the method is divided by 60*60*100 (milliseconds to be then converted into hours)
				Decimal resultingHours = result/(60*60*1000);
				//Populating result into our custom field & setting number of decimals
				myLead.New_Business_Hours_2__c = resultingHours.setScale(2); 
            
            //calculates difference between New Date Time and Nurturing Date Time
            	} else if (myLead.New_Date_Time__c != NULL && myLead.Working_Date_Time__c == NULL && myLead.Nurturing_Date_Time__c != NULL) {
                decimal result = BusinessHours.diff(defaultBH.Id, myLead.New_Date_Time__c, myLead.Nurturing_Date_Time__c );
				Decimal resultingHours = result/(60*60*1000);
				myLead.New_Business_Hours_2__c = resultingHours.setScale(2);  
            
            //Calculates difference between New Date Time and Qualified
            	} else if (myLead.New_Date_Time__c != NULL && myLead.Nurturing_Date_Time__c == NULL && myLead.Working_Date_Time__c == NULL && myLead.Qualified_Date_Time__c != NULL) {
                decimal result = BusinessHours.diff(defaultBH.Id, myLead.New_Date_Time__c, myLead.Qualified_Date_Time__c );
				Decimal resultingHours = result/(60*60*1000);
				myLead.New_Business_Hours_2__c = resultingHours.setScale(2);
            
            //if New Date Time is not null but all the other Date Times are Null - then have the calculation be made from NOW()
            	} else if (myLead.New_Date_Time__c != Null && myLead.Nurturing_Date_Time__c == NULL && myLead.Working_Date_Time__c == NULL && myLead.Qualified_Date_Time__c == NULL) {
                decimal result = BusinessHours.diff(defaultBH.Id, myLead.New_Date_Time__c, datetime.now());
				Decimal resultingHours = result/(60*60*1000);
				myLead.New_Business_Hours_2__c = resultingHours.setScale(2);
            	} //else //if (myLead.New_Date_Time__c == NULL) 
            	//{ myLead.New_Business_Hours_2__c = NULL;
				//}
			}
                
            
            //CALCULATE WORKING
            //calculates difference between working and nurturing if both are not null
            if (myLead.Working_Date_Time__c != Null ){
                if(myLead.Nurturing_Date_Time__c != Null) {
                decimal result = BusinessHours.diff(defaultBH.Id, myLead.Working_Date_Time__c, myLead.Nurturing_Date_Time__c);
				Decimal resultingHours = result/(60*60*1000);
				myLead.Working_Business_Hours_2__c = resultingHours.setScale(2);
            //calculates difference between working and Qualified if Nurturing is null but Working and Qualified are not null   
            } else if (myLead.Working_Date_Time__c != Null && myLead.Qualified_Date_Time__c != Null && myLead.Nurturing_Date_Time__c == NULL) {
				decimal result = BusinessHours.diff(defaultBH.Id, myLead.Working_Date_Time__c, myLead.Qualified_Date_Time__c);
				Decimal resultingHours = result/(60*60*1000);
				myLead.Working_Business_Hours_2__c = resultingHours.setScale(2);
            //calculates difference between working and Now() if working is not null but nurturing and qualified are 
            } else if (myLead.Working_Date_Time__c != Null && myLead.Nurturing_Date_Time__c == Null && myLead.Qualified_Date_Time__c == Null) {
                decimal result = BusinessHours.diff(defaultBH.Id, myLead.Working_Date_Time__c, datetime.now());
				Decimal resultingHours = result/(60*60*1000);
				myLead.Working_Business_Hours_2__c = resultingHours.setScale(2);
            } //else // (myLead.Working_Date_Time__c == Null) 
            	//{myLead.Working_Business_Hours_2__c = Null; 
                //}
            }
            
            //CALCULATE NURTURING    
            //calculates difference between nurturing and qualified if both are not null
            if (myLead.Nurturing_Date_Time__c != Null) {
                if(myLead.Qualified_Date_Time__c != Null) {
            	decimal result = BusinessHours.diff(defaultBH.Id, myLead.Nurturing_Date_Time__c, myLead.Qualified_Date_Time__c);
				Decimal resultingHours = result/(60*60*1000);
				myLead.Nurturing_Business_Hours_2__c = resultingHours.setScale(2);
            //calculates difference between nurturing and Now() if qualified is null
            	} else if (myLead.Nurturing_Date_Time__c != Null && myLead.Qualified_Date_Time__c == Null) {
                decimal result = BusinessHours.diff(defaultBH.Id, myLead.Nurturing_Date_Time__c, datetime.now());
				Decimal resultingHours = result/(60*60*1000);
				myLead.Nurturing_Business_Hours_2__c = resultingHours.setScale(2);
           		} //else //(myLead.Nurturing_Date_Time__c == NULL) 
                //{myLead.Nurturing_Business_Hours_2__c = 0.00;
            	//}  
        	}
            //if new, working or nurturing date times are null, there is no calculation of business hours for it
            if (myLead.New_Date_Time__c == NULL) {
                myLead.New_Business_Hours_2__c = NULL;
            }
            if (myLead.Working_Date_Time__c == NULL) {
                myLead.Working_Business_Hours_2__c = NULL;
            }
            if (myLead.Nurturing_Date_Time__c == NULL){
                myLead.Nurturing_Business_Hours_2__c = NULL;
            }
            
    	}    
	}
}



 
 
Hi there, 

I did a test class for my controller but I can't find my error, could you please help me? I'll give you an example of my controller and my test class.

Controller : 

public with sharing class AdvancedAnalyseController {
    @AuraEnabled
    public static void cloneThisAnalyse(Id analyseId, Integer nombreA) {
        String queryAnalyse = 'SELECT Id, ';
        queryAnalyse += buildCustomFieldsQuery(Analyse__c.getSObjectType());
        queryAnalyse = queryAnalyse.removeEnd(', ') + ' FROM Analyse__c WHERE Id = \'' + analyseId + '\'';
        mDebugUntruncated(queryAnalyse);
        List<Analyse__c> aList = Database.query(queryAnalyse);
        if (aList.isEmpty()) {
            AuraHandledException ex = new AuraHandledException('NO_ANALYSE');
            ex.setMessage('NO_ANALYSE');
            throw ex;
        }
        List<Analyse__c> analyseClone = new List<Analyse__c>();
         for (Integer i=0; i<nombreA; i++) {
            Analyse__c newAnalyse = aList.get(0).clone();
            newAnalyse.Clone__c = true;
            analyseClone.add(newAnalyse);
         }
        insert analyseClone;
        
    }
    @TestVisible
    private static String buildAllFieldsQuery(Schema.SObjectType targetSObjectType) {
        Map<String, Schema.SObjectField> fieldMap = targetSObjectType.getDescribe().fields.getMap();
        String query = '';
        for (String key : fieldMap.keySet()) {
            Schema.SObjectField field = fieldMap.get(key);
            Schema.DescribeFieldResult result = field.getDescribe();
            query += result.getName() + ', ';
        }
        return query.removeEnd(', ');
    }
    @TestVisible
    private static String buildCustomFieldsQuery(Schema.SObjectType targetSObjectType) {
        Map<String, Schema.SObjectField> fieldMap = targetSObjectType.getDescribe().fields.getMap();
        String query = '';
        for (String key : fieldMap.keySet()) {
            Schema.SObjectField field = fieldMap.get(key);
            Schema.DescribeFieldResult result = field.getDescribe();
            if (result.isCustom()) {
                query += result.getName() + ', ';
            }
        }
        return query.removeEnd(', ');
    }
    public static void mDebugUntruncated(String sMsg) {
        for (Integer i = 0; i < sMsg.length(); i=i+300) {
            Integer iEffectiveEnd = (i+300 > (sMsg.length()-1) ? sMsg.length()-1 : i+300);
            System.debug(sMsg.substring(i,iEffectiveEnd));
        }
    }
}

Test class : 

@isTest
private class AdvancedAnalyseControllerTest {
    @TestSetup
    static void makeData() {
        Account acc = new Account (Name='Test_Account', Phone='0123456789');
        insert acc;
        PAD.ApexForcedBypass.remove('AP001');
        Agence__c ag = new Agence__c(Code_agence__c = 'IDF',Code_agence_telephone__c = '98254');
        insert ag;
        Bulle__c bulle = new Bulle__c();
        bulle.Name = 'Bulle de test';
        bulle.Date_cr_ation__c = Date.today();
        insert bulle;
        opportunity opp = new Opportunity(Name='Test_Opp', Code_agence__c='IDF', StageName='Prospection', accountid=acc.Id,
                                            CloseDate=Date.today() , Site_Ville__c='Paris');
        opp.Bulle__c = bulle.Id;
        opp.Agence_code__c = ag.Id;
        insert opp;
        Affaire__c affaire1 = new Affaire__c();
        affaire1.Name = 'Affaire test 1';
        affaire1.Bulle__c = bulle.Id;
        affaire1.Agence__c = ag.Id;
        affaire1.Opportunit__c = opp.Id;
        insert affaire1;
        Chantier__c chantier = new Chantier__c();
        chantier.Name = 'Chantier Test';
        chantier.Compte__c = acc.Id;
        chantier.Opportunite__c = opp.Id;
        chantier.Code_agence__c = ag.Id;
        chantier.Bulle_del__c = bulle.Id;
        chantier.Affaire__c = affaire1.Id;
        insert chantier;
        Analyse__c analyse = new Analyse__c();
        analyse.Etat__c = 'Création = bon de commande';
        analyse.Nature__c = 'Mesure environnementale';
        analyse.Chantier__c = chantier.Id;
        insert analyse;
    }
    @isTest
    static void testmDebugisOK() {
        AdvancedAnalyseController.mDebugUntruncated('test');
    }
    @isTest
    static void testbuildFullListisOk() {
        String fieldList = AdvancedAnalyseController.buildAllFieldsQuery(Analyse__c.getSObjectType());
        System.assertNotEquals(null, fieldList);
    }
    @isTest
    static void testbuildCustomListisOk() {
        String fieldList = AdvancedAnalyseController.buildCustomFieldsQuery(Analyse__c.getSObjectType());
        System.assertNotEquals(null, fieldList);
    }
    @isTest
    static void testCloneAnalyseisOk() {
        PAD.ApexForcedBypass.remove('AP001');
        Analyse__c analyse = [SELECT Id, Chantier__c FROM Analyse__c];
        Test.startTest();
        List<Analyse__c> analyseClone = AdvancedAnalyseController.cloneThisAnalyse();
        for (Integer i=0; i<10; i++) {
            Analyse__c newAnalyse = analyse.clone();
            newAnalyse.Clone__c = true;
            analyseClone.add(newAnalyse);
         }
        Test.stopTest();
        List<Analyse__c> analyses = [SELECT Id FROM Analyse__c];
        System.assertEquals(1, analyses.size());
    }
    @isTest
    static void testCloneAnalyseisNOK() {
        PAD.ApexForcedBypass.remove('AP001');
        Analyse__c analyse = [SELECT Id FROM Analyse__c];
        delete analyse;
        Test.startTest();
        try {
        List<Analyse__c> analyseClone = AdvancedAnalyseController.cloneThisAnalyse();
            for (Integer i=0; i>10; i++) {
            Analyse__c newAnalyse = analyse.clone();
            newAnalyse.Clone__c = true;
            analyseClone.add(newAnalyse);
         }
        } catch (AuraHandledException ex) {
            System.assertEquals('NO_ANALYSE', ex.getMessage());
            return;
        }
        Test.stopTest();
        System.assert(false);
    }
}
We have clients that access Salesforce API to write data and read data using the salesforce standard APIs. How do monitor the traffic, logs for these API calls? I'm also looking for ways to know the traffic by username or clientId
  • September 24, 2019
  • Like
  • 0
Hello All,
I am learning on Asynchronous Apex Trigger, recently introduced on summer release '19. I have created a custom object Event_testing and added it to Change Data capture and created a new trigger, that has a debug statement to capture the trigger.new values. However, The custom event trigger is not even called after the insert operation. 
Any advise would be much appreciated. 
trigger Testing_tgr1 on Event_testing__ChangeEvent (after insert) {
    for(Event_testing__ChangeEvent c : trigger.new){
        system.debug('C is '+c);
        
    }
}

Thank you.
Regards, 
Sujendran. 
​​​​​​​
ublic class MyUploadStatementController {
    public String LeadsId {get;set;}
    public List<Attachment> docs{get;set;}
    public List<Attachment> insertedDocs{get;set;}
    public string attNames{get;set;}
    
    public MyUploadStatementController(){
        LeadsId = ApexPages.currentPage().getParameters().get('Id');
        system.debug('LeadId -->'+LeadsId);
        attNames = '';
        docs = new List<Attachment>();
        insertedDocs = new List<Attachment>();
    }
    
    public pagereference prepareSFDocuments(){           
        try{     
            //system.debug('**'+leadobj);
            attNames = attNames.removeEnd('\n');
            List<string> atts = attNames.split('\n');        
            
            //sfDocs = new List<SFDocument>();       
            for(String attName:atts){
                List<string> nameSplit = attName.split('\t');
                system.debug('Attname just '+attName);
                Attachment doc = new Attachment(Name=nameSplit[0], ParentId=LeadsId );
                docs.add(doc);
                system.debug('Debug Docs '+docs);
                //SFDocument d = new SFDocument(nameSplit[0], leadobj.id,Long.valueOf(nameSplit[1]),getDisplaySize(Long.valueOf(nameSplit[1])));
                //sfDocs.add(d);
            }
            
            System.debug('Attachment List-->'+docs);
            //Integer.valueOf('***'+docs.size());
        }catch(Exception ex){ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage()+'\n'+ex.getStackTraceString());
                             ApexPages.addMessage(myMsg);}
        return null;
    }
    
    public pagereference updateDocs(){
        //Integer.valueof('pare'+parentId);
        try{
            system.debug('Dropbox docs '+docs);
            for(Attachment da : docs){
                system.debug('Inside For Loop DropBox '+da);
                da.ParentId = LeadsId;
            }
            if(docs.size()>0)
                insert docs;
            insertedDocs.addAll(docs);
            docs = new List<Attachment>();
        }catch(Exception ex){
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
                             ApexPages.addMessage(myMsg);
        }
        return null;
    }
    
    @RemoteAction
    public static void UploadAttachment(String LeadId){
        
    }
}
1. Create a SSO app with enable SAML .
2. When I configure a url "http://example.com/SAML/ACS" for ACS URL, actually it will be changed to "https://example.com/SAML/ACS" when I sign in my own application by salesforce.
3. But the locahost is rigid. The "http://localhost/SAML/ACS" won't be changed.
I want to know whether it is a policy. BTW, there is no document for it.
HI,
I need help to cover following code into my test class
User-added imageUser-added imageUser-added image
Hi guys,
 I have a doubt on ant deployment tool, iam new to this...
So what my doubt is... I have a two orgs x and y ,, I was retrieving Apex classes from x org and deploying to y org and next I have done some modifications on  Apex class  in x org and retrieve again and deployed to y org but I was getting an error because the Apex classes with same name are already existed in y org as we deployed at first time ,, so can any one tell me is it possible to override those classes ,,if it is please explain
thanks.
Hi Techie's,
Please help me out
here the scenario when i insert a account record with name 'Test A' and the folder sholud be created with the 'Test A' in Box.com
As Box Supports OAUTH Authentication it is having with conflict with writing trigger ..can any one help on this 

Thanks ,
Ram
Hello,

I am trying to solve the challange of the HTTP and Basic Callout module of Salesforce trailhead and I am having some queries in which you could point to the right direction:

1- The challange asked us to call this URL https://th-apex-http-callout.herokuapp.com/animals/:id in method getAnimalNameById... should that URL be in this form instead of the above https://th-apex-http-callout.herokuapp.com/animals?id ? Where id is a parameter in the URL.

2- When I tried to check the solution of the challange, Salesforce generated that error for me
"Challenge Not yet complete... here's what's wrong: 
Executing the 'getAnimalNameById' method on 'AnimalLocator' failed. Make sure the method exists with the name 'getAnimalNameById', is public and static, accepts an Integer and returns a String."
despite that my class implementation has this method declared as public static String as below in the code snippet:
 
public class AnimalLocator {
	
	public static String getAnimalNameById(Integer id) {
		
		Http http = new Http();
		HttpRequest request = new HttpRequest();
		request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals?id');
		request.setMethod('GET');
		
		HttpResponse response = http.send(request);
		List<Object> animals = NULL;
		String returnValue = NULL;
		
		// if the request was successful, then parse the JSON response
		if (response.getStatusCode() == 200) {
			Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
			animals = (List<Object>) result.get('animals');
			System.debug(animals);
		}
		
		if (animals.size() > 0 && animals != NULL && id < animals.size()) {
			returnValue = (String) animals.get(id);
		}
		
		return returnValue;
	} // end getAnimalNameById method
    
} // end AnimalLocator class

I would appreciate your help in this post.

Thank you,

Sinan
I have implemented web-to-case + entitlements / service contracts and an entitlement process.
How can I automatically create and assign an entitlement to a case? I now have to do it manually and only then does it trigger the entitlement process with the relevant processes. In my use case it concerns a case that needs to be picked up after 60 minutes when it is in the queue. I can assign an escalation rule but I would rather work with an entitlement process as you can add other milestones in the process to resolve the case according to SLA settings.
Hey I'm really new to Salesforce development. I have two triggers i need to deploy from sandbox, but code coverage is 0%.
I have to add some test classes, right? but i'm not sure how to handle it.

Trigger 1
trigger CopyPartnerSource on Lead (before insert, before update) {

for (Lead l : Trigger.new) { l.Partner_Account_Mirror__c = l.Partner_Account__c; } }




Trigger 2
trigger Trigger_Task_Send_Email on Task (before update) {
  
    Set<Id> createdbyIds = new Set<Id>();
   
    for(Task tsk: Trigger.New)
        createdbyIds.add(tsk.createdbyId);
   
    Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :createdbyIds]);
    for(Task tsk : Trigger.New)
    {
        User theUser = userMap.get(tsk.createdbyId);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {theUser.Email};
        mail.setToAddresses(toAddresses);    // Set the TO addresses
        mail.setSubject('A task created by you has been updated');    // Set the subject
  
        String template = 'Hello {0}, \nYour task has been modified. Here are the details: \n\n';
        template+= 'Subject - {1}\n';
        template+= 'Due Date - {2}\n';
        String duedate = '';
        if (tsk.ActivityDate==null)
            duedate = '';
        else
            duedate = tsk.ActivityDate.format();
        List<String> args = new List<String>();
        args.add(theUser.Name);
        args.add(tsk.Subject);
        args.add(duedate);
        
       
        // Here's the String.format() call.
        String formattedHtml = String.format(template, args);
       
        mail.setPlainTextBody(formattedHtml);
        Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
}




Any help will be appreciated, thanks
Hi I have some 9 sobjects data retrieved via SOQL. Now I want to add all this List's to a Generic List<sobejct> type to perform single DML operation

Can't this be done with out using For-loops ?
I tried addALL method od list
Hi All,

Please bear with me. I am an APEX newbie and needed some assistance please.

Goal: I wanted to update the checkbox (SentForApproval__c) in Child Object (Rate_sheet__c) to TRUE if the Parent Record (Lead) Status (Lead_Status_NEW__c) was set to "CA Completed". This is a lookup relationship.

Parent Object: Lead
Child Object: Rate_sheet__c

Here's what I have so far and I am unsure how to complete the code or even correct this:
 
trigger CAforApproval on Lead (after update){

	set<Id> leadIds = new set<Id>();
    	map<Id, Lead> mapLead = new map<Id, Lead>();
    	list<Rate_sheet__c> listRateSheet = new list<Rate_sheet__c>();
    
    	for(Lead lead : trigger.new) {
        	leadIds.add(lead.Id);
        	mapLead.put(lead.Id, lead);
        }
    
   	 listRateSheet = [SELECT SentForApproval__c,  Lead__r.Id  FROM Rate_sheet__c WHERE Lead__r.Id  IN : leadIds];
    
    if(listRateSheet.size() > 0) { 
        for(Rate_sheet__c rs : listRateSheet) {

Any help is greatly appreciated. Thank you
I would like to know which all operation it is guarenteed that System.Isbatch() will be true. 

Data inserted from dataloader or other data migration tools / third party software.
Batch Apex?
Any other API?


Got this error & just following directions...

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: HQVTALII

It is a brand new org.
I was wondering if anyone has had any experience assigning a Topic to a record from the Question object before.

Some background
We are currently buiding a custom site using VisualForce and custom JS to essentially provide our own interface to the standard SF community functionality.

The page I'm currently working on is our Q&A page - specifically the page through which customers can post their own Questions to our customer community.

The Goal
The issue is, we need to be able to filter our questions by topic - not just by data category.  This must also be achieved purely in APEX without any standard apex components on the VF page.

What has been done so far
So far, I have enabled topics for the question object (under Topics for Objects in SF setup).  I have enabled system permissions for the appropriate profiles to create, edit, and assign topics.  Yet I keep running into an apex exception when I try to assign the topic to the question.

Attempt 1: Manually insert a record into the TopicAssignment object
In the code, I create and insert a question (and topic if required).  This works without any problems.  Then I run the following:
TopicAssignment a = new TopicAssignment(TopicId=t.Id, EntityId=q.Id, NetworkId=n.Id);
insert a;
This line will throw the following error:
Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Entity ID: id value of incorrect type: 906N00000004EF7IAM: [EntityId]
Attempt 2:  Use the ConnectApi
I then found a new class in the ConnectApi called Topics which does not yet appear to be documented.
ConnectApi.Topics.assignTopic(networkId question.Id, topic.Id);
Using this instead yields the following error:
Failed to assign topic to 906N00000004EFC. Please ensure you have permissions to assign topics for this record.


Both of the above errors still occur if the class has sharing off - e.g.
public without sharing class ClassName {
}



I am hoping to achieve this without having to create a new object as a workaround.

So, I was wondering if anyone else has had this issue?  Has anyone succesfully assigned a topic to a question in pure APEX?  Can anyone help?

Thank you very much,

Nic



 
Dear all,

For 2 days, I have been having the following issue : all the automatical emails my team and I usually receive from Salesforce (e.g. emails when a big opportunity is won, emails when I am trying a new email template and sending me a test email to preview the result...) are sent with a few hours of delay (usually at the end of the day).

So I tried the email deliverability test and I only received ~20 of the 32 emails I should have received.

Do you have any idea on why this is happening ?

Thanks in advance,
Yannick
Is this happening to you? You're 100% sure you've done a Trailhead challenge right, but it just won't validate?

So here's the deal. We're doing a real-time API call to check your work, and sometimes, there might be existing configuration or code in your Developer Edition that interferes with our check, causing it to fail.

The best thing to do if you're 100% sure you're right is create a new Developer Edition and do the challenge again.

But wait, what about my badges?

No worries! Logging into Trailhead is a two-step process. Check out this image.

The login button is in the upper right, and the second login is on the unit page right before you do the challenge

In step (1), you tell Trailhead who you are. This is where your badges are stored. You can use your production username or any Developer Edition username for this step.

In step (2), you tell Trailhead where you're doing the challenge. This must be a Developer Edition.

Okay, I got the new DE. Now what?

So, just stay logged in at (1), and make a new Developer Edition to log in at (2). Do the challenge in the new Developer Edition and check it.

If it passes, it was probably something funky in your old DE. If it fails, time to revisit your challenge! Read the instructions again and make sure you didn't miss any steps.

But why would this happen?

It could be your DE is older, or it could be you've done some additional config or customization that is interfering with our check. 

Good luck!
There is a permission page after community user login via mobile app which we created with native SF SDK. The wording "否允存取" in the permission page is very strange in Chinese locale. I don't understand the meaning of "否允存取" even I speak in Chinese for 30 years. Is there a way we can edit the wording or removing the page!? Actually our client owns the APP, the SF org and all member data so we don't need the permission page at all.
HI Experts,

while posting my code in developers community, getting this error what does it mean by."The operation is not permitted. If you received this in error, please contact info@developerforce.com (code: B2)"
I am working on a project to create a VF page where the user can add multiple attachments when creating a record.  Someone suggested the controller listed below, and while it will save the attachments, it isn't saving any of the information entered in the VF page for the Incident Report.  If anyone can take a look at this and tell me why the Incident Report isn't being saved, I would truly appreciate it.

APEX CLASS
 
public class AddMultipleAttachments {
    
    public Incident_Reports__c objIncidentReport { get; set; }
    public Attachment attachment1 { get; set; }
    public Attachment attachment2 { get; set; }
    public Attachment attachment3 { get; set; }

    public AddMultipleAttachments (ApexPages.StandardController stdController)
    {
        // Record and Attachments to be inserted
        objIncidentReport = new Incident_Reports__c();
        attachment1 = new Attachment();
        attachment2 = new Attachment();
        attachment3 = new Attachment();
    }

    public PageReference createRecordAndAttachments()
    {
        
        Savepoint sp = Database.setSavepoint();
        try
        {
            // Insert the record
            insert objIncidentReport;

        
            // Insert Attachments;
            List<Attachment> toInsert = new List<Attachment>();

            if(attachment1.Name != null)
            {
                attachment1.ParentId = objIncidentReport.Id;
                toInsert.add(attachment1);
            }
            
            if(attachment2.Name != null)
            {
                attachment2.ParentId = objIncidentReport.Id;
                toInsert.add(attachment2);
            }

            if(attachment3.Name != null)
            {
                attachment3.ParentId = objIncidentReport.Id;
                toInsert.add(attachment3);
            }

            if(toInsert.size() > 0)
                insert toInsert;
        }
        catch(Exception ex)
        {
            Database.rollback(sp);
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
            ApexPages.addMessage(msg);
        }

        // View the record
        PageReference page = ApexPages.currentPage();
        page.setRedirect(true);
        return page;
    }

}

Here is the Visualforce page:

Visualforce Page
 
<apex:page standardController="Incident_Reports__c" extensions="AddMultipleAttachments">
    
    <apex:sectionHeader title="Property Incident Reports Edit" subtitle="{!Incident_Reports__c.Name}"/>
    <apex:form >
        
        <apex:commandButton value="Save" action="{!save}"/>
        <apex:commandButton value="Save with Attachments" action="{!createRecordAndAttachments}"/>
        <apex:commandButton value="Cancel" action="{!cancel}"/>
        <apex:pageBlock title="Property Incident Reports Edit" mode="edit" id="thePageBlock">
          <apex:pagemessages />
            
            <apex:pageBlockSection columns="1">
              <apex:outputText value="ATTENTION:  Attorney work product/privileged document (for internal use only).  NOT for Associate Injuries, use Worker's Comp Incident Report." style="font-weight:800"/>
              <apex:outputText value="RED LINES REPRESENT REQUIRED FIELDS" style="color:red"  />
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Property Information" columns="2">
                <apex:inputField value="{!Incident_Reports__c.Property__c}" required="true"/>
                
            </apex:pageBlockSection>
               
            <apex:pageBlockSection title="Claimant Information" columns="2">
                <apex:inputField value="{!Incident_Reports__c.Claimant_s_Name__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Claimant_s_Gender__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Claimant_s_Address__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Claimant_s_Age__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Claimant_s_Date_of_Birth__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Claimant_s_Phone_Number__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Claimant_s_Phone_Number_Other__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Claimant_s_Occupation__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Alliance_Associate__c}" required="false"/>
            </apex:pageBlockSection>  
                          
        </apex:pageBlock>
            
       
        
       <apex:pageBlock title="Incident Information" mode="edit" id="Incident">
            
          <apex:actionRegion >
            <apex:pageBlockSection title="Incident Type" columns="1">
              <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Type of Incident"/>
                    <apex:outputPanel >
                      <apex:inputField value="{!Incident_Reports__c.Type_of_Incident__c}" required="TRUE">
                        <apex:actionSupport event="onchange" rerender="Incident" status="IncidentType"/>
                      </apex:inputField>
                      <apex:actionStatus startText="applying value..." id="IncidentType"/>
                    </apex:outputPanel>
                  </apex:pageBlockSectionItem> 
            </apex:pageBlockSection>
          </apex:actionRegion>

          <apex:actionRegion >
            <apex:pageBlockSection title="Incident Information" columns="2">     
                <apex:inputField value="{!Incident_Reports__c.Date_Time_of_Incident__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Date_Time_Incident_Reported__c}" required="false"/> 
                <apex:inputField value="{!Incident_Reports__c.Pictures_Attached__c}" required="false"/>
                <apex:inputField value="{!Incident_Reports__c.Property_Owner_Notified__c}" required="false"/> 
                
                <apex:pageBlockSectionItem helpText="Check this box if Police, Fire or Ambulance were dispatched to the property.">
                    <apex:outputLabel value="Emergency Services Called"/>
                    <apex:outputPanel >
                      <apex:inputField value="{!Incident_Reports__c.Emergency_Services_Required__c}" label="Check if Police, Fire or Ambulance were dispatched to the property.">
                        <apex:actionSupport event="onclick" rerender="Incident" status="status"/>
                      </apex:inputField>
                      <apex:actionStatus startText="applying value..." id="status"/>
                    </apex:outputPanel>
                  </apex:pageBlockSectionItem>  
            </apex:pageBlockSection>
            
          </apex:actionRegion>
          
          <apex:actionRegion >
            <apex:pageBlockSection title="Responding Agencies" id="agencies" columns="2" rendered="{!Incident_Reports__c.Emergency_Services_Required__c == TRUE}">
              
              
              <apex:pageBlockSectionItem >
               
              <apex:outputLabel value="Police Department"/>
              <apex:outputPanel >
                <apex:inputField value="{!Incident_Reports__c.Police_Responded__c}">
                <apex:actionSupport event="onclick" rerender="Incident" status="status1"/>
              </apex:inputField>
              <apex:actionStatus startText="adding Police Department block..." id="status1"/>
              </apex:outputPanel>
              </apex:pageBlockSectionItem>
              
              <apex:pageBlockSectionItem >
               
              <apex:outputLabel value="Fire Department"/>
              <apex:outputPanel >
                <apex:inputField value="{!Incident_Reports__c.Fire_Department_Responded__c}">
                <apex:actionSupport event="onclick" rerender="Incident" status="status2"/>
              </apex:inputField>
              <apex:actionStatus startText="adding Fire Department block..." id="status2"/>
              </apex:outputPanel>
              </apex:pageBlockSectionItem>
              
              <apex:pageBlockSectionItem >
               
              <apex:outputLabel value="Ambulance Service"/>
              <apex:outputPanel >
                <apex:inputField value="{!Incident_Reports__c.Ambulance_Company_Responded__c}">
                <apex:actionSupport event="onclick" rerender="Incident" status="status3"/>
              </apex:inputField>
              <apex:actionStatus startText="adding Ambulance Service block..." id="status3"/>
              </apex:outputPanel>
              </apex:pageBlockSectionItem>
              
              <apex:pageBlockSectionItem >
               
              <apex:outputLabel value="Other Emergency Service"/>
              <apex:outputPanel >
                <apex:inputField value="{!Incident_Reports__c.Other_Department_Responded__c}">
                <apex:actionSupport event="onclick" rerender="Incident" status="status4"/>
              </apex:inputField>
              <apex:actionStatus startText="adding Other Emergency Service block..." id="status4"/>
              </apex:outputPanel>
              </apex:pageBlockSectionItem>
              
            </apex:pageBlockSection>
          </apex:actionRegion>
            
            <apex:pageBlockSection title="Police Department Information" id="police" columns="2" rendered="{!Incident_Reports__c.Police_Responded__c == TRUE}">
                <apex:inputField value="{!Incident_Reports__c.Police_Department_Name__c}" label="Police Department Name"/>
                <apex:inputField value="{!Incident_Reports__c.Police_Report_Number__c}" label="Police Report Number"/>
                
                                
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Fire Department Information" columns="2" rendered="{!Incident_Reports__c.Fire_Department_Responded__c == TRUE}">
                <apex:inputField value="{!Incident_Reports__c.Fire_Department_Name__c}" label="Fire Department Name"/>
                <apex:inputField value="{!Incident_Reports__c.Fire_Dept_Report_Number__c}" label="Fire Dept. Report Number"/>
                
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Ambulance Information" columns="2" rendered="{!Incident_Reports__c.Ambulance_Company_Responded__c == TRUE}">
                <apex:inputField value="{!Incident_Reports__c.Ambulance_Company_Name__c}" label="Ambulance Company Name"/>
                <apex:inputField value="{!Incident_Reports__c.Ambulance_Company_Report_Number__c}" label="Ambulance Co. Report Number"/>
                
                <apex:inputField value="{!Incident_Reports__c.Hospital_Name__c}" label="Hospital Taken To (if applicable)"/>
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Other Emergency Services" columns="2" rendered="{!Incident_Reports__c.Other_Department_Responded__c == TRUE}">
                <apex:inputField value="{!Incident_Reports__c.Other_Respondant__c}" label="Other Department Name"/>
                <apex:inputField value="{!Incident_Reports__c.Other_Report_Number__c}" label="Other Department Report Number"/>
                
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Moisture / Flooding" columns="3" rendered="{!Incident_Reports__c.Type_of_Incident__c == 'Flood/Moisture'}" id="FloodingSection">
                <apex:inputTextarea value="{!Incident_Reports__c.Affected_Area__c}" label="Describe Affected Area" cols="40" rows="8"/>
                <apex:inputTextarea value="{!Incident_Reports__c.Source_Cause_of_Moisture__c}" label="Describe Cause of Moisture" cols="40" rows="8"/>
                <apex:inputTextarea value="{!Incident_Reports__c.Personal_Property_Damage__c}" label="Detail Damage to Personal Property" cols="40" rows="8"/>
                <apex:inputField value="{!Incident_Reports__c.Date_Notification_Letter_Sent__c}" label="Date Notification Letter Sent"/>
                <apex:inputField value="{!Incident_Reports__c.Date_Option_Letter_Given__c}" label="Date Option Letter Given"/>
                <apex:inputField value="{!Incident_Reports__c.Date_Option_Letter_Received__c}" label="Date Option Letter Received"/>
                <apex:inputField value="{!Incident_Reports__c.Follow_Up_Call_Completed__c}" label="Date Follow-up Call Completed"/>
                <apex:inputField value="{!Incident_Reports__c.Follow_Up_Call_Associate__c}" label="Name of Associate Conducting Call"/>
                <apex:inputTextarea value="{!Incident_Reports__c.Result_of_Conversation__c}" label="Result of Conversation" cols="40" rows="8"/>
            </apex:pageBlockSection>
           
        </apex:pageBlock>
           
        <apex:pageBlock title="Add Attachments">
          	<apex:pageBlockSection title="Attachment 1" >
                <apex:inputFile value="{!attachment1.body}" fileName="{!attachment1.name}"/>
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Attachment 2" >
                <apex:inputFile value="{!attachment2.body}" fileName="{!attachment2.name}"/>
            </apex:pageBlockSection>
            
            <apex:pageBlockSection title="Attachment 3" >
                <apex:inputFile value="{!attachment3.body}" fileName="{!attachment3.name}"/>
            </apex:pageBlockSection>
        
        </apex:pageBlock>
    </apex:form>    
</apex:page>

Again, any help is greatly appreciated.

Thanks,

Matt
I'm using AggregateResult to display 2 values, first is a sum of a custom field Hours_Used__c which is in a custom object Holiday__c. Second is a sum of a custom field Hours_Available__c which is on the User object.

I am able to show these results separately on my visualforce page shown here:

vfpage

My requirement is to be able to display Hours_Available__c - Hours_Used__c to leave me with a column that shows the Staff Member Name and the total hours that are left.

For example using the screenshot above I would need a pageblocktable that shows:

Staff Member   | Hours Left
Adam west      | 252
Duke Young     | 225
Jim Taylor       | 198

Controller:
public class HolidayManagementController {
    
    Public List<Holiday__c> HolidayList {get;set;}
    Public List<AggregateResult> HoursUsedList;
    Public List<AggregateResult> AllowanceTotalList;
 
    String cname {get;set;}
    
    Public HolidayManagementcontroller(){
        cname		= UserInfo.getUserName();
        user cu	  	= [SELECT Name FROM User WHERE username =:cname];
        
        HolidayList 		= [SELECT Hours_Used__c, Staff_Member__c, Staff__r.Name, Manager_Name__c
                               FROM Holiday__c
                               WHERE Manager_Name__c =:cu.Name
                               ORDER BY Staff__r.Name];
       
        HoursUsedList 		= [SELECT SUM(Hours_Used__c) hours, Staff__r.Name staff
                               FROM Holiday__c
                               WHERE Manager_Name__c =:cu.Name
                               GROUP BY Staff__r.Name
                               ORDER BY Staff__r.Name asc];
        
        AllowanceTotalList 	= [SELECT SUM(Hours_Available__c) allowance, Name
                              FROM User
                              WHERE Manager__c =:cu.Name
                              GROUP BY Name
                              ORDER BY Name asc];
        
    }
    
    public list<AggregateResult> HoursList {
 	get { return HoursUsedList;}
 	}
    
    public list<AggregateResult> AllowanceList {
 	get { return AllowanceTotalList;}
 	}
}

VF Page:
<apex:page controller="HolidayManagementController" sidebar="false">
    <apex:form>
        <apex:pageBlock>
			<apex:pageBlockTable value="{!HolidayList}" var="hlist">

                <apex:column headerValue="Staff Member">
                <apex:outputField value="{!hlist.Staff__r.Name}"/>
                </apex:column>

                <apex:column headerValue="Manager">
                <apex:outputField value="{!hlist.Manager_Name__c}"/>
                </apex:column>
  
                <apex:column headerValue="Hours Used">
                <apex:outputField value="{!hlist.Hours_Used__c}"/>
                </apex:column>
                
            </apex:pageBlockTable>            
        </apex:pageBlock>
        
        <apex:pageBlock>
        <apex:pageBlockTable value="{!HoursList}" var="h">
        	  
           <apex:column >
            <apex:facet name="header">Staff Member</apex:facet>
            {!h['staff']}</apex:column>
            
            <apex:column >
            <apex:facet name="header">Hours Used</apex:facet>
            {!h['hours']}</apex:column>
            

            
        </apex:pageBlockTable>
            
        <apex:pageBlockTable value="{!AllowanceList}" var="a">
        	  
           <apex:column >
            <apex:facet name="header">Staff Member</apex:facet>
            {!a['Name']}</apex:column>
            
            <apex:column >
            <apex:facet name="header">Hours Available</apex:facet>
            {!a['allowance']}</apex:column>
            

            
        </apex:pageBlockTable>    
            
        </apex:pageBlock>
    </apex:form>
</apex:page>

Any help would be greatly appreciated. I'm pretty new to programming in general so i'm open to suggesstions if i'm going about this the wrong way. 

Thanks
L
  • January 25, 2015
  • Like
  • 1
Hello,
I have a number field on my account object that if greater than 1, I want it to change the account type to "Account Active"
Account Active is currently an option under the picklist field = Type.

What I am currently doing manually is running a report that shows customers with number of subscriptions. If I see one that has 1 or more subscription I have to go and change the account type to "Active Customer" currently it just stays as "Active Prospect" which is the default field.
Is this possible to automate with a trigger?
thank you-
  • November 06, 2014
  • Like
  • 1