• PRABHAKARAN CHOCKALINGAM
  • NEWBIE
  • 85 Points
  • Member since 2015

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 0
    Questions
  • 27
    Replies
Hello,

I have a basic trigger that needs to update a lookup field (Discount_code_LU__c). I'm just trying to map the lookup field with the text field (Discount_code__c). The lookup field (Discount_code_LU__c) is related to the Product object. Any assistance will be greatly appreciated!

Thank you!!
trigger UpdateOpportunityProduct on Opportunity (before insert){
    
 for(Opportunity opp:Trigger.new)
 {
     opp.Discount_code_LU__c =  opp.Discount_code__c ;
          
}
}

 
  • February 08, 2017
  • Like
  • 0
Hello,

I am trying to write a test for a trigger that is firing a future apex callout and I get this error:
Methods defined as TestMethod do not support Web service callouts
The trigger calls the callBillingService method from this class:
public class BillingCalloutService {
    //Implement business and callout logic methods here
    @Future(callout=true)
    public static void callBillingService(List<Id> recordIds) {
        List<Project__c> projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];

        List<Project__c> projectsToUpdate = new List<Project__c>();

        String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;
        String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;

        String auth = username + ':' + password;
        String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));

        for(Project__c p : projects) {

            BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();
            service.inputHttpHeaders_x = new Map<String, String>();
            service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);

            BillingServiceProxy.project project = new BillingServiceProxy.project();
            project.username = username;
            project.password = password;
            project.projectRef = p.ProjectRef__c;
            project.billAmount = p.Billable_Amount__c;

            if(service.billProject(project).equals('ok')){
                projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));
            }
        }
        shouldIRun.stopTrigger();
        upsert projectsToUpdate ProjectRef__c;
    }
}
here is the test class:
 
@IsTest
private class BillingCalloutServiceTest {

    @IsTest
    private static void testBillingCalloutService() {
    Account a = new Account(Name = 'Acme');
    insert a;
    Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());
    insert o;
    Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);
    insert p;

    insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');

    Test.startTest();
    Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());
      p.Status__c = 'Billable';
      update p;
    Test.stopTest();
    // runs callout and check results
    p = [select Status__c from Project__c where id =: p.id];
    System.assertEquals('Billed', p.Status__c);
    }

}

Could you please advise ?

Thanks a lot.
 
I created a simple workflow to automatically opt contacts out of email, mailings, and phone calls when they're marked as deceased. I've tested it, and it's working well. 

However, I'm getting an error when I try to do a mass upsert to trigger the workflow on all those who are already marked as deceased. Here's what I did:

1. Pull down a list of everyone already marked deceased. List includes Contact ID and the Deceased field.
2. Used Data Loader to update the contacts, matched on ID. The update should trigger the workflow.
3. Out of 1,650 contacts, I had 65 successes. The rest errored. Here's the error message:

The record couldn’t be saved because it failed to trigger a flow. A flow trigger failed to execute the flow with version ID 30170000000bpoL. Flow error messages: <b>An unhandled fault has occurred in this flow</b><br>An unhandled fault has occurred while processing the flow.  Please contact your system administrator for more information.  Contact your administrator for help.

Not sure why it's erroring in the first place, or why it would have thrown up an error for some but not others? Help?
In our existing database, the customer number serves as the link between Account and Contact objects. Can we use that field instead of ID field provided by Forces.com? Your suggestion will be much appreacited.
I have a process that creates a new Opportunity when a new Event is created where there are no open Opporunities under the Account. However, the related to field on the Event defaults to the Account. How can I automate this to update the related to ID to the new Opportunity ID?
Hello,

I have a basic trigger that needs to update a lookup field (Discount_code_LU__c). I'm just trying to map the lookup field with the text field (Discount_code__c). The lookup field (Discount_code_LU__c) is related to the Product object. Any assistance will be greatly appreciated!

Thank you!!
trigger UpdateOpportunityProduct on Opportunity (before insert){
    
 for(Opportunity opp:Trigger.new)
 {
     opp.Discount_code_LU__c =  opp.Discount_code__c ;
          
}
}

 
  • February 08, 2017
  • Like
  • 0
Hello,

I am trying to write a test for a trigger that is firing a future apex callout and I get this error:
Methods defined as TestMethod do not support Web service callouts
The trigger calls the callBillingService method from this class:
public class BillingCalloutService {
    //Implement business and callout logic methods here
    @Future(callout=true)
    public static void callBillingService(List<Id> recordIds) {
        List<Project__c> projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];

        List<Project__c> projectsToUpdate = new List<Project__c>();

        String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;
        String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;

        String auth = username + ':' + password;
        String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));

        for(Project__c p : projects) {

            BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();
            service.inputHttpHeaders_x = new Map<String, String>();
            service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);

            BillingServiceProxy.project project = new BillingServiceProxy.project();
            project.username = username;
            project.password = password;
            project.projectRef = p.ProjectRef__c;
            project.billAmount = p.Billable_Amount__c;

            if(service.billProject(project).equals('ok')){
                projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));
            }
        }
        shouldIRun.stopTrigger();
        upsert projectsToUpdate ProjectRef__c;
    }
}
here is the test class:
 
@IsTest
private class BillingCalloutServiceTest {

    @IsTest
    private static void testBillingCalloutService() {
    Account a = new Account(Name = 'Acme');
    insert a;
    Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());
    insert o;
    Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);
    insert p;

    insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');

    Test.startTest();
    Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());
      p.Status__c = 'Billable';
      update p;
    Test.stopTest();
    // runs callout and check results
    p = [select Status__c from Project__c where id =: p.id];
    System.assertEquals('Billed', p.Status__c);
    }

}

Could you please advise ?

Thanks a lot.
 
I have written below Cross Object value transition trigger ...
When the status field on Monthly Activity is either of the 4 values, I would like to capture these 4 values from Approver_Editorial/Financial and ApproverE/F_Date ... And then assign them to 4 fields on ExpertMmonthlyAudit object...

The only connection between the 2 objects is via a lookup.

Unfortunately the fields on the 'ExpertMmonthlyAudit' are still blank.
Not sure what I am doing wrong.
Can any one care to point out.
Thanks!
trigger updateValues on Monthly_Activity__c (before insert, before update) {
    Set<Id> Ids= new Set<Id>();
    for ( Monthly_Activity__c m: Trigger.new){
        if(m.Status__c == 'Rejected by Editorial' || m.Status__c == 'Submitted to Finance' 
        || m.Status__c == 'Rejected by Finance' || m.Status__c == 'Approved'){
               Ids.add(m.Id);
         }
       }  
    List<Monthly_Activity__c> mList = new List<Monthly_Activity__c>([SELECT Id, Status__c, Approver_Editorial__c, Approver_Financial__c,ApproverE_Date__c, ApproverF_Date__c FROM Monthly_Activity__c WHERE Id in:Ids]);
    
    for(Monthly_Activity__c temp : mList){
    
    ExpertMonthlyAudit__c mVal = new ExpertMonthlyAudit__c();
    mVal.EditName__c = temp.Approver_Editorial__c;
    mVal.FinName__c = temp.Approver_Financial__c;
    mVal.EditDate__c =temp.ApproverE_Date__c;
    mVal.FinDate__c = temp.ApproverF_Date__c;
    insert mVal;
                                                                          
   }
}

 
I am trying to finish the creation of a formula field in the trail head module,but was facing with this error.

<--Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [types__c, model__c]: [types__c, model__c]--> 

here comes the screen shot of the work i did.
User-added image

I created formula field on the case object-fields-custom fields,the field accessibility is given to all the profiles out there.
can anyone help me out where i have made the mistake..

i can reckon i have gone somehere silly.. 
help appreciated..

thanks
  • February 07, 2017
  • Like
  • 0
While looking into an existing code where a query used as "SELECT  Opportunity.Id, Opportunity.Name  From Opportunity where Opportunity.AccountID ="XXXX". As per my understanding, neither Opportunity nor any Object in Salesforce has the field "ID".Yet the field is used in querying in SF and result is also succesfully returned.Can anyone help where this "ID" field is coming from
I am using a standard object and custom object thats related.  I am trying to solve for the following:  When LLC_BI_Status__c = Complete, update the Opportunity stage (stagename) to "Won".  Object Names; Product Package (API= Product_Package). Status (LLC_BI_Status__c)  and Opportunitites (Stagename)
 
Hello friends
I have a scenario where when a account field is udpated corresponding contact field descriptions also gets updated.
pls see code as follows , its working.
 
public class Account_ContactDescription
{
      public void Update_ContactDescription(Set<ID> accountIDs)
   {
      List<Contact> contactsToUpdate=new List<Contact>();
      
      List<Contact> conaccountIDs=[select Id,FirstName,LastName from contact where accountID IN :accountIDs];
      
      if (conaccountIDs.size() > 0 && conaccountIDs != NULL)
      {
         for(Contact con:conaccountIDs)
         {
         contactsToUpdate.add(new Contact(ID=con.ID, Description=con.FirstName+' '+con.LastName));
            
         }
      }
      
      Database.Update(contactsToUpdate,false);
   }
}

trigger trg_updateContactDescripton on Account (before Update) 
{
  
  if (trigger.IsUpdate)
  {
    Account_ContactDescription obj = new Account_ContactDescription();
    obj.Update_ContactDescription(Trigger.NewMap.Keyset());
  }
}

If I use   after Update event also it works, then my question is what is the specific case scenario where a user is forced to use after trigger.
pls elaborate

thanks
vandana
Hello,

I've seen this topic come up, but I don't see any answers that seem to be relevant to my case.

I am using the Rails restforce Gem to connect to Salesforce.  I am able to connect, pull, update, create data, but after some period of time my session seems to expire with the message "INVALID_SESSION_ID: Session expired or invalid".  

Here is the code I am using to initialize my client:
 
@client = Restforce.new oauth_token: options[:salesforce_token],
      refresh_token: options[:salesforce_refresh_token],
      instance_url:  options[:salesforce_instance_url],
      client_id:     sales_force_client_id,
      client_secret: sales_force_client_secret,
      authentication_callback: Proc.new { |x| Rails.logger.debug x.to_s }

And when I make a request (again after a period of time) I get the following back:
 
url: "https://cs13.salesforce.com/services/data/v38.0/sobjects/Contact"
  method: :post
  headers: {"User-Agent"=>"Faraday v0.9.2", "Content-Type"=>"application/json", "Authorization"=>"OAuth XXXXXXXXXXX"}
  body: "{\"LastName\":\"Test\",\"FirstName\":\"Test \",\"MailingCountry\":\"United States\",\"MailingPostalCode\":\"29464\",\"MailingCity\":\"Mount Pleasant\",\"MailingState\":\"South Carolina\",\"Phone\":\"1-555-555-5555\",\"Business_Contact__c\":true,\"RecordTypeId\":\"01238000000UVfW\"}"
D, [2017-02-06T14:43:14.791977 #99698] DEBUG -- response:
  status: "401"
  headers: {"date"=>"Mon, 06 Feb 2017 19:43:07 GMT", "x-content-type-options"=>"nosniff", "x-xss-protection"=>"1; mode=block", "content-security-policy"=>"reflected-xss block;report-uri /_/ContentDomainCSPNoAuth?type=xss, referrer origin-when-cross-origin", "set-cookie"=>"BrowserId=I2nltdq0SSqJ7KinYQEyMw;Path=/;Domain=.salesforce.com;Expires=Fri, 07-Apr-2017 19:43:07 GMT", "expires"=>"Thu, 01 Jan 1970 00:00:00 GMT", "www-authenticate"=>"Token", "content-type"=>"application/json;charset=UTF-8", "transfer-encoding"=>"chunked", "connection"=>"close"}
  body: "[{\"message\":\"Session expired or invalid\",\"errorCode\":\"INVALID_SESSION_ID\"}]"

Any pointers would be greatly appreciated!

Hi,

I am feeling strange issue that, I have created scheduled job to run everyday at 09:00 AM to update the checkbox field on basis of pull out the records on filter criterion from salesforce database.

But Scheduled job page is showing next fire time for the job, but it stuck at queued status even it passed the date.

 

Please help me the same, 

Hi,

I am getting the below exception in my apex trigger. Can anyone suggest me how to resolve this issue?

FATAL_ERROR|System.LimitException: Query of LOB fields caused heap usage to exceed limit.

Thanks,
Vijay
For anyone who may have faced the same task, here is a sample code for displaying filtered tasks and events to display in Account details.
As you may see, I've filtered the results via SOQL, you may extend the code to improve or anything else :)
I used a workaround for reading the events, because they are not readable via the 15 digits AccountId but with the 18 digit once. Crazy, but it works. All of you may correct me, if this may not be usable in future.

1) Add a apex class:
public with sharing class RelatedActivitesTest {
public List<Task> tasksLimited {get;set;}
public List<Event> eventsLimited {get;set;}
public List<Contact> conts {get;set;}
public RelatedActivitesTest(ApexPages.StandardController con){
conts = [SELECT id FROM Contact WHERE AccountId =:ApexPages.currentPage().getParameters().get('id')];
tasksLimited= [select id,activitydate,createdbyid,description,subject,whoid,type,ownerid from task
where (
accountid=: ApexPages.currentPage().getParameters().get('id') or
WhoId in :conts
) and
subject not in ('Rechnung per E-Mail','Rechnung erstellt','Box-Austausch erstellt','Support angelegt','Gutschrift erstellt','Lizenzdatei per E-Mail','Webroot-Lizenzzertifikat per E-Mail','Teilgutschrift erstellt','PreSales angelegt','Angebot per E-Mail')
order by activitydate desc limit 1000];
// Used convertID to get the external url repesantation of Account Id, which helps me getting all events. Internal Ids won't work somehow.
eventsLimited= [select id,activitydate,createdbyid,description,subject,whoid,type,ownerid,whatid FROM Event
WHERE (
WhatId =:convertID(ApexPages.currentPage().getParameters().get('id')) or
WhoId =:convertID(ApexPages.currentPage().getParameters().get('id')) or
AccountId =:convertID(ApexPages.currentPage().getParameters().get('id')) or
WhoId in :conts
) and
subject not in ('Rechnung per E-Mail','Rechnung erstellt','Box-Austausch erstellt','Support angelegt','Gutschrift erstellt','Lizenzdatei per E-Mail','Webroot-Lizenzzertifikat per E-Mail','Teilgutschrift erstellt','PreSales angelegt','Angebot per E-Mail')
order by activitydate desc limit 1000];
}
public static String convertID(String id){
if(id.length() == 18) return id;
String suffix = '';
for(Integer i=0;i<3;i++){
Integer flags = 0;
for(Integer j=0;j<5;j++){
String c = id.substring(i*5+j,i*5+j+1);
if(c.compareTo('A') >= 0 && c.compareTo('Z') <= 0){
flags += 1 << j;
}
}
if (flags <= 25) {
suffix += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.substring(flags,flags+1);
}else suffix += '012345'.substring(flags-26,flags-26+1);
}
return id+suffix;
}
}


Create a visual force page:
<apex:page standardController="Account" extensions="RelatedActivitesTest" tabStyle="Account">
<apex:pageBlock title="Filtered Events">
<apex:outputPanel layout="block" style="overflow:auto;width:100%;height:200px">
<apex:dataTable value="{!eventsLimited}" var="eventLimited" cellpadding="4" bgcolor="white" rowClasses="even,odd">
<apex:column headerValue="Subject">
<apex:outputLink value="/{!URLFOR(eventLimited['id'])}">{!eventLimited.subject}</apex:outputLink>
</apex:column>
<apex:column headerValue="Description">
<apex:outputtext value="{!LEFT(eventLimited.description, 150)}" />
</apex:column>
<apex:column value="{!eventLimited.whoid}" headerValue="Member" />
<apex:column value="{!eventLimited.type}" headerValue="Type" />
<apex:column value="{!eventLimited.activitydate}" headerValue="Activity Date" />
<apex:column value="{!eventLimited.ownerid}" headerValue="Assigned To" />
</apex:dataTable>
</apex:outputPanel>
</apex:pageBlock>
<apex:pageBlock title="Filtered Tasks">
<apex:outputPanel layout="block" style="overflow:auto;width:100%;height:200px">
<apex:dataTable value="{!tasksLimited}" var="taskLimited" cellpadding="4" bgcolor="white" rowClasses="even,odd">
<apex:column headerValue="Subject">
<apex:outputLink value="/{!URLFOR(taskLimited['id'])}">{!taskLimited.subject}</apex:outputLink>
</apex:column>
<apex:column headerValue="Description">
<apex:outputtext value="{!LEFT(taskLimited.description, 150)}" />
</apex:column>
<apex:column value="{!taskLimited.whoid}" headerValue="Member" />
<apex:column value="{!taskLimited.type}" headerValue="Type" />
<apex:column value="{!taskLimited.activitydate}" headerValue="Activity Date" />
<apex:column value="{!taskLimited.ownerid}" headerValue="Assigned To" />
</apex:dataTable>
</apex:outputPanel>
</apex:pageBlock>
</apex:page>


The visualforce page is connected to Account so you can add it to the Account view in your pagelayout.
If you want to change the filter, just change them to fit your needs.

Anyway, if you like my first post, give me a "like".

Thanks
Thimo
 
  • November 26, 2014
  • Like
  • 6
In Pat Patterson's article,"Calling the Force.com REST API from Visualforce Pages, Revisited", https://developer.salesforce.com/blogs/developer-relations/2013/06/calling-the-force-com-rest-api-from-visualforce-pages-revisited.html, he points out that since Summer '13 the REST API is directly accessible from VisualForce pages, and gives examples of doing so with JQuery. I translated the example to use AngularJS for the JavaScript engine.
Code can be found at https://gist.github.com/rrcook/0f07838bc3d35d017206