• SRK
  • SMARTIE
  • 1090 Points
  • Member since 2010

  • Chatter
    Feed
  • 32
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 550
    Replies

Hello, I have a Contracts object where we keep track of company's contracts data. I want to create a field that keeps track of what number renewal cycle we are in. For example, if the original contracts ends on 2/2/20, so the renewal period begins on 2/3/20, once 2/3/20 hits, I want the "Renewal cycle #" field to automatically change from 0 to 1. Then when the next renewal cycle begins, I want "Renewal cycle #" to automatically change from 1 to 2. I am open to doing this through a formula field or workflow action or Apex-- whatever works. Any help is greatly appreciated. 

Hello,

I am quering a Prive book Entry, and i made sure that there are no fuplicates,

but still i have below error
 
Line: 122, Column: 1
System.DmlException: Insert failed. First exception on row 7; first error: FIELD_INTEGRITY_EXCEPTION, This price definition already exists in this price book: []

Any suggestions
Hello,

I am trying to accomplish the following:
  • Call an external REST API on Account page load
  • JSON response will be parsed into a table within a custom object
I have already coded the REST call in apex. How do I get this to interact with a custom object and run on page load? Do I need to use visualforce? I am having some trouble understaing how all of these elements interact, so any guidance would be helpful. Thanks!
Hi everyone. I am trying to develop a VisualForce page which will allow users to selectively send Case attachments to an external service. The way I'm doing this is by selecting all ContentDocumentLinks related to the Case, then displaying them in a table with a "Send" button next to each one.

I thought about using apex:actionSupport as a way to store the ID of the specific ContentDocumentLink, however the variable I'm using to store the ContentDocumentLink is NULL after clicking.

Here is the relevant portion of my VF page:
<apex:pageBlockTable value="{!cdls}" var="cdl">
    <apex:column>
        <apex:facet name="header">Documents</apex:facet>
        <apex:outputText value="{!cdl.ContentDocument.Title}"/>
        <apex:form>
            <apex:commandButton value="Send">
                <apex:actionSupport event="onclick" action="{!sendCdl}">
                    <apex:param name="cdlToSend" value="{!cdl.Id}" assignTo="{!cdlToSend}"/>
                </apex:actionSupport>
            </apex:commandButton>
        </apex:form>
    </apex:column>
</apex:pageBlockTable>

And here is the relevant portion of my controller:
public class SendToV1_Button {

    ...

    public Id cdlToSend {get; set;}

    ...

    public PageReference sendCdl() {
        System.debug(cdlToSend);
        return redirect();
    }
}

Any help would be greatly appreciated.​​​​​​​
Hi all, I got authentication and a first query ($query1) working, but I don't succeed making a query with a where clause in it ($query2). It results in a Bad Request. Any help is greatly appreciated.
 
$instance_url = Salesforce_user::get_instance_url($cg_user_id);

        $name = 'Guido';
        $query1 = "SELECT email , name , FirstName FROM LEAD LIMIT 1";
        $query2 = "SELECT email ,name, FirstName WHERE FirstName = '$name' FROM LEAD LIMIT 1";

        $query_encoded = urlencode($query1);
        $url = $instance_url . "/services/data/v45.0/query/?q=".$query_encoded;

        $options['headers']['content-type'] = 'application/json';
        
        $request = ApiController::$provider->getAuthenticatedRequest(
            'GET',
            $url,
            ApiController::static_oauth_get_access_token($cg_user_id), $options
        );

 
  • January 20, 2020
  • Like
  • 0
I'm in a little bit of struggle here. Have an error in this class. I tried to debug log this error but I don't understand why only one user is having this problem. For the rest of the users this error does not occur. This is the error:
 
Visualforce Page: /apex/VisitReportPage

caused by: System.NullPointerException: Attempt to de-reference a null object Class.VisitReportPageExtension.setIsFullReport: line 105, column 1 Class.VisitReportPageExtension.: line 65, column 1


This is my class:

 

public with sharing class VisitReportPageExtension {

    public List<SelectOption> PicklistValues { get; set; }
    public List<SelectOption> SecondPicklistValues { get; set; }
    public List<SelectOption> LastPicklistValues { get; set; }
    public Map<String, String> PicklistMap = new Map<String, String>();

    Public List<String> selectedValues { get; set; }
    Public List<String> SecondselectedValues { get; set; }
    public List<String> LastSelectedValues { get; set; }

    public static final String DEFAULT_TASK_STATUS = 'New';
    public static final String DEFAULT_TASK_PRIORITY = 'Normal';

    public static final String EVENT_URL_PARAM = 'EventID';
    public static final String RETURN_URL_PARAM = 'retUrl';
    public static final String RECORD_TYPE_URL_PARAM = 'RecordType';
    public static final String ACCOUNT_URL_PARAM = 'AccountId';
    public static final String OPPORTUNITY_URL_PARAM = 'OpportunityId';

    public static final String MEMO_REPORT_DEVELEOPER_NAME = 'Call_Memo';

    private List<List<String>> contactFields;
    private Map<ID, Contact> contactsCache = new Map<ID, Contact>();
    private Map<ID, User> userCache = new Map<ID, User>();
    private List<Message> messages = new List<Message>();
    private Map<Id, RecordType> mInteractionReportRecordTypes = null;

    private boolean isFullReport = true;
    private String retURLParam = null;

    public Boolean isNew { get; private set; }
    public Boolean showCreateContactPopup { get; set; }

    public List<ActionItemWrapper> actionItems { get; set; }
    public List<CustomerParticipantWrapper> customerParticipants { get; set; }
    public List<CustomerParticipantWrapper> internalParticipants { get; set; }
    public Contact contactHandler { get; set; }

    public Visit_Report__c record { get; set; }

    /**
     * Constructor creates instance of class. Loads Interaction 
     * report and related records.
     * @param  stdCtr Standard controller.
    */
    public VisitReportPageExtension(ApexPages.StandardController stdCtr) {
        customerParticipants = new List<CustomerParticipantWrapper>();
        internalParticipants = new List<CustomerParticipantWrapper>();

        record = (Visit_Report__c) stdCtr.getRecord();
        isNew = (stdCtr.getId() == null);

        mInteractionReportRecordTypes =
                RecordTypeService.getRecordTypesForObject('Visit_Report__c');
        loadParams();

        loadInteractionRecord();
        clearContactHandler();
        closeCreateContactPopup();
        setIsFullReport(record.RecordTypeId);


        selectedValues = new List<String>();
        SecondselectedValues = new List<String>();
        LastSelectedValues = new List<String>();

        PicklistValues = new List<SelectOption>();
        SecondPicklistValues = new List<SelectOption>();
        LastPicklistValues = new List<SelectOption>();
        List<Schema.PicklistEntry> FieldPicklistvalues =
                Visit_Report__c.Innovation_presented_to_customer__c.getDescribe().getPicklistValues();

        for (Schema.PicklistEntry FieldPicklistvaluesfor : FieldPicklistvalues) {
            PicklistValues.add(new SelectOption(FieldPicklistvaluesfor.getValue(),
                    FieldPicklistvaluesfor.getLabel()));
            PicklistMap.put(FieldPicklistvaluesfor.getvalue(),
                    FieldPicklistvaluesfor.getLabel());
        }
    }


    private void loadParams() {
        Map<String, String> mGetParams = ApexPages.currentPage().getParameters();
        record.EventID__c = mGetParams.get(EVENT_URL_PARAM);
        retURLParam = ApexPages.currentPage().getParameters().get(RETURN_URL_PARAM);

        //TODO get rec type 
        if (record.RecordTypeId == null) {
            if (mGetParams.containsKey(RECORD_TYPE_URL_PARAM)) {
                record.RecordTypeId = mGetParams.get(RECORD_TYPE_URL_PARAM);
            }
        }
        if (mGetParams.containsKey(ACCOUNT_URL_PARAM)) {
            record.Account_Name__c = mGetParams.get(ACCOUNT_URL_PARAM);
        }
    }

    private void setIsFullReport(Id recordTypeId) {
        isFullReport = (mInteractionReportRecordTypes.get(recordTypeId).DeveloperName != MEMO_REPORT_DEVELEOPER_NAME);
    }


    public boolean getIsFullReport() {
        return isFullReport;
    }
}

Why this error only occurs for only one user? I don't know why the code breaks. Any suggestions?
Not Able to edit Dynamic Dashboards as i has switched to Lightning UI
please suggest me if any one knows how can i achieve this requirement.

I want to check name case insensitive.
find below my code.
Public void UpdateStageNameSample(List<Opportunity> oppList){       
        List<Opportunity> optyList = new List<Opportunity>();
        String s = 'valued client';       
        for(Opportunity opp: oppList){
            if(opp.Name.contains(s.toUpperCase())){                
                opp.StageName = 'Sample';                           
            }
        }       
    }
  • November 25, 2015
  • Like
  • 0
Hi all,

How to get the selected day dates in the a given date range. For eg: i am selecting the date range from nov 1st to nov 30th. In this date range i want to get the monday date's i.e nov 2nd, nov 9th, etc.

Also i want to check a condition in soql like createddate day is equal to monday .

Kindly help me in this.

Regards,
Abinaya.

 
Hello,

I am integrating Google maps with Salesforce using below link
http://www.bulkified.com/How+to+use+the+Google+Maps+API+in+Salesforce.com

This above example gives a VF page to calculate.

I have below Objects:
ObjectA__C
CustomField__1
CustomField__2
CustomField__3

When Address is entered in CustomField__1 and CustomField__2, I want to calcuate the distance and time and fill it automatically in CustomField__3.

thanks for suggestion !
 
/-- Below is my Visual force page coding.

<apex:page Controller="CreateAccount" >

<head>
  <meta charset="utf-8"/>
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"/>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css"/>

  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>
</head>
<body>
 

 
</body>

<apex:stylesheet value="http://www.pageresource.com/wallpapers/wallpaper/latest-google-hd.jpg"/>
 <apex:form id="form">
 <div align="center" draggable="false" >
 <apex:image url="http://googlezone.ru/wp-content/uploads/2014/11/101020141429292562322.jpg" width="120" height="50"/>
 </div>
 <apex:pageBlock title="Create your Google Account" mode="edit"  id="pgblock"> 
 <apex:pageBlockSection >
 
 Firstname <apex:inputtext value="{!Firstname}"/>
 Lastname <apex:inputtext value="{!Lastname}"/>
 Username <apex:inputtext value="{!Username}"/>
 Password <apex:inputtext value="{!Password}"/>
 Retypepassword <apex:inputtext value="{!Retypepassword}"/>
 MobilePhone <apex:inputtext value="{!MobilePhone}"/>
 Email <apex:inputtext value="{!Email}"/>
 DateOfBirth <input type="text"  id="datepicker"/>
 </apex:pageBlockSection>
 <apex:commandButton action="{!saveRecord}" style="float:centre" styleClass="button" value="Save" id="recordID"  />
 </apex:pageBlock>
 </apex:form>
</apex:page>


Apex Class

public with sharing class CreateAccount {

    public PageReference saveRecord() {
       
 GoogleBlog__c blog = new GoogleBlog__c();
    blog.FirstName__c= Firstname;
    blog.Lastname__c= Lastname;
    blog.Password__c= Password;
    blog.RetypePassword__c= Retypepassword;
    blog.Username__c= Username;
    blog.MobilePhone__c= MobilePhone;
    blog.Email__c= Email;
    Date.valueOf(DateOfBirth);
    insert blog;
    system.debug('!!!!!!!!!!' + blog);
  return null;
  
    }

    public String getContact() {
        return null;
    }


Public string Firstname {get;set;}
Public string Lastname {get;set;}
Public string Username {get;set;}
Public string Password {get;set;}
Public string Retypepassword {get;set;}
Public string MobilePhone {get;set;}
Public string Email {get;set;}
Public string DateOfBirth {get;set;}
}

When i try to save a Recod it throws me error like this, Can anyone suggest me what is the mistake in thisERROR
Hi All,

I have a scenario like, I need to check the owner.division as a condition in my SOQL for a cusotm object query.  But for a custom object you cannot use the owner.division field in querying the value.

But, by using map, I can retreive all the user records and check the condition from there while looping the list of custom object records as follows, 

Map<id,User> ulist = new Map<id,User>([Select id,name,division from user]);

List<CustomObject__c> customList = [Select id,name, ownerid from CustomObject__c Where <my condition here>];

for(CustomObject__c c : customList)
{
       if(ulist.get(c.ownerid).division == 'xxxx')    //This is possible
       {
              //my logic goes here
        }
}

But, I want to check the condition of this division in the query itself. Becuase would like to filter out the records in the query. Is this possible?
Please help.

Thanks in advance!
 

Hey there,

 

I am attempting to deploy a very important Apex Trigger to production. In sandbox the trigger has a test coverage of 100% and works perfectly. However, upon deploying it failed because of two old tests.

 

This is the error:

 

TESTdestiny_Product_bIbU.myUnitTest() Class 18   Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [Destiny_Product__c]", Failure Stack Trace: "Class.TESThelper.__sfdc_testDestiny00: line 18, column 1 Class.TESTdestiny_Product_bIbU.myUnitTest: ... TESTdestiny_Service_bIbU.myUnitTest() Class 18  

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []", Failure Stack Trace: "Class.TESThelper2.__sfdc_testDestiny01: line 18, column 1 Class.TESTdestiny_Service_bIbU.myUnitTest: line 25, column 1"

 

 

 

What can I do?

 

Thankyou

please any one tell the process of moving app sandbox to producction?  and how to create sandbox and production and change sets ?

I am trying to update Parent and child object using Nest Query but child records are not getting saved.

 

Public List<Account> getAccount(){
list<Account> acc = [select Id, Name,Country, (select Id, FirstName,LastName,Email from contact) from account where Id=: a.Id];
return acc;
}

 

<apex:repeat var="a" value="{!Account}">
    <apex:outputText value="{!a.Name}"/>
      <apex:repeat var="c" value="{!a.Contacts}">
        <apex:inputfield value="{!c.FirstName}">
        <apex:inputfield value="{!c.LastName}">
        <apex:inputfield value="{!c.Email}">
      </apex:repeat>
<apex:repeat>

 

  • March 29, 2013
  • Like
  • 0

i am calling a batch class from finish method of another batch class and facing the above error

my finish method code is public class BatchPublicCampaignsToGoogle implements Database.Batchable, Database.Stateful, Database.AllowsCallouts {

public void finish(Database.BatchableContext BC){

        if(newBatch == true)
        {           CalendarSettings__c c= [Select Id, Name, CalendarId__c,CalendarQuery__c,FieldToDisplay__c from CalendarSettings__c WHERE Name = 'Internal marketing Calendar' LIMIT 1] ;
       BatchPublicCampaign bjob = new BatchPublicCampaign();
                Database.executeBatch(bjob);

        }
    }

} but i was facing error Database.executeBatch cannot be called from a batch or future method.

after finishing Batch request i am trying to call it(i have to call it for two times) again.so i call it.

How to get rid of error.i know we can call a batch class from finish method of a Batch Class but why i am getting this error ??

 

Hi All,
My requirement is to restrict users to save EVENTS thats being created for ACCOUNTS based on the below criteria.

 

If the START DATE of the Event is greater than TODAY ,"YOR_Activity_Status__c" cannot be set to "Completed" and the DESCRIPTION field cannot be NULL.

 

Below is the Events trigger thats being written to achieve this:

 

I am getting this error message while saving:

 

Please help me to solve this and correct if I am wrong.

 

Error: Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger myTrigger caused an unexpected exception, contact your administrator: myTrigger: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.myTrigger: line 3, column 1

 

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

trigger myeventvalidation on Event (after insert,after update) {
Set<Id> accIds = new Set<Id> ();
List<Account> lstAcc;
for(Event e: Trigger.new) {
if(e.StartDateTime > System.today() && e.YOR_Activity_Status__c == 'Completed' && e.Description ==NULL) {
e.addError('Not Possible');
}
}


lstAcc = [Select Id from Account where ID IN: accIds];

for(Event e: Trigger.new) {
if(Trigger.isInsert) {
for(Account a: lstAcc) {
if(e.StartDateTime > System.today() && e.YOR_Activity_Status__c == 'Completed' && e.Description ==NULL) {
e.addError('Not Possible');
}
}
}


else if(Trigger.isUpdate) {
if(e.StartDateTime > System.today() && e.YOR_Activity_Status__c == 'Completed' && e.Description ==NULL) {
for(Account a: lstAcc) {
if(a.Id == e.WhatId) {
e.addError('Not Possible');
}
}
}
}
}

update lstAcc;
}

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

  • March 26, 2013
  • Like
  • 0

I am using exact target to send emails to contacts , leads , campaigns, reports. But whenever I send an email to a lead or to a report (of leads or contacts) it fails with the following error message " (UpdateSyncStatus) Job failed after repeated subscriber sync attempts or sync timeout, job 8254 ".

 

Please help.

 

Thanks

Hi ,

I need to Clone a Record and once i clone i need the new record to have all fields carried and input the record Id from which it is cloned  ??

 

 

Please help me out with this very Urgent need

Hi,

 

I found this type of method in the Cook book area that helps remove script statements as I understand; however, I wanted to make sure that I understand the key in this type of code.

 

I wrote the looping version (not shown) and adding the MyCustomKey to the map as the key value but in the code below I thought if I put that field first in the SELECT statement it would pick that field but instead it looks like it automatically chooses the ID!  Is that a correct statement and if so is ther a work around to force it to select the key I want or do I have to stay with the loop method to get the results I want.

 

...

...

String DynamicQuery = 'SELECT MyCustomKey__c, Name, Id FROM Opportunity ' + WhereClause;
Map<String, Opportunity> OppsMap = new Map<String, Opportunity>((List<Opportunity>)Database.query(DynamicQuery));

...

...

 

 

Hi All 

I am trying to add user role as GroupMember  to a group 

Now i have problem that GroupMember have only two fields GroupId // which will take the group id and UserOrGroupId = // which will only take user id or a group id, but it is not taking role id

and as have check that when we insert role as GroupMember throw cofiguration, salesforce create a saprate group and populate RelatedId with the role id and then insert this new group in GroupMember 

exmaple if there is a Group G1 and we want to add a role R1 , what salesforce will do is it create a saparate Group (let call G2) and in G2 salesforce pupulate RelatedId with the role id and type =role and then add this group G2 as group member to G1 (in that case in group mebmber Groupid will be poulated with G1 and UserOrGroupId populated with G2 id)

Now problem is that RelatedId , is not writable throw apex code so i am not able to understand how to insert a Role as a group member using apex
  • January 07, 2016
  • Like
  • 0
Hi All 

I am trying to add user role as GroupMember  to a group 

Now i have problem that GroupMember have only two fields GroupId // which will take the group id and UserOrGroupId = // which will only take user id or a group id, but it is not taking role id

and as have check that when we insert role as GroupMember throw cofiguration, salesforce create a saprate group and populate RelatedId with the role id and then insert this new group in GroupMember 

exmaple if there is a Group G1 and we want to add a role R1 , what salesforce will do is it create a saparate Group (let call G2) and in G2 salesforce pupulate RelatedId with the role id and type =role and then add this group G2 as group member to G1 (in that case in group mebmber Groupid will be poulated with G1 and UserOrGroupId populated with G2 id)

Now problem is that RelatedId , is not writable throw apex code so i am not able to understand how to insert a Role as a group member using apex
  • January 07, 2016
  • Like
  • 0

just a quick question

If  i am developing a Offline Hybrid application in that case i belive we cannot use VF pages

I think i need to write HTML5 Page

 

As it's a offline application so if internaet is not aviable i belive users are not able to access the VF Pages

 

Please provide your valueable thoughts

  • June 10, 2013
  • Like
  • 0

Hi I have SAP Team but those gays don;t know how to generate WSDL from SAP
Can any once provide me a sample WSDL which can be consume in salesforce

OR can Provide the Step to generate WSDl from SAP system

 

it will be really grate help

  • April 12, 2013
  • Like
  • 0
I'm getting this error in the Visual force page but i have all the <td> tag ends with <./td>
Not sure why its triggering this error.

Please suggest.
Hi there,

The issue I am having is email tracking is counting activities on the Opportunities level, but not the Lead level when checking the Activities Report.

User-added image


The number you see in the screenshot (55) is all opportunities, but no leads. How do I get it to count both leads and opportunities?

Thanks.
Hey Everyone,

I'm trying to extract information via the Data Loader for a trailhead exercise. I've downloaded the application, and attempted to run the steps provided: 

The next step is to select the Account object, rename the file to be extracted and save it to your desktop. Note: All file names default to extract.csv. Renaming files prevents losing or overwriting them.
From the Select Salesforce Object list, select Account (Account).
In the Choose a target for extraction text box, enter Accounts Export.csv.
Click Browse…
Navigate to the desktop, click Save, then click Next.
Now create the necessary SOQL query.
Choose the query fields below:
Id
Name
Site
To complete the where clause to your query, type (or copy and paste) WHERE Type LIKE '%Customer%' in the text box so your query looks like this:
Select Id, Name, Site FROM Account WHERE Type LIKE '%Customer%'
Click Finish, then click Yes. The Operation Finished window appears, reporting the number of successful extractions. Note: The resulting export file should contain 11 records.

I get this message as a result: 
Site FROM Account WHERE Type LIKE ‘%Customer%’                                  ^ ERROR at Row:1:Column:51 line 1:51 no viable alternative at character '‘'
Can anyone provide some insight into how to fix this issue or how to proceed? 

Thanks for any help you could provide!
I want to input mobile number in Text field after saving the record the mobile number should display in (999) 999-9999 format..

I've tried creating a formula field of text and gave the below formula
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE( Phone__c ,
 '.', NULL),
 ' ', NULL), 
'-', NULL), 
')', NULL),
 '(', NULL)

But it doesn't worked for me.Can anyone help me doing this..
Hi,

I have a time-based workflow on the account which is updating a checkbox field to true when this action is executed I want my custom code to fire (after update) and make some updates on the object. Currently, the scheduled time-based action is changing to the future time when it comes to schedule execution time.

Thanks

Hello, I have a Contracts object where we keep track of company's contracts data. I want to create a field that keeps track of what number renewal cycle we are in. For example, if the original contracts ends on 2/2/20, so the renewal period begins on 2/3/20, once 2/3/20 hits, I want the "Renewal cycle #" field to automatically change from 0 to 1. Then when the next renewal cycle begins, I want "Renewal cycle #" to automatically change from 1 to 2. I am open to doing this through a formula field or workflow action or Apex-- whatever works. Any help is greatly appreciated. 

What I have so far covers 26% of the batch class. I'm not able to cover the execute portion of the batch class.

batch.cls
public class Batch implements Database.Batchable<sObject> {

	public Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id, jstcl__Consultant__r.Previous_Timesheet_Status__c FROM jstcl__TG_Timesheet__c WHERE jstcl__Placement__r.ts2__Status__c =\'Active\' AND jstcl__Placement__r.VMS__c = \'\' AND jstcl__Week_Ending__c = LAST_N_DAYS:4 AND jstcl__Status__c = \'Pending\'';
          return Database.getQueryLocator(query);
    }
   public void execute(Database.BatchableContext BC, List<jstcl__TG_Timesheet__c> timesheets){
       List<Contact> consultants = new List<Contact>();
       List<Contact> consultants2 = new List<Contact>();

       for(jstcl__TG_Timesheet__c timesheet : timesheets){
           Contact consultant = timesheet.jstcl__Consultant__r; 
           if (consultant == null) continue;
           consultant.Previous_Timesheet_Status__c = 'Pending';
           if(consultants.contains(consultant)){
               consultants2.add(consultant);
           }else{consultants.add(consultant);}
           }
           update consultants;
        }
   public void finish(Database.BatchableContext BC){}
}
test.cls
@istest 
private class Test {

static TestMethod void hfTest() {
     Profile prof = [select id from profile where name='system Administrator'];
     User usr = new User(alias = 'usr', email='us.name@vmail.com',
                emailencodingkey='UTF-8', lastname='lstname',
                timezonesidkey='America/Los_Angeles',
                languagelocalekey='en_US',
                localesidkey='en_US', profileid = prof.Id,
                username='testuser128@testorg.com');
                insert usr;
    Id idRecordId = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Candidate').getRecordTypeId();

    	ts2__Source__c source = new ts2__Source__c(Name = 'LinkedIn.com - Resume Search');
    	Account acc = new Account(Name = 'Express Scripts Holding Company');
        insert acc;
  		Account acc2 = new Account(Name = 'Candidates- 10-2018');
        insert acc2;
    	Contact con = new Contact(FirstName='fnadmes', LastName = 'lnamdes', Email = 'emadils@gmail.com', Phone = '9744800300', AccountId = acc2.Id, ts2__Source__c = source.Id, ts2__People_Status__c = 'Placed');
        Contact con2=new Contact(FirstName='fnames', LastName = 'lnames', Email = 'emails@gmail.com', Phone = '9743800300', AccountId=acc.Id, Relationship_Status__c = 'Lunch'); 
    	insert con; insert con2;
        ADP_Department__c adp = new ADP_Department__c(Name = 'Georgia');
        insert adp;
        ts2__Job__c job = new ts2__Job__c(Name = 'Software Engineer',Hiring_Manager_Contact__c = con2.Id);
        insert job;
        ts2__HolidayCalendar__c hcal = new ts2__HolidayCalendar__c(Name= 'Holiday Calendar');
        insert hcal;
        Labor_Category__c lcat = new Labor_Category__c(Name='Software Engineer 1');  
        insert lcat;
        ts2__Placement__c plc = new ts2__Placement__c(ts2__Job__c = job.Id, Contractor_Type__c = 'Technical Youth', Onboarding_Method__c= 'Staff Augmentation', ts2__Start_Date__c= Date.newInstance(2019, 1, 7), ts2__End_Date__c= Date.newInstance(2019, 2, 15),
        jstcl__HireType__c= 'W2', ADP_Department__c= adp.Id, ts2__Bill_Rate__c= 60.00, ts2__Pay_Rate__c= 30.00, jstcl__Invoice_Batch__c= 'Placement', ts2__Client__c= acc.Id, ts2__Hiring_Manager__c= con2.Id, jstcl__TimecardApprover__c= con2.Id, jstcl__HolidayCalendar__c= hcal.Id,
		State_Worked_In_Non_TFI_Placements__c= 'GA - Georgia', jstcl__Overtime_Bill_Rate__c= 60, jstcl__Burden__c= 0.20, jstcl__Accounts_Receivable_U__c= '00537000005d7F2AAI', jstcl__Terms__c= 'Net 60', ts2__Employee__c= con.Id, Labor_Category__c= lcat.Id);
		insert plc;
     	List<jstcl__TG_Timesheet__c> tsList = new List<jstcl__TG_Timesheet__c>();
    	 jstcl__TG_Timesheet__c ts = new jstcl__TG_Timesheet__c(jstcl__Consultant__c = con2.Id, jstcl__Placement__c = plc.Id, jstcl__Week_Ending__c = Date.newInstance(2019, 2, 15));
    tsList.add(ts);

	Test.startTest(); 
     Batch abcd = new Batch();
     ID batchprocessid = Database.executeBatch(abcd);
	Test.stopTest();
 }    
}

 

Good day,

On below trigger, my Insert and Update works. Please assist in an after delete trigger:

trigger calcClaim on Claim__c (after Insert, after Update, after Delete){
    
    set<Id> OccIds = new set<Id>();
    integer count = 0;
    for(Claim__c cl: Trigger.new)
    {    
        decimal temp = 0.0;
        try{temp = Trigger.old[count].Initial_Estimate__c;}
        Catch(exception e)
        {}
        if(cl.Initial_Estimate__c != temp)
        {
            OccIds.add(cl.Occurrence__c);
        } else
            if(Trigger.isDelete){
            /*{for(Claim__c c : trigger.old)
                system.debug(trigger.old);
                OccIds.add(cl.Occurrence__c);}*/
              count++;        
    }
    List<RK_Occurrence__c> occs  = ([SELECT id FROM RK_Occurrence__c where Id in :OccIds]);
    system.debug(occs);
    
    OccurenceClaimCalculator.calculateOcc(occs);
    
    }

  • February 03, 2020
  • Like
  • 0
Hi All,
I am struggling to find best way to create a lightning component which lists Accounts as well as Person Account records created within a time range ordered by distance from a certain location (lat/lng) along with pagination.

I already have a working components which lists all accounts created within time specified ordered by distance with Offset value for 10 records each time. But now to include all Person accounts in that list with ordering to work together on (Account+Person Accounts), is it possible to achieve with one query?
 
Hello,

I am quering a Prive book Entry, and i made sure that there are no fuplicates,

but still i have below error
 
Line: 122, Column: 1
System.DmlException: Insert failed. First exception on row 7; first error: FIELD_INTEGRITY_EXCEPTION, This price definition already exists in this price book: []

Any suggestions
i have written a increment trigger, where there are 5 custom field(India,ME,US,SEA,EU),all these fields are Incremented based on a formula field(PraticeLWC__Region__c), now if i update for ME the record should increment for 1 and 2, and if i delete a record related to ME and again add the record the record for ME it should take as 2 itself and not 3, how do i achive this

so basically when i add the records based on the region it should get incremented and if i delete a record it should get decremented

Region1
 
trigger Increment on Lead (before insert,Before Update) {
    if(trigger.isBefore && (trigger.isInsert || trigger.isUpdate || Trigger.IsUnDelete))  {
        List<Lead> leadList = [Select Id,PraticeLWC__Lead_No_Region_IN__c From Lead Where PraticeLWC__Region__c = 'India'];
        For(Lead l : trigger.New ) {
            if(l.PraticeLWC__Region__c == 'India') {
                if(leadList.size() > 0){
                    l.PraticeLWC__Lead_No_Region_IN__c = leadList.size()+0;   
                } else {
                    l.PraticeLWC__Lead_No_Region_IN__c = 1;
                }
            }
        }
        List<Lead> leadListt = [Select Id,PraticeLWC__Lead_No_Region_USA__c From Lead Where PraticeLWC__Region__c = 'US'];
        For(Lead m : trigger.New) {
            if(m.PraticeLWC__Region__c == 'US') {
                if(leadListt.size() > 0){
                    m.PraticeLWC__Lead_No_Region_USA__c = leadListt.size()+0;   
                } else {
                    m.PraticeLWC__Lead_No_Region_USA__c = 1;
                }
            }
        } 
        List<Lead> leadListm = [Select Id,PraticeLWC__Lead_No_Region_EU__c From Lead Where PraticeLWC__Region__c = 'EU'];
        For(Lead n : trigger.New) {
            if(n.PraticeLWC__Region__c == 'EU') {
                if(leadListm.size() > 0){
                    n.PraticeLWC__Lead_No_Region_EU__c = leadListm.size()+0;   
                } else {
                    n.PraticeLWC__Lead_No_Region_EU__c = 1;
                }
            }
        } 
        List<Lead> leadListo = [Select Id,PraticeLWC__Lead_No_Region_SEA__c From Lead Where PraticeLWC__Region__c = 'SEA'];
        For(Lead o : trigger.New) {
            if(o.PraticeLWC__Region__c == 'SEA') {
                if(leadListo.size() > 0){
                    o.PraticeLWC__Lead_No_Region_SEA__c = leadListo.size()+0;   
                } else {
                    o.PraticeLWC__Lead_No_Region_SEA__c = 1;
                }
            }
        }
        List<Lead> leadListp = [Select Id,PraticeLWC__Lead_No_Region_ME__c From Lead Where PraticeLWC__Region__c = 'ME'];
        For(Lead p : trigger.New) {
            if(p.PraticeLWC__Region__c == 'ME') {
                if(leadListp.size() > 0){
                    p.PraticeLWC__Lead_No_Region_ME__c = leadListp.size()+0;   
                } else {
                    p.PraticeLWC__Lead_No_Region_ME__c = 1;
                }
            }
        } 
        
    }                   
}

 
Start Method : 

 global APTS_UsageInput_ValidateDataBatch(APTS_UsageInputWrapper uirecordsfromloadfile)
    {
        workid=uirecordsfromloadfile.EQ_WorkId;
        inputrecord = uirecordsfromloadfile;
    }
String str='select id,EQ_UsageSchedule__c,EQ_ValidationError__c,EQ_ProcessStatus__c,APTS_Legacy_ExternalID__c, EQ_ServiceCode__c,EQ_Account__c,EQ_AssetLineItem__c ,EQ_AccountLocation__c, EQ_IssueNumber__c, EQ_SourceSystem__c,EQ_RecordKey__c, EQ_WorkId__c, EQ_QuantityID__c, EQ_LoadMonth__c, EQ_Quantity__c from EQ_TempSSP1Data__c where EQ_WorkId__c=:workid';
    global database.QueryLocator start(Database.BatchableContext BC)
    {
      return Database.getQueryLocator(str);
   }
Execute Method : 
 global void execute(Database.BatchableContext BC, List<EQ_TempSSP1Data__c> scope)
   {
     String key;
           set<String> distinctTempSsp1DataSourceSystems = new set<String>();
           set<String> issueNumbers = new set<String>();
           set<String> serviceCodes = new set<string>();
           set<String> areAllIssueNumbersPresent = new set<String>();
           list<string> errors=new list<string>();
           Set<String> pickListValuesList= new Set<String>();
           String SourceSystem='004:Invalid Source System';
           string IssueNumber = '001:IssueNumber Does not exists';
           string DuplicatesFound = '012:Duplicate issue number service code pair record found';
           string NotValidDateRange = '006:sageData Date is not in the valid(Effective) Date range';
           string ServiceCode = '002:Fee Code Does not exists';
           string ServiceCodeIssueNumberCombo = '007:Asset doesnot exists for the Account-Fee Code'; 
           string missingAssetData = '008: every record from the load file doesnot have existing Account or AccountLocation';
           string MultipleAssetsPerFeeCode = '013: Multiple Assets for Account or Acc Location per Fee Code';
           string InactiveAccount = '003:Account is Inactive';
           list<String> duplicateSourcecode= new list<String>();
           list<String> encounterSourcecode= new list<String>();
           list<String> duplicateIssue= new list<String>();
           list<String> encounterIssue= new list<String>();
           list<EQ_SSP1Data__c> ssp1Data =new list<EQ_SSP1Data__c>();
           list<EQ_SSP1Data__c> ssp1DataRef =new list<EQ_SSP1Data__c>();
           map<string,list<EQ_TempSSP1Data__c>> tempSsp1DataIssueFeeCodeKey = new map<string,list<EQ_TempSSP1Data__c>>();
           map<string,list<EQ_SSP1Data__c>> ssp1DataAccountIdKey = new map<string,list<EQ_SSP1Data__c>>();
           map<string,list<EQ_SSP1Data__c>> ssp1DataAccountLocationIdKey = new map<string,list<EQ_SSP1Data__c>>();
           list<String> encounterList= new list<String>();
           list<String> duplicateList= new List<String>();
           list<ErrorTempSSP1Data > errorTempSection   = new list<ErrorTempSSP1Data >();
           
          system.debug(': Heap size is-1 ' + limits.getHeapSize() + ' enforced is ' + limits.getLimitHeapSize()); 
          tempSsp1Data=scope;
         system.debug('Validate Batch -Scope list contains---->'+tempSsp1Data);
           //---------------------------validation 1---------------------------------------------------------------------
         // ErrorChecker with tempSsp1Data for valid values of the fields and check SourceSystem is existing in system
         
                
           // Blank Check on records
          list<ErrorTempSSP1Data> errorTempSection_1= new list<ErrorTempSSP1Data>();
          for(EQ_TempSSP1Data__c record : tempSsp1Data)
              {
                 distinctTempSsp1DataSourceSystems.Add(record.EQ_SourceSystem__c);
                serviceCodes.add(record.EQ_ServiceCode__c);
                 list<String> nullerrors= new list<String>();
                  map<ID,list<String>> nullCheckmap= new map<ID,list<String>>();
                 nullerrors = ErrorChecker.ValidateImportData(record);
                 system.debug('Null Errors List ->'+nullerrors);
                 if(nullerrors.size()!=0)
                 {
                    if (!errorTempData.ContainsKey(String.valueof(record)))
                        {
                            ErrorTempSSP1Data ins = new ErrorTempSSP1Data();
                            ins.TempData=record;
                            ins.Errors=nullerrors;
                             nullCheckmap.put(ins.TempData.id,ins.Errors);
                             ins.mapErrors=nullCheckmap;
                             errorTempSection_1.add(ins);
                             system.debug('Null Errors if any ->'+ins.mapErrors );
                         } 
                 }
                  
              }
         if(errorTempSection_1.size()!= 0)
                {
                    for(ErrorTempSSP1Data errorTemp:errorTempSection_1)
                    {
                        key = string.valueof(errorTemp.TempData);

                        if (!errorTempData.ContainsKey(key))
                         {
                            errorTempData.put(key,errorTemp);
                         }
                    }
             }
        system.debug('errorTempData data1--->'+errorTempData.values());
       system.debug(': Heap size is--2 ' + limits.getHeapSize() + ' enforced is ' + limits.getLimitHeapSize());
       
       // Validation for duplicate IssueNumber-ServiceCode pairs in the load file
             for(EQ_TempSSP1Data__c x:tempSsp1Data)
             {
              list<String> error1= new list<String>();
              map<ID,list<String>> m1= new map<ID,list<String>>();
              if((x.EQ_IssueNumber__c!=null || x.EQ_IssueNumber__c!='')&& (x.EQ_ServiceCode__c!=null||x.EQ_ServiceCode__c!=''))
                
              {
                  String uniqueChecksum= x.EQ_IssueNumber__c + x.EQ_ServiceCode__c;
                  List<EQ_TempSSP1Data__c> entitiesForKey = tempSsp1DataIssueFeeCodeKey.get(uniqueChecksum);
                    if (entitiesForKey == null) 
                    {
                        entitiesForKey = new List<EQ_TempSSP1Data__c>();
                        tempSsp1DataIssueFeeCodeKey.put(uniqueChecksum, entitiesForKey);
                    }    
                  entitiesForKey.add(x);
                 tempSsp1DataIssueFeeCodeKey.put(uniqueChecksum,entitiesForKey);
                 if(!encounterList.contains(uniqueChecksum))
                 {
                    encounterList.add(uniqueChecksum);
                 }
                 else
                 {
                     ErrorTempSSP1Data ins = new ErrorTempSSP1Data();
                         ins.TempData=x;
                         error1.add(DuplicatesFound);
                         ins.Errors=error1;
                         m1.put(ins.TempData.id,ins.Errors);
                         ins.mapErrors=m1;
                         system.debug('Duplicate issue number service code error if any-->'+ ins.mapErrors);
                        errorTempSection.add(ins);
                 }
              }
           }       
             
           
             if(errorTempSection.size()!= 0)
                {
                    for(ErrorTempSSP1Data errorTemp :errorTempSection)
                    {
                        key = string.valueof(errorTemp.TempData);

                        if (!errorTempData.ContainsKey(key))
                        {
                            errorTempData.put(key, errorTemp);
                            
                         }

                    }
                }

  for(ErrorTempSSP1Data item:errorTempData.Values())
                {
                    for(String st:item.Errors)
                    {
                       errorsList.add(st);
                    }
                    
                }
         count=errorsList.size();
         system.debug('ErrorList^^^^^'+errorsList);
         system.debug('ErrorList count^^^^^'+count); 
          status = (count == 0)
                ? 'PegaCallbackStatus.Complete'
                : 'PegaCallbackStatus.Error';
       //-----------------------------
 //Update error field on tempssp1 records
        EQ_TempSSP1Data__c tempSsp1Record=new EQ_TempSSP1Data__c() ;
        String str='';
       list<EQ_TempSSP1Data__c> listtoupdate1 = new list<EQ_TempSSP1Data__c>();
       list<EQ_TempSSP1Data__c> tempSsp1Recordlist = new list<EQ_TempSSP1Data__c>();
       system.debug(': Heap size is--11 ' + limits.getHeapSize() + ' enforced is ' + limits.getLimitHeapSize());
        if(status=='PegaCallbackStatus.Error')
        {
           for(ErrorTempSSP1Data record:errorTempData.Values())
           {
               str='';
               list<String> listOferrors = record.mapErrors.get(record.Tempdata.id);
               if(listOferrors.size()>0)
               {
                for (integer i = 0; i < listOferrors.size() ;i++)
                    {
                        str=str+record.mapErrors.get(record.Tempdata.id);
                    }
                  
                    if(str!=null)
                    {
                         record.TempData.EQ_Errors__c =str;
                         record.TempData.EQ_ProcessStatus__c ='failure';
                         listtoupdate1.add(record.TempData);
                    }
                }
                
                
           }
            update listtoupdate1;
            
                
           }
  
   
   }


Finish :

global void finish(Database.BatchableContext BC)
   {
       
         status = (count == 0)
                ? 'PegaCallbackStatus.Complete'
                : 'PegaCallbackStatus.Error';
       
       
       validationHelper1.PegaCallbackServiceCall(status,count,workid,errorTempData);
}
 
How to send Case Id,return Type as CSV file in apex class and method functinaulty?
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_system_remoteobjectcontroller.htm

RemoteObjectController
Use RemoteObjectController to access the standard Visualforce Remote Objects operations in your Remote Objects override methods.

RemoteObjectController Methods
The following are methods for RemoteObjectController. All methods are static.
create(type, fields) Create a record in the database.
del(type, recordIds) Delete records from the database.
retrieve(type, fields, criteria) Retrieve records from the database.
updat(type, recordIds, fields) Update records in the database.

retrieve(type, fields, criteria)
Retrieve records from the database.
Signature
public static Map<String,Object> retrieve(String type, List<String> fields, Map<String,Object> criteria)
Parameters
type
Type: String
The sObject type on which retrieve is being called.
fields
Type: List<String>
The fields to retrieve for each record.
criteria
Type: Map<String,Object>
The criteria to use when performing the query.


My question is: How do set the criteria like 'where' and 'orderby' (in the java script below) in the retrieve method for RemoteObjectController
<apex:remoteObjectsjsNamespace="RemoteObjectModel">    
    <apex:remoteObjectModel name="Contact" fields="FirstName,LastName"/>  
</apex:remoteObjects>

<script>
var ct = new RemoteObjectModel.Contact();
ct.retrieve( 
    { where: { 
        FirstName: {eq: 'Marc'}, 
        LastName: {eq: 'Benioff'} 
      }, 
      orderby: [ {LastName: 'ASC'}, {FirstName: 'ASC'} ],
      limit: 1 },  

    function(err, records) { 
        if (err) { 
            alert(err); 
        } else { 
            console.log(records.length); 
            console.log(records[0]); 
        } 
    } 
);
</script>
 
public class TestRemoteActionOverrideController{
    @RemoteAction
    public static Map<String,Object> retrieve(String type, List<String> fields, Map<String, Object> criteria) {
        fields.add('Name');

        //
        // place holder for converting criteria below in java script to apex
        //
        // { where: { 
        // FirstName: {eq: 'Marc'}, 
        // LastName: {eq: 'Benioff'} 
        // }, 
        // orderby: [ {LastName: 'ASC'}, {FirstName: 'ASC'} ],
        // limit: 1 }
        
        // call through to the default remote object controller with our modified field list.
        return RemoteObjectController.retrieve(type, fields, criteria);
    }
}

 
Hello Everyone,

I have observed a wired behavior with "Blob.toPDF(<string>)" Salesforce Apex API's , this method strips off Chinese characters and there is no option to set character encoding, please find below the sample code.


String targetString = 'Before - 測試中文字 - After';

Attachment attachmentPDF = new Attachment();
attachmentPDF.parentId = '<parent record id>';
attachmentPDF.Name = 'Test' + '.pdf';
attachmentPDF.ContentType = 'application/pdf; charset=UTF-8';
attachmentPDF.body = Blob.toPdf(targetString); //This creates the PDF content
insert attachmentPDF;

I have also tried encoding Chinese character content to UTF-8 but this displays all the encoded characters in PDF,

String targetString = 'Before - 測試中文字 - After';
String encodedString = EncodingUtil.urlEncode(targetString,'UTF-8');
System.debug('##encodedString:-'+encodedString);

Attachment attachmentPDF = new Attachment();
attachmentPDF.parentId = '<parent record id>';
attachmentPDF.Name = 'Test' + '.pdf';
attachmentPDF.ContentType = 'application/pdf; charset=UTF-8';
attachmentPDF.body = Blob.toPdf(encodedString); //This creates the PDF content
insert attachmentPDF;

Please help.

Thanks
-Tejas(+91 9663266726)