+ Start a Discussion
Felix QuinonesFelix Quinones 

Hello All, 

I'm trying to create a formula field (Yearly Compliance) for a custom object named Compliance. The formula should add the compliance for the quarter (i.e. Q1_c__c), if not left blankand, and divide those by the number of complete fields. I'm trying to calculate the percent of compliance. The problem is that any of those four number fields could be left on black.

I tried the following formulas in where any of the Qs (i.e. Q1_c__c)  could be a number or could be left blank.

IF( 
AND 
   (Q1_c__c =0, 
    Q1_c__c = 0, 
    Q1_c__c = 0, 
   Q1_c__c = 0
    ),
    0, 
(Q1_c__c + Q2_c__c + Q3_c__c + Q4_c__c)/4)

 

IF(

AND(
ISBLANK(Q1_c__c),
ISBLANK(Q2_c__c),
ISBLANK(Q3_c__c),
ISBLANK(Q4_c__c)
),
NULL,(Q1_c__c + Q2_c__c + Q3_c__c + Q4_c__c)/4)

Here is a picture of the pay layout . 

  • If the quarter is left black, means that do not apply.
  • I'm trying to calculate the percent of Yearly Compliance. Here the Yearly Compliance should be 100% divided by 3. This is because the quarter empty (Q1) do not count for this year compliance. Also, the other two quarters are in 0%. 


Example
 

Yearly compliance should be 33.33%
Best Answer chosen by Felix Quinones
Swati PawarSwati Pawar
Hi,

Below mentioned formula might help you.  Make sure to check "Treat blank fields as blanks" option in your formula field.

Formula :
IF(
(Q1__c = 0 ||ISBLANK(Q1__c)) && (Q2__c = 0 || ISBLANK(Q2__c)) && (Q3__c = 0 || ISBLANK(Q3__c)) && (Q4__c = 0 || ISBLANK(Q4__c)) ,
0 ,
((IF(ISBLANK(Q1__c),0,Q1__c) +
IF(ISBLANK(Q2__c),0,Q2__c) +
IF(ISBLANK(Q3__c),0,Q3__c) +
IF(ISBLANK(Q4__c),0,Q4__c) ) )/ 
(IF(ISBLANK(Q1__c),0,1)+ IF(ISBLANK(Q2__c),0,1) +
IF(ISBLANK(Q3__c),0,1) + IF(ISBLANK(Q4__c),0,1))
 
)

User-added image


If it works for you then mark it as a best answer.

Thanks !!
RJ12RJ12 

I'm doing a REST API call to get the global value set and trying to deserialize the JSON result to get the picklist values in a List<String>.

Here is the JSON:

{
  "size": 1,
  "totalSize": 1,
  "done": true,
  "queryLocator": null,
  "entityTypeName": "GlobalValueSet",
  "records": [
    {
      "attributes": {
        "type": "GlobalValueSet",
        "url": "/services/data/v53.0/tooling/sobjects/GlobalValueSet/0Nt59000000AAAAAAA"
      },
      "Metadata": {
        "customValue": [
          {
            "color": null,
            "default": false,
            "description": null,
            "isActive": null,
            "label": "USA",
            "urls": null,
            "valueName": "USA"
          },
          {
            "color": null,
            "default": false,
            "description": null,
            "isActive": null,
            "label": "Canada",
            "urls": null,
            "valueName": "Canada"
          }
        ],
        "description": null,
        "masterLabel": "US States & Territories",
        "sorted": false,
        "urls": null
      },
      "Id": "0Nt59000000AAAAAAA"
    }
  ]
}
I need help in fixing the error and also how to get valueNames in a List<String>

Error: System.JSONException: Malformed JSON: Expected '{' at the beginning of an object.

Here is what I have tried so far:

Wrapper:
    public class GlobalValueSetWrapper{
        Metadata metadata;

    public class Metadata {
        public List<CustomValue> customValue;
    }
    
    public class CustomValue {
        public String label;  
        public String valueName;
    }
    }


Class:
//calling API to get the JSON result
HttpResponse res = GlobalValueSetAPIHandler.getResponse('Countries');
GlobalValueSetWrapper wrapper = (GlobalValueSetWrapper) JSON.deserialize(res.getBody(), GlobalValueSetWrapper.class);
Best Answer chosen by RJ12
RJ12RJ12

I'm able to fix it.

public class GlobalValueSetWrapper{
    public List<Records> records;

    public class Records {
        public Metadata metadata;
    }
    
    public class Metadata {
        public List<CustomValue> customValue;
    }

    public class CustomValue {
        public String label;
        public String valueName;    
    }

    public static List<String> getPicklistValues(HttpResponse response){
        List<String> picklistValues = new List<String>();
        
        GlobalValueSetWrapper wrapper = (GlobalValueSetWrapper) System.JSON.deserialize(response.getBody(), GlobalValueSetWrapper.class);
        
        for(GlobalValueSetWrapper.customValue value : wrapper.records[0].metadata.customValue){
            picklistValues.add(value.valueName);
        }
        system.debug('Piclist Values: ' + picklistValues);
        
        return picklistValues;
    }
}
merrick devillemerrick deville 
Hello everyone I could use some help on the using future Methods trailhead. Please keep in mind I am not an Apex coder at all but I am trying to learn as much as I can.

Here is the Task

Create an Apex class with a method using the @future annotation that accepts a List of Account IDs and updates a custom field on the Account object with the number of contacts associated to the Account. Write unit tests that achieve 100% code coverage for the class.
Create a field on the Account object called 'Number_of_Contacts__c' of type Number. This field will hold the total number of Contacts for the Account.
Create an Apex class called 'AccountProcessor' that contains a 'countContacts' method that accepts a List of Account IDs. This method must use the @future annotation.
For each Account ID passed to the method, count the number of Contact records associated to it and update the 'Number_of_Contacts__c' field with this value.
Create an Apex test class called 'AccountProcessorTest'.
The unit tests must cover all lines of code included in the AccountProcessor class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.

I have written an Apex class and a Test class but I think I am doing them both Wrong: because when I try to check the challenge i Get this error

Challenge Not yet complete... here's what's wrong: 
The 'AccountProcessorTest' test class doesn't appear to be calling the 'AccountProcessor.countContacts' method between Test.startTest() and Test.stopTest().


When I run the Test class I get this error :

System.QueryException: List has no rows for assignment to SObject

Here is the CLASS:
 
public class AccountProcessor {
     @future

  public static void someFutureMethod(List<id> scope) {

   Account[] updates = new Account[] {};
        for (AggregateResult ar : [
                select AccountId a, count(Id) c
                from Contact
                where AccountId in :scope
                group by AccountId
                ]) {
            updates.add(new Account(
                    Id = (Id) ar.get('a'),
                    Number_of_Contacts__c = (Decimal) ar.get('c')
                    ));
        }
        update updates;
    }

}

Here is the Test Class:
 
@IsTest
public class AccountProcessorTest {
  public static testmethod void TestAccountProcessorTest() {
 
Test.startTest();
     Account a = new Account();
        a.Name = 'Test Account';
        Insert a;
      
      Contact cont = New Contact();
      
      cont.FirstName ='Bob';
      cont.LastName ='Masters';
      cont.AccountId = a.Id;
      Insert cont;

    Test.stopTest() ;
     Contact ACC = [select AccountId from Contact where id = :a.id LIMIT 1];

 
        System.assert(Cont.AccountId != null);
        System.assertequals(cont.id, ACC.AccountId);

  }}

I have used alot or diffrent google searches to get me this far. But I have not Idea if Im even remotly close to the right answer or not.


 
Best Answer chosen by merrick deville
Amit Chaudhary 8Amit Chaudhary 8
As per task you method should be "countContacts"

Please update your Apex class like below :-
public class AccountProcessor 
{
  @future
  public static void countContacts(Set<id> setId) 
  {
      List<Account> lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
      {
          List<Contact> lstCont = acc.contacts ;
          
          acc.Number_of_Contacts__c = lstCont.size();
      }
      update lstAccount;
  }
}

Test class:-
@IsTest
public class AccountProcessorTest {
    public static testmethod void TestAccountProcessorTest() 
    {
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;

        Contact cont = New Contact();
        cont.FirstName ='Bob';
        cont.LastName ='Masters';
        cont.AccountId = a.Id;
        Insert cont;
        
        set<Id> setAccId = new Set<ID>();
        setAccId.add(a.id);
 
        Test.startTest();
            AccountProcessor.countContacts(setAccId);
        Test.stopTest();
        
        Account ACC = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
        System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);
  }
  
}

Please let us know if this will help you

Thanks
Amit Chaudhary
 
msb-appsupport1.3905906418879758E12msb-appsupport1.3905906418879758E12 
I want to use Apex code and visualforce page to create a new lead.

In web, I need to choose a record type before I create a new lead. And there are three types of leads.
In visualforce page, I want to create a new lead with assigned record type using code.

The confusion for me is that the recordType is related list for the lead. I could extract a list of record type by the following.

for (list<RecordType> rts : [SELECT ID, name FROM RecordType WHERE SObjectType = 'Lead' Order by name])

However, I could not pull out the recordType for a lead by the following, since the recordType is related list.

Lead l = [SELECT RecordType FROM LEAD].

Besides, what I want is create a new lead like below.
Lead l = new Lead(firstname='testInsertLead2', lastname='test',company='Temp Company', RecordType = 'registration type lead');

Could anyone help me with this to access the related list using apex code or visualforce page?

Thanks a lot.


Best Answer chosen by msb-appsupport1.3905906418879758E12
Chidambar ReddyChidambar Reddy
Hi

Try the following it will be user friendly



Map<String,Id> recordtypeMap  = new Map<String,Id>();

for(Record Type leadRT :  [select id, Name from RecordType where SObjectType = 'Lead' ]){

recordtypeMap.put(leadRT.Name,leadRT.Id);
 }

//you can create lead by following 

Lead l = new Lead(firstname='testInsertLead2', lastname='test',company='Temp Company', RecordTypeId = recordtypeMap.get('registration type lead'));

// be sure to enter record type name correctly other wise it would give an error.



Thank you,
Choose it as Best Answer if it resolved your issue.



StormConsultingStormConsulting 
How can I get the current Salesforce User ID in an Apex class?

Any help is appreciated!

Chris
Best Answer chosen by Admin (Salesforce Developers) 
hisrinuhisrinu
You can get the current user id like this.

UserInfo.getUserId() which returns the user id of the current user.
BDeigsBDeigs 

I can't get this to work and was hoping someone can help...  Any thoughts?

 

IF(BEGINS( Phone , "(804)"), "Richmond",
IF(BEGINS(Phone , "(757)"),"Virginia Beach - Norfolk",
IF(BEGINS(Phone , "(704):(980)"),"Raleigh",
IF(BEGINS(Phone , "(919)"),"Charlotte",
IF(BEGINS(Phone , "(813):(727):(941)"),"Tampa",
IF(BEGINS(Phone , "(321):(407)"),"Orlando",
IF(BEGINS(Phone , "(904)"),"Jacksonville",
IF(BEGINS(Phone , "(770):(678):(404)"),"Atlanta",
IF(BEGINS(Phone , "(914):(631):(516):(347):(718):(917):(212):(646):(862):(973):(201):(551)"),"NYC - Newark",
IF(BEGINS(Phone , "(484):(610):(835):(215):(267):(856):(609):(302)"),"Philadelphia",
IF(BEGINS( Phone , "(781):(857):(339):(617)"),"Boston",
IF(BEGINS(Phone , "(716):(858)"),"Buffalo",
IF(BEGINS(Phone , "(860)"),"Hartford",
IF(BEGINS(Phone , "(401)"),"Providence",
IF(BEGINS(Phone , "(305):(786):(954):(754)"),"Miami",
IF(BEGINS(Phone , "(412):(878)"),"Pittsburgh",
IF(BEGINS(Phone , "(513)"),"Cincinnati",
IF(BEGINS(Phone , "(216):(440)"),"Cleveland",
IF(BEGINS(Phone , "(614)"),"Columbus",
IF(BEGINS(Phone , "(571):(703):(202):(240):(301)"),"DC",
IF(BEGINS(Phone , "(410):(443)"),"Baltimore",
"?-Non-metro")))))))))))))))))))))

Best Answer chosen by Admin (Salesforce Developers) 
jhurstjhurst

Not quite sure what the issue you are seeing is, but my guess is that you see a "?-Non-Metro" for any of the cities you are using the OR for.  If that is the case, it is because you are using an invalid OR designation.  By including the : in the quotes you are using them as a matching string.  So to get "Raleigh" the number would have to start with the string "(704):(980)".

 

I was able to get what I think you are looking for with the formula:

 

IF(BEGINS( Phone , "(804)"), "Richmond",
IF(BEGINS(Phone , "(757)"),"Virginia Beach - Norfolk",
IF(BEGINS(Phone , "(704)") || BEGINS(Phone, "(980)"),"Raleigh",
IF(BEGINS(Phone , "(919)"),"Charlotte",
IF(BEGINS(Phone , "(813)") || BEGINS(Phone , "(727)") || BEGINS(Phone , "(941)"),"Tampa",
IF(BEGINS(Phone , "(321)") || BEGINS(Phone , "(407)"),"Orlando",
IF(BEGINS(Phone , "(904)"),"Jacksonville",
IF(BEGINS(Phone , "(770)") || BEGINS(Phone , "(678)") || BEGINS(Phone , "(404)"),"Atlanta",
IF(BEGINS(Phone , "(914)") || BEGINS(Phone , "(631)") || BEGINS(Phone , "(516)") || BEGINS(Phone , "(347)") || BEGINS(Phone , "(718)") || BEGINS(Phone , "(917)") ||
     BEGINS(Phone , "(212)") || BEGINS(Phone , "(646)") || BEGINS(Phone , "(862)") || BEGINS(Phone , "(973)") || BEGINS(Phone , "(201)") || BEGINS(Phone , "(551)"),"NYC - Newark",
IF(BEGINS(Phone , "(484)") || BEGINS(Phone , "(610)") || BEGINS(Phone , "(835)") || BEGINS(Phone , "(215)") || BEGINS(Phone , "(267)") || BEGINS(Phone , "(856)") ||
     BEGINS(Phone , "(609)") || BEGINS(Phone , "(302)"),"Philadelphia",
IF(BEGINS(Phone , "(781)") || BEGINS(Phone , "(857)") || BEGINS(Phone , "(339)") || BEGINS(Phone , "(617)"),"Boston",
IF(BEGINS(Phone , "(716)") || BEGINS(Phone , "(858)"),"Buffalo",
IF(BEGINS(Phone , "(860)"),"Hartford",
IF(BEGINS(Phone , "(401)"),"Providence",
IF(BEGINS(Phone , "(305)") || BEGINS(Phone , "(786)") || BEGINS(Phone , "(954)") || BEGINS(Phone , "(754)"),"Miami",
IF(BEGINS(Phone , "(412)") || BEGINS(Phone , "(878)"),"Pittsburgh",
IF(BEGINS(Phone , "(513)"),"Cincinnati",
IF(BEGINS(Phone , "(216)") || BEGINS(Phone , "(440)"),"Cleveland",
IF(BEGINS(Phone , "(614)"),"Columbus",
IF(BEGINS(Phone , "(571)") || BEGINS(Phone , "(703)") || BEGINS(Phone , "(202)") || BEGINS(Phone , "(240)") || BEGINS(Phone , "(301)"),"DC",
IF(BEGINS(Phone , "(410)") || BEGINS(Phone , "(443)"),"Baltimore",
"?-Non-metro")))))))))))))))))))))

 Hope this helps.

Jay

Rohit TripathiRohit Tripathi 
I am getting error message while solving this challenge in Trailhead :

To complete this challenge, add a validation rule which will block the insertion of a contact if the contact is related to an account and has a mailing postal code (which has the API Name MailingPostalCode) different from the account's shipping postal code (which has the API Name ShippingPostalCode).Name the validation rule 'Contact must be in Account ZIP Code'.
A contact with a MailingPostalCode that has an account and does not match the associated Account ShippingPostalCode should return with a validation error and not be inserted.
The validation rule should ONLY apply to contact records with an associated account. Contact records with no associated parent account can be added with any MailingPostalCode value. (Hint: you can use the ISBLANK function for this check)

Error Message is :  There was an unhandled exception. Please reference ID: HKIZNLVZ. Error: Trailhead::TrailheadTimeOut. Message: Trailhead.view: failed to get a 200 response. Made 3 attempts each resulting in a 403 or 500 failure for url challenges?key=%5B%22trailhead.challenge.validation_rules.en.us.192%22%5D.

I am not sure what went wrong here.
My Validation Rule is on Contact Object  :

  AND ( NOT(ISBLANK( Account.Name)),
( MailingPostalCode <> Account.ShippingPostalCode))

Can anyone please help with this.
Best Answer chosen by Rohit Tripathi
Amit Chaudhary 8Amit Chaudhary 8
Please try below valudation rule
AND(
NOT(ISBLANK(AccountId)),
MailingPostalCode != Account.ShippingPostalCode
)
i Used same and got all points in Trailhead challenge


 
Shaolin MasterShaolin Master 
I want to know how to parse the URL params from a get request
/services/apexrest/Endpoint/?subject=test&status=active&priority=1&origin=?subject=test&status=active&priority=1
I want to parse the url params in the class below
@HttpGet
    global static void getStatus() {
        RestRequest request = RestContext.request;
        System.debug(request.requestURI); 
        
    }

Please help!
Best Answer chosen by Shaolin Master
Maharajan CMaharajan C
Hi,

You have to write like below to parse the request:
@HttpGet
global static void getStatus() {
    RestRequest req = RestContext.request;
    String subject = req.params.get('subject');
    String status = req.params.get('status');
    String priority = req.params.get('priority');
    String origin = req.params.get('origin');
    
    system.debug('subject --> ' + subject  + ' status --> ' + status + 'priority --> ' + priority + 'origin --> ' + origin);

}

Thanks,
Maharajan.C
Michele Losch 4Michele Losch 4 
I'm unable to check step 2: Automate Accounts because I'm receiving this error: 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: ZKCVFIZH
 
Best Answer chosen by Michele Losch 4
Michele Losch 4Michele Losch 4
I fixed my validation rules and the error went away.
Palmira AngelovaPalmira Angelova 
Hi friends,

I need to look up specific Contacts on Accounts, but only include Contacts on Accounts that have Opportunities WHERE Stage IN('X','Y','Z') i.e. what I think of as a child -> parent -> child lookup. I've been using workbench for this. 

I couldn't figure out a way to do this within the syntax, so instead I opted for Account -> Contacts WHERE Account -> Opportunities meets my criteria, which seemed to make sense to me. However, my query is getting an error telling me I can't have a child -> parent lookup in the where clause:
"MALFORMED_QUERY: 
AND Id IN(SELECT Account.Id FROM Opportunity WHERE
ERROR at Row:5:Column:24
The inner select field 'Account.Id' cannot have more than one level of relationships"

Here is my query:
SELECT Id,
       (SELECT Id FROM Contacts WHERE Send_Partner_Updates__c = TRUE)
FROM Account
WHERE Account.POS_Provider_s__c NOT IN('Toshiba ACE', 'Toshiba ACE (old, non-integrated)')
      AND Id IN(SELECT Account.Id FROM Opportunity WHERE Stage IN('6 - Deployed', '6 - Deploying', '6.5 - Fully Deployed'))

Does anyone have a way to get by this? When I tried "SELECT Id FROM Opportunity", removing the child->parent lookup within the Opportunity query, I get this error: "The selected field 'Id' in the subquery and the left operand field in the where expression in the outer query 'Id' should point to the same object type"...so I haven't been able to think of a way around these two limitations.

Thanks for your help!
Best Answer chosen by Palmira Angelova
jigarshahjigarshah
Palmira,

Change the Account.Id to AccountId in the subquery for Opportunity hence your updated Soql query will now become
SELECT Id,
    (SELECT Id FROM Contacts WHERE Send_Partner_Updates__c = TRUE)
FROM Account
WHERE Account.POS_Provider_s__c NOT IN('Toshiba ACE', 'Toshiba ACE (old, non-integrated)')
      AND Id IN (SELECT AccountId, Stage FROM Opportunity WHERE Stage IN('6 - Deployed', '6 - Deploying', '6.5 - Fully Deployed'))
Hope that helps.