• Tad Aalgaard 3
  • SMARTIE
  • 627 Points
  • Member since 2014

  • Chatter
    Feed
  • 20
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 11
    Questions
  • 153
    Replies
Hello,

I have a button like below on Opportunity object
User-added image
 
<apex:page standardController="Opportunity" extensions="VFC009_CreateContract" lightningStyleSheets="true" docType="html-5.0" >
    <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <head>
          <apex:slds />
        </head>
        <body>

        </body> 
    </html>
</apex:page>
 
public class VFC009_CreateContract {

    public VFC009_CreateContract(ApexPages.StandardController stdController){
        currentOpp = (Opportunity)stdController.getRecord();
        initPage();
    }

}

If the Created date of opportunity in less than jan 2015, i want to display a message to user to say that "opp is too old cant convert" else the apex code is executed normally.

How can i implement the code ?

Thank you for suggestion !
  • October 16, 2019
  • Like
  • 0
Hi there,

I am working on a custom APEX trigger that validates whether users have attached a file to a record in a custom object. 

Custom Object: Advice

Context: users must upload a file to their Advice records in order to recieve credit for the record - this is a requirement for reporting. I have created a custom checkbox field called, "Has Attachment" (API: HasAttachment__c) on the Advice object and implemented a trigger that sets HasAttachment__c = true when a file is uploaded. However, I am now trying to add on to the trigger so that it sets HasAttachment__c = false if the file is subsequently deleted. That is, if the record becomes empty again (no file) after there previously was a file uploaded, then the checkbox would be = false.

Here is my trigger code so far...it is on the Content Document Link object: 
 
trigger ContentDocumentLinkTrigger on ContentDocumentLink ( after insert, after update, after delete ) {

    List<ContentDocumentLink> cdls = ( Trigger.new == null ? Trigger.old : Trigger.new );

    Set<ID> parentIds = New Set<ID>();

    for ( ContentDocumentLink cdl : cdls ) {
        parentIds.add( cdl.LinkedEntityId );
}

    for ( List<Advice__c> adviceToUpdate: [ SELECT Id, ( SELECT Id FROM ContentDocumentLinks LIMIT 1 ) FROM Advice__c WHERE Id IN :parentIds ] ) {
        
        for ( Advice__c q : adviceToUpdate) {
            q.HasAttachment__c = true ;
        }

        update adviceToUpdate;

    }

}
If anyone could provide any help, suggestions or guidance, it would be GREATLY appreciated. Thanks in advance.
when I run the test class I was getting this error::System.JSONException: Unexpected character ('s' (code 115)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]

public  static String save(string data)
 InnerWrapper req =(InnerWrapper)JSON.deserialize(data,InnerWrapper.class);

Inner class
=======
public class InnerWrapper{
        List<String> ls;
        List<String> types;
        String parentId;
        Boolean ismpty;
        Boolean pSave;
        Map<String,Rule__c> type;
        String no;
    }
I am trying to add months to a date field and add that value to the List<Date>. I am getting null pointer exception

Apex Code
public class stndReduceExcel {
   public Contingency__c stndReduce{get;set;}
    public List<Date> bill{get;set;}
    ApexPages.StandardController controller;

    
    public stndReduceExcel(ApexPages.StandardController con){
        controller = con;
        stndReduce = [Select name, Account__c, BILLING_BEGINS_DATE__c,  Num_to_Bill__c   from Contingency__c where id = :System.currentPagereference().getParameters().get('id')];
        
          Date newbill =  stndReduce.BILLING_BEGINS_DATE__c;
        
        for(Integer i = 1; i <= stndReduce.Num_to_Bill__c ; i++){
            newBill = newBill.addMonths(i);
            system.debug(newBill);
            bill.add(newBill);
        }
    }
}

I am getting Null Pointer exceptbill.add(newBill). I used system debug statement shows the correct value.

Cant understand how to fix this. 
Any help would be aapreciated!
Hi team, 

When I code something and deploy to a sandbox, something it fails if I made a mistake or something doesn't work with the configuration of the sandbox.   When it fails, it used to give a details reason such as:
row 3 col 5 illegal assignment of String in Number field 

However, for some reason it stopped giving reasons but just the outcome
Now it just says DeployFailed: Deploy Failed

I am not sure if something change in CLI or I made a wrong setting. 
Can anyone please help?

Thanks!!

Hello All,

I have a simple trigger, PreventCCDeletion that should only allow Users with Profile='System Administrator-2012' or with Permission Set='Super User'  to delete Case Comments. The trigger works well...unfortunately I cannot reach the proper Code Coverage and cannot get over 66%.

Thanks in advance for your help.

Kned regards,

Robert

User-added image

Here is my trigger:

trigger PreventCCDeletion on CaseComment (before delete) {

Boolean YouCanDelete;
YouCanDelete=FALSE; 

    for(CaseComment cc : trigger.old)
    {
       
    // Check for 'System Administrator-2012' Profile
    
      List<Profile> PROFILE = [SELECT Id, Name FROM Profile WHERE Id=:userinfo.getProfileId() LIMIT 1];
      String MyProfileName = PROFILE[0].Name;
      If (MyProfileName=='System Administrator-2012'){ 
        YouCanDelete=TRUE;
      }
    
   
     // Check for 'Super User' ( 0PS0y000000D0dvGAC ) Permission Set
     
     If (YouCanDelete=FALSE){
        List<PermissionSetAssignment> SUPERUSER = [SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId= :UserInfo.getUserId() AND PermissionSet.Name = 'Super_User' LIMIT 1];
        String MyPermissionName = SUPERUSER[0].PermissionSet.Name;
          If (MyPermissionName=='Super_User'){   
          YouCanDelete=TRUE;
        }
      }
  
      If (YouCanDelete=FALSE) 
      { 
        cc.adderror('Case Comments cannot be deleted');
      }
    } 
}
 

Here is my test class:

@isTest
public class PreventCCDeletion_Test{
    
    static Case tCase;
    static CaseComment tComment;
    static Profile tProfile;
    static User tUser;
    
// Start of Test 1    
    static void createTestData1(){
        tCase = new Case();
        tCase.Status = 'Open';
        tCase.Description = 'Test Description-1 ';
        tCase.Origin = 'Annuity External';
        tCase.Type = 'Feature Request';
        tCase.Priority = 'Low';
        INSERT tCase;
        
        tComment = new CaseComment();
        tComment.ParentId = tCase.Id;
        tComment.CommentBody = 'Some Comment-1';
        tComment.IsPublished = TRUE;
        INSERT tComment;
        
        tProfile = 
            [
                SELECT Id 
                FROM   Profile 
                WHERE  Name = 'System Administrator-2012'
            ];
            
        tUser = new User(
            Alias = 'standt', 
            Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', 
            LastName='Testing', 
            LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', 
            ProfileId = tProfile.Id, 
            TimeZoneSidKey='America/Los_Angeles', 
            UserName='testuser@sometestorg.com',
            Non_Use_Send_Deactivation_Alert__c=FALSE,
            DefaultCurrencyIsoCode='USD',
            CurrencyIsoCode='USD',
            ReceivesAdminInfoEmails=FALSE,
            ByPass_New_Hire_Welcome__c=TRUE
        );
        INSERT tUser; 
                             
    }
    
    testMethod
    static void execCaseCommentDelete1(){
    test.startTest();
     
    createTestData1();
    
       try{
           System.runAs(tUser)
            {
             DELETE tComment;
            }
          }
       catch(Exception e){ }
       test.stopTest();
    }    
// End of Test 1


    
// Start of Test 2    
    static void createTestData2(){
        tCase = new Case();
        tCase.Status = 'Open';
        tCase.Description = 'Test Description-2 ';
        tCase.Origin = 'Annuity External';
        tCase.Type = 'Feature Request';
        tCase.Priority = 'Low';
        INSERT tCase;
        
        tComment = new CaseComment();
        tComment.ParentId = tCase.Id;
        tComment.CommentBody = 'Some Comment-2';
        tComment.IsPublished = TRUE;
        INSERT tComment;
        
        tProfile = 
            [
                SELECT Id 
                FROM   Profile 
                WHERE  Name = 'Prod IT Support User'
            ];
            
        tUser = new User(
            Alias = 'standt2', 
            Email='standarduser2@testorg.com', 
            EmailEncodingKey='UTF-8', 
            LastName='Testing', 
            LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', 
            ProfileId = tProfile.Id, 
            TimeZoneSidKey='America/Los_Angeles', 
            UserName='testuser2@sometestorg.com',
            Non_Use_Send_Deactivation_Alert__c=FALSE,
            DefaultCurrencyIsoCode='USD',
            CurrencyIsoCode='USD',
            ReceivesAdminInfoEmails=FALSE,
            ByPass_New_Hire_Welcome__c=TRUE
        );
        INSERT tUser; 
                             
    }
    
    testMethod
    static void execCaseCommentDelete2(){
    test.startTest();
     
    createTestData2();
            
    // Query your permission set name from Organization that your want to test.
       PermissionSet PS2 = [SELECT Id FROM PermissionSet WHERE Name = 'Super_User'];
       PermissionSetAssignment PSA2=new PermissionSetAssignment
       (AssigneeId = tUser.Id,PermissionSetId = PS2.Id); 
                       
       try{
           System.runAs(tUser)
            {
             insert PSA2; 
              System.debug('****testPS2....'+PS2);
              DELETE tComment;
            }
          }
       catch(Exception e){ }
       test.stopTest();
    }    
// End of Test 2
    
}
 

 

 

 

 

Hi everybody,

i have an issue and i need to update only one field records.

when i update one field records on custom object with data loader did the other fields get updated even if i didn't mapped them?

Thank you
  • June 18, 2019
  • Like
  • 0
Hi everyone,
my i am stuck in test class need my code coverage is not improving.
Can u please help to to achive. 
my apex code:
public class MindbodySubscriberService
{
    //when testing in dev you need to generate a new token via postman and put it in the devToken variable below. auth.mbodev.me is NOT available from salesforce!
    static final String devToken = null; //auth.mbodev.me is not available externally this should be generated via postman and put here for testing
    static final String authUser = 'SfEventClientUser'; //in dev/sanbox we have to fake the auth using the devToken above so these values are for production
    static final String authPass = 'dTr58@1GvUlob!';
    static String authToken = null;
    static datetime authExpiry = datetime.now().addMinutes(-10);
    
    @future(callout=true)
    public static void sendNotification(String oldEmail, String newEmail, String AccountNumber) 
    {
        System.debug('MBSubscriberService.sendNotification ' + AccountNumber);
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        string token = MindbodyAuthCallout();
        if (token == null)
        {
            System.debug('Failed to authenticate to Mindbody');
            return;
        }
        req.setHeader('Authorization','Bearer ' + token);
        req.setEndpoint(SubscriberUrl());
        req.setMethod('PUT');
        req.setHeader('Content-Type', 'application/json');
        
        EmailAccountObject upData = new EmailAccountObject();
        upData.OldEmail = oldEmail;
        upData.NewEmail = newEmail;
        upData.AccountNumber = AccountNumber;
        req.setBody(JSON.serialize(upData));
        System.debug(upData);
        try 
        {
            res = http.send(req);
            System.debug(res.getBody());
            System.debug(res.getStatus());
        } 
        catch(System.CalloutException e) 
        {
            System.debug('MB Callout error: '+ e);
            System.debug(res.toString());
        }
    }

public static string MindbodyAuthCallout ()
{
    if(Test.isRunningTest()){
         return null;   
    }
     if (isSandbox())
     {
        MindbodySubscriberService.authExpiry = datetime.now().addSeconds(7000); //just assume it's valid for dev environments 
        return MindbodySubscriberService.devToken;
     }
     if (MindbodySubscriberService.authToken != null && MindbodySubscriberService.authExpiry > datetime.now().addMinutes(-5))
     {
        return MindbodySubscriberService.authToken;
     }
     MBAuthObject auth = new MBAuthObject();
     auth.username = MindbodySubscriberService.authUser;
     auth.password = MindbodySubscriberService.authPass;
     auth.grant_type = 'password';
     auth.scope = 'urn:mboframeworkapi';
     HttpRequest req = new HttpRequest();
     req.setEndpoint('https://auth.mindbodyonline.com/issue/oauth2/token');
     req.setMethod('POST');
     req.setHeader('Authorization', 'Basic U2ZFdmVudENsaWVudDppaEF5bm9hR2xaZko4dzFieU9yU3pCZ3doUjR1cURLaTUvdE9LYlgyc1FBPQ==');
     req.setHeader('Content-Type', 'application/json');
     req.setBody(JSON.serialize(auth));
   
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HttpResponse res = http.send(req);

     JSONParser parser = JSON.createParser(res.getBody());
     while (parser.nextToken() != null) 
     {
        if (parser.getCurrentToken() == JSONToken.FIELD_NAME)
        {
            if (parser.getText() == 'access_token')
            {
                        parser.nextToken();
                        MindbodySubscriberService.authToken = parser.getText();
            }
            if (parser.getText() == 'expires_in')
            {
                        parser.nextToken();
                        MindbodySubscriberService.authExpiry = datetime.now().addSeconds(parser.getIntegerValue());
            }
        }
        if (MindbodySubscriberService.authExpiry > datetime.now())
        {
            return MindbodySubscriberService.authToken;
        }
     }
     System.debug ('Failed to get response token:' + res.getBody());
     return null;
}

public class MBAuthObject
{
    public String username;
    public String password;
    public String grant_type;
    public String scope;
}

public class EmailAccountObject
{
    public string AccountNumber;
    public string OldEmail;
    public string NewEmail;
}

  // Updates Subscriber Information in MINDBODY SAAS subscriber database as needed for the principal owner
  // Reach out to MB PT & E before modifying or disabling this trigger.  Primary use is STRIPE payout notifications
  // Author: A.J. Brann June 2018

  public static void UpdateMindbodySubscriberWhenPrincipalOwner(List<Contact> listContacts, Map<Id, Contact> oldMap, Boolean isInsert, Boolean isUpdate)
  {
      /*
    if(Test.isRunningTest())  //too many test failures in production, mocking the auth doesn't seem to help so we're just going to jump ship and not do anything from a test.
    {
           return;
    }
*/
    for(contact c: listContacts)
    {
        String contact_account;
        /*Update SAAS Platform for payout notifications to the principal owner upon change of email*/
        if(c.Role__c == 'Principal Owner' && isUpdate  && c.Email != oldMap.get(c.ID).Email)
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification(oldMap.get(c.ID).Email, c.Email, contact_account);
            }

        }
        if (c.Role__c != 'Principal Owner' && isUpdate && oldMap.get(c.ID).Role__c == 'Principal Owner') //role changed from principal owner
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification(oldMap.get(c.ID).Email, '', contact_account);
            }
        }
        if (c.Role__c == 'Principal Owner' && isInsert) //possible new owner
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification('', c.Email, contact_account);
            }
        }
    }
  }
  
 @testVisible
    private Static Boolean isSandbox(){
        String host = URL.getSalesforceBaseUrl().getHost();
        String server = host.substring(0,host.indexOf('.'));
 
        // It's easiest to check for 'my domain' sandboxes first 
        // even though that will be rare
        if(server.contains('--'))
            return true;
 
        // tapp0 is a unique "non-cs" server so we check it now
        if(server == 'tapp0')
            return true;
 
        // If server is 'cs' followed by a number it's a sandbox
        if(server.length()>2){
            if(server.substring(0,2)=='cs'){
                try{
                    Integer.valueOf(server.substring(2,server.length()));
                }
                catch(exception e){
                    //started with cs, but not followed by a number
                    return false;
                }
 
                //cs followed by a number, that's a hit
                return true;
            }
        }
        // If we made it here it's a production box
        return false;
    }
@TestVisible
    private Static String SubscriberUrl ()
    {
        String devSubscriber = 'https://subscriber.mbodev.me/Subscriber/Settings';
        String prodSubscriber = 'https://subscriber.mindbodyonline.com/Subscriber/Settings';
        if (isSandbox())
        {
            return devSubscriber;
        } 
        return prodSubscriber;
    }
 }

================================
my test class
=================================
public class MindbodySubscriberService
{
    //when testing in dev you need to generate a new token via postman and put it in the devToken variable below. auth.mbodev.me is NOT available from salesforce!
    static final String devToken = null; //auth.mbodev.me is not available externally this should be generated via postman and put here for testing
    static final String authUser = 'SfEventClientUser'; //in dev/sanbox we have to fake the auth using the devToken above so these values are for production
    static final String authPass = 'dTr58@1GvUlob!';
    static String authToken = null;
    static datetime authExpiry = datetime.now().addMinutes(-10);
    
    @future(callout=true)
    public static void sendNotification(String oldEmail, String newEmail, String AccountNumber) 
    {
        System.debug('MBSubscriberService.sendNotification ' + AccountNumber);
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        string token = MindbodyAuthCallout();
        if (token == null)
        {
            System.debug('Failed to authenticate to Mindbody');
            return;
        }
        req.setHeader('Authorization','Bearer ' + token);
        req.setEndpoint(SubscriberUrl());
        req.setMethod('PUT');
        req.setHeader('Content-Type', 'application/json');
        
        EmailAccountObject upData = new EmailAccountObject();
        upData.OldEmail = oldEmail;
        upData.NewEmail = newEmail;
        upData.AccountNumber = AccountNumber;
        req.setBody(JSON.serialize(upData));
        System.debug(upData);
        try 
        {
            res = http.send(req);
            System.debug(res.getBody());
            System.debug(res.getStatus());
        } 
        catch(System.CalloutException e) 
        {
            System.debug('MB Callout error: '+ e);
            System.debug(res.toString());
        }
    }

public static string MindbodyAuthCallout ()
{
    if(Test.isRunningTest()){
         return null;   
    }
     if (isSandbox())
     {
        MindbodySubscriberService.authExpiry = datetime.now().addSeconds(7000); //just assume it's valid for dev environments 
        return MindbodySubscriberService.devToken;
     }
     if (MindbodySubscriberService.authToken != null && MindbodySubscriberService.authExpiry > datetime.now().addMinutes(-5))
     {
        return MindbodySubscriberService.authToken;
     }
     MBAuthObject auth = new MBAuthObject();
     auth.username = MindbodySubscriberService.authUser;
     auth.password = MindbodySubscriberService.authPass;
     auth.grant_type = 'password';
     auth.scope = 'urn:mboframeworkapi';
     HttpRequest req = new HttpRequest();
     req.setEndpoint('https://auth.mindbodyonline.com/issue/oauth2/token');
     req.setMethod('POST');
     req.setHeader('Authorization', 'Basic U2ZFdmVudENsaWVudDppaEF5bm9hR2xaZko4dzFieU9yU3pCZ3doUjR1cURLaTUvdE9LYlgyc1FBPQ==');
     req.setHeader('Content-Type', 'application/json');
     req.setBody(JSON.serialize(auth));
   
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  
  
     Http http = new Http();
     HttpResponse res = http.send(req);

     JSONParser parser = JSON.createParser(res.getBody());
     while (parser.nextToken() != null) 
     {
        if (parser.getCurrentToken() == JSONToken.FIELD_NAME)
        {
            if (parser.getText() == 'access_token')
            {
                        parser.nextToken();
                        MindbodySubscriberService.authToken = parser.getText();
            }
            if (parser.getText() == 'expires_in')
            {
                        parser.nextToken();
                        MindbodySubscriberService.authExpiry = datetime.now().addSeconds(parser.getIntegerValue());
            }
        }
        if (MindbodySubscriberService.authExpiry > datetime.now())
        {
            return MindbodySubscriberService.authToken;
        }
     }
     System.debug ('Failed to get response token:' + res.getBody());
     return null;
}

public class MBAuthObject
{
    public String username;
    public String password;
    public String grant_type;
    public String scope;
}

public class EmailAccountObject
{
    public string AccountNumber;
    public string OldEmail;
    public string NewEmail;
}

  // Updates Subscriber Information in MINDBODY SAAS subscriber database as needed for the principal owner
  // Reach out to MB PT & E before modifying or disabling this trigger.  Primary use is STRIPE payout notifications
  // Author: A.J. Brann June 2018

  public static void UpdateMindbodySubscriberWhenPrincipalOwner(List<Contact> listContacts, Map<Id, Contact> oldMap, Boolean isInsert, Boolean isUpdate)
  {
      /*
    if(Test.isRunningTest())  //too many test failures in production, mocking the auth doesn't seem to help so we're just going to jump ship and not do anything from a test.
    {
           return;
    }
*/
    for(contact c: listContacts)
    {
        String contact_account;
        /*Update SAAS Platform for payout notifications to the principal owner upon change of email*/
        if(c.Role__c == 'Principal Owner' && isUpdate  && c.Email != oldMap.get(c.ID).Email)
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification(oldMap.get(c.ID).Email, c.Email, contact_account);
            }

        }
        if (c.Role__c != 'Principal Owner' && isUpdate && oldMap.get(c.ID).Role__c == 'Principal Owner') //role changed from principal owner
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification(oldMap.get(c.ID).Email, '', contact_account);
            }
        }
        if (c.Role__c == 'Principal Owner' && isInsert) //possible new owner
        {
            //retrieve the account for this contact
            List<Account> contact_accounts = [select MINDBODY_ID__c from Account where Id =: c.AccountId];
            if(!contact_accounts.isEmpty())
            {
                contact_account = contact_accounts[0].MINDBODY_ID__c;
                //post it to MINDBODY SAAS platform subscriber webhook
                sendNotification('', c.Email, contact_account);
            }
        }
    }
  }
  
 @testVisible
    private Static Boolean isSandbox(){
        String host = URL.getSalesforceBaseUrl().getHost();
        String server = host.substring(0,host.indexOf('.'));
 
        // It's easiest to check for 'my domain' sandboxes first 
        // even though that will be rare
        if(server.contains('--'))
            return true;
 
        // tapp0 is a unique "non-cs" server so we check it now
        if(server == 'tapp0')
            return true;
 
        // If server is 'cs' followed by a number it's a sandbox
        if(server.length()>2){
            if(server.substring(0,2)=='cs'){
                try{
                    Integer.valueOf(server.substring(2,server.length()));
                }
                catch(exception e){
                    //started with cs, but not followed by a number
                    return false;
                }
 
                //cs followed by a number, that's a hit
                return true;
            }
        }
        // If we made it here it's a production box
        return false;
    }
@TestVisible
    private Static String SubscriberUrl ()
    {
        String devSubscriber = 'https://subscriber.mbodev.me/Subscriber/Settings';
        String prodSubscriber = 'https://subscriber.mindbodyonline.com/Subscriber/Settings';
        if (isSandbox())
        {
            return devSubscriber;
        } 
        return prodSubscriber;
    }
 }

Hello to all, $

Usually, I use HaoIDE with Sublime Text.

With HaoIDE, I have the possibility to recover elements of my organization to modify them in local: class apex, component lightning, ...

I understand that Salesforce DX pushes us to go through a repository.

But I would like to know if a feature that allows me to recover existing code directly on an organization exists please.

Thank you in advance !
I have written an invocable apex class for process builder to update th owner change of accounts and related Opportunity, contracts and quotes on custom object and its working fine. Now i need to bulkify the code. what are the changes required in below code ?
below code :
public class RequestPortalRecords
{
    @InvocableMethod
    public static void ReqChange(List<Request_Portal__c> rp)
    {
        system.debug('entered raghav' +rp);
        Set<Id> accountIds=new Set<Id>();
        Id ownerid;
        list<Account> updateAccOwnerList = new list<Account>();
        list<Opportunity> updateoppList = new list<Opportunity>();
        list<SBQQ__Quote__c> updateqsList = new list<SBQQ__Quote__c>();
        list<contract> updatecrList=new list<contract>();
        
        
        for(Request_Portal__c r : rp)
        {
            accountIds.add(r.Account_Name__c);
            ownerid=r.New_Owner__c;
            system.debug('accountIds'+accountIds+' ownerid'+ ownerid);
            
        }
        
        //updaTE ACCOUNT
        List<Account> accList=[Select id,ownerid from account where id=:accountIds];
        system.debug('accList'+accList.size());
        
        for(Account acc:accList){
            acc.ownerid=ownerid;
            updateAccOwnerList.add(acc);
        }
        
        system.debug('updateAccOwnerList'+updateAccOwnerList.size());
        if(updateAccOwnerList.size()>0){
            update updateAccOwnerList;
        }
        
        //update opportunities
        List<Opportunity> oppList=[Select id,Ownerid,AccountId from Opportunity Where AccountId = :accountIds ];
        system.debug('opplist'+oppList.size());
        
        
        
        for(Opportunity op: opplist){
            op.ownerid=ownerid;
            updateoppList.add(op);
            
        }
        
        system.debug('updateoppList'+updateoppList);  
        
        if(!updateoppList.isEmpty())
            update updateoppList;  
    
    //update Quote
    List<SBQQ__Quote__c> qsList=[Select id,Ownerid from SBQQ__Quote__c where SBQQ__Account__c = :accountIds];
     for(SBQQ__Quote__c qs: qsList){
            qs.ownerid=ownerid;
           updateqsList.add(qs);
            
      }
        system.debug('updateqsList'+updateqsList);  
        
        if(!updateqsList.isEmpty())
            update updateqsList; 
        
        //contract
        List<Contract> crList=[Select id,Ownerid from Contract where AccountId = :accountIds];
     for(Contract qs: crList){
            qs.ownerid=ownerid;
           updatecrList.add(qs);
            
      }
        system.debug('updatecrList'+updatecrList);  
        
        if(!updatecrList.isEmpty())
            update updatecrList;  
    }    
}
Hello,

I have created a trigger which is supposed to create multiple records.
 
trigger CreateMultipleContacts on Contract  (after insert,  after update) {
    
    List<Contract_Renewal__c> contractFinalListToInsert = New List<Contract_Renewal__c>();
    
    if(Trigger.isInsert || Trigger.isUpdate){
        for(Contract  c : Trigger.New) {
            if(c.Renew__c == true) {
                Integer fetchingAlreadyExistedRecords = [SELECT count() FROM Contract_Renewal__c WHERE Contract__c=:c.Id and Not_Renewed__c=:false and Multi_Year__c=:true];
                
                if(fetchingAlreadyExistedRecords!=null) {
                    // We are only creating a records when there at least one Contract record exists.
                    for(Integer i=0; i<fetchingAlreadyExistedRecords; i++) {
                        Contract_Renewal__c con = new Contract_Renewal__c();
                        con.Contract__c = c.Id;
                        contractFinalListToInsert.add(con);
                        
                    }
                }
            }
            
            try{
                if(!contractFinalListToInsert.IsEmpty()){
                    INSERT contractFinalListToInsert;
                }
            }
            catch(Exception e){
                System.debug('The thrown exception for CreatingAutoRecords is:: ' + e.getMessage());
            }
        }
    }
}
I have the Contracts object and the Contract Renewals which is related to Contracts(Contracts master object)
When i check the box renew in contracts, records of contract renewal which are its children are created. However, when i do that no records are created. I check the contract renewals object just in case records arecreated without being assigned to the contracts. any ideas of what might be missing here?

when i
Hi All,
I have written a Trigger to update the lead status from Engagement to Negotiation when a file is uploaded on Lead when the status is Engagement. I want to restrict the trigger to fire when the file is uploaded on Engagement status and update the status to negotiation thats it. The trigger should not fire if the lead is on another status and if a user upload the file. Could you please help me how to achieve this in the below code.
trigger FileUploadonLead on ContentVersion (after insert) {
map <id,string> lmap = new map <id,string>();
    list<lead> leadlist = new list <lead>();
    for(contentversion cv : trigger.new){
        id x = cv.FirstPublishLocationId;
        if(string.valueof(x.getsobjecttype()) == 'lead'){
            system.debug('inside test');
            lmap.put(cv.FirstPublishLocationId,'Negotiation');
            
            
        }
        
        
    }
    
    for(lead l : [select id,status from lead where id in : lmap.keySet()]){
    system.debug('lmap.get() '+ lmap.get(l.id) );
        l.status = lmap.get(l.id);
        leadlist.add(l);
        
    }
    
    if(leadlist.size()>0){
        system.debug('leadlist ' + leadlist );
        update leadlist;
    }
}

 
Hi Everyone how to reduce line of codes 
this logic i used many times in trigger and my code length is line 400 lines so how to reduce them only the UserRole.Name is changed according to hierarchy because my hierarchy is so long its for 6-7 states so i used this logic for all states only role name is changed in the query this below code part is only little






trigger Distributor on Account (before insert,before update) {
    
String role;
String owner;
    
  list<Account> changeOwner=new list<Account>();
    
    for(Account acc:trigger.new){
        
       if(acc.Under__c=='Chhattisgarh'){
           role='SO CG';
           changeOwner.add(acc);
       }
   list <User> socg1=[select id,Name from User where UserRole.Name='SO CG' Order BY FirstName,LastName];
   list <User> socg2=[select id,Name from User where UserRole.Name='ASM CG' Order BY FirstName,LastName];
   list <User> socg3=[select id,Name from User where UserRole.Name='DRM CG' Order BY FirstName,LastName];
   list <User> socg4=[select id,Name from User where UserRole.Name='RM CG' Order BY FirstName,LastName];
  
   if(socg1.size()>0){
        owner=socg1.get(0).id;
    }
    
     else if(socg1.size()<=0){
     
        if(socg2.size()>0){
            owner=socg2.get(0).id; 
        }
        
        else if(socg2.size()<=0){
            
            if(socg3.size()>0){
              owner=socg2.get(0).id;  
             }
        
        else if(socg3.size()<=0){
            
             if(socg4.size()>0) {
               owner=socg4.get(0).id;   
             }   
        }
      }
   }
   for(Account acc:changeOwner){
       
        if(socg1!=null){
            acc.OwnerId=Owner;
        }
    }
    
I am extracting the obj data from salesforce through  data loader  CLI and i am getting the below error:
java.lang.RuntimeException: com.salesforce.dataloader.mapping.Mapper$InvalidMappingException: No such field loan_application on entity Invoice_Details__c
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:169)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:107)
        at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:266)
Caused by: com.salesforce.dataloader.mapping.Mapper$InvalidMappingException: No such field loan_application on entity Invoice_Details__c
        at com.salesforce.dataloader.mapping.SOQLMapper.getSfdcField(SOQLMapper.java:239)
        at com.salesforce.dataloader.mapping.SOQLMapper.evalSfdcField(SOQLMapper.java:230)
        at com.salesforce.dataloader.mapping.SOQLMapper.evalSfdcField(SOQLMapper.java:206)
        at com.salesforce.dataloader.mapping.SOQLMapper.normalizeSoql(SOQLMapper.java:190)
        at com.salesforce.dataloader.mapping.SOQLMapper.addSoqlFieldMapping(SOQLMapper.java:186)
        at com.salesforce.dataloader.mapping.SOQLMapper.putPropertyEntry(SOQLMapper.java:119)
        at com.salesforce.dataloader.mapping.Mapper.putPropertyFileMappings(Mapper.java:147)
        at com.salesforce.dataloader.mapping.Mapper.putPropertyFileMappings(Mapper.java:142)
        at com.salesforce.dataloader.mapping.Mapper.<init>(Mapper.java:89)
        at com.salesforce.dataloader.mapping.SOQLMapper.<init>(SOQLMapper.java:70)
        at com.salesforce.dataloader.controller.Controller.createMapper(Controller.java:246)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:153)
        ... 2 more
How do i pass the value of list from a static void method to another method.
 
public static void abcd(List<Id> activityIds, String message, Datetime scheduleDateTime){
            
        }





public static void createSalesforceActivities(List<Id> recordIdSet ,String message, Datetime scheduleDateTime, String status){
            List<Task> lstTask = new List<Task>();
            
            for(String id: recordIdSet){
                Task taskObj = new Task();
                taskObj.ActivityDate = Date.valueOf(scheduleDateTime);
                taskObj.Status = status;
                taskObj.Description = message;
                taskObj.WhoId = id;
                
                lstTask.add(taskObj); 
            }
            insert lstTask;
        }

So basically i want to pass the list of inserted task record values to static void abcd method. 
what is the best possible way?
  • April 22, 2019
  • Like
  • 0
When a new person account is created, check if there are existing unconverted leads with the same email address.
If any lead is found, convert lead using the same account which is creating it. If there are multiple leads found, first merge to latest modified lead. (Merge can only happen for max 3 leads as per Salesforce Limit. If we have more duplicates lead, we might have to consider using batch). 
If no leads found, do nothing.

code
public class AccountTriggerHandler {
    public static void existingunconvertedleads (List<Account> lstInsertedAccount){
        map<string,Account> mapOfAccount = new map<string,Account>();
        
        // Check to see if Email already exists
        for (Account a : lstInsertedAccount) {
            if(a.IsPersonAccount){
                if(String.isnotBlank(a.PersonEmail)){
                    mapOfAccount.put(a.PersonEmail,a);
                }
            }
        }
        Map<string,List<Lead>> mapOfLeadWithEmail = new Map<string,List<Lead>>();
        for(lead objld :[select id,email from lead where IsConverted = false And Email in: mapOfAccount.keySet()]){
            if(mapOfLeadWithEmail.containsKey(objld.Email)){
                List<lead> ldlist =  mapOfLeadWithEmail.get(objld.Email);
                ldlist.add(objld);
                mapOfLeadWithEmail.put(objld.Email,ldlist);
            } else{
                mapOfLeadWithEmail.put(objld.Email, new list<lead>{objld});   
            }
            
        }
        
        
        for(string strEmail: mapofLeadWithEmail.keyset()){
            if(mapofLeadWithEmail.get(strEmail).size() > 1){
              list<lead> ls = [select id from lead where id =:mapOfLeadWithEmail.keyset()];
                
                
                LeadStatus CLeadStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true];
                List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
                for(id currentlead: mapOfAccount.keyset()){
                    Database.LeadConvert Leadconvert = new Database.LeadConvert();
                    Leadconvert.setLeadId(currentlead);                
                    Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                    MassLeadconvert.add(Leadconvert);
                    if (!MassLeadconvert.isEmpty()) {
                        List<Database.LeadConvertResult > lcr = Database.convertLead(MassLeadconvert);
                    }
                } 
            }
               
            
            system.debug('strEmail ::: '+strEmail);
            system.debug('Lead size ::: '+mapofLeadWithEmail.get(strEmail).size());
        }
    }
}
Hello everyone,

I am working on my first trigger and I was able to get the trigger to create a Case from a change in the account object but the only problem is, it is only supposed to create a Case if there isn't already a Case in the status of 'New' or 'On Service' in the Account

When i go to a test account, the trigger fires even when there is a Case that is New. I was wondering if anyone could look at my code and help me find out why this is happening
 
trigger caseCheck on Account (After update) {
        //Get all account and cases.
  

  List<Account> allAccounts = new List<Account>([Select id,Fuzion_Status__c,(select id from cases where status in('New','On Service')) from account where id in :Trigger.new]);
   List<Case> newCases = new List<Case>();
    
    for(Account myAccount :allAccounts){
    Account oldAccount = trigger.oldMap.get(myAccount.id);
    if(oldAccount.Fuzion_Status__c == 'Initial Phone call' && myAccount.Fuzion_Status__c != 'Initial Phone call'){
        if(myAccount.cases !=null){
            Case c = new Case();
            c.Accountid = myAccount.Id;
            c.Type = 'ICM';
            c.Origin = 'SHIP';
            c.Division__c = 'Case Management';
            c.Status = 'New';
            c.RecordTypeId = '01236000000OJLq';
            newCases.add(c); 
        }
     }
        
    }
    if(!NewCases.isEmpty()){
        insert newCases;
    }
 
}

 
Hello,
I am writing a test for an @InvocableMethod and for some reason I keep getting an error that says Invalid Type: SendPdf. Code below, any help is appreciated!!
Controller
public with sharing class EchoSign {
    private ApexPages.StandardController standardController;
    public EchoSign(ApexPages.StandardController standardController){
        this.standardController = standardController;}

@InvocableMethod
    public static void SendPdf(List<ID> conid){
        
    List<Contact> con = [SELECT Id, AccountId, Name FROM Contact WHERE Id =: conid LIMIT 1];  
        
        pageReference pdfPage = Page.ContactPDF;
        pdfPage.getParameters().put('Id',con[0].Id);
        blob pdfBody;
        pdfBody = pdfPage.getContentAsPDF();

//creation of Adobe Sign Agreement and Attachment here
}
}
Test
@isTest
public class Test_EchoSign2 {
    static testMethod void testechosign(){
    	Account ac = new Account(RecordTypeId = [SELECT Id, SobjectType, Name FROM Recordtype WHERE Name = 'Prospect/Client' AND SobjectType = 'Account' LIMIT 1].Id);
    	ac.Name = 'TestAcnt';
    	ac.Type = 'Prospect';
    	insert ac;
    
		Contact con = new Contact(RecordTypeId = [SELECT Id,SObjectType,Name FROM RecordType WHERE Name = 'Prospect/Client' AND SobjectType = 'Contact' LIMIT 1].Id);
		con.LastName = 'testLastName';
    	con.AccountId = ac.Id;
	    con.LeadSource = 'Unknown';
        insert con;
        
        Test.startTest();
        
        PageReference ContactPDF = Page.ContactPDF;
        ContactPDF.getParameters().put('Id',con.Id);
        Test.setCurrentPage(ContactPDF);
        
        SendPdf pdf = new SendPdf();
    }
}


 
I need to reference a put a Select Query into a String, but it won't process system data like getUserId() (or system.now, although I'm not sure because the error message centers on getUserId()).

Here's what I have:
 
String UserID = UserInfo.getUserId();

String myRequest = 'SELECT id, Owner.Id, type, subject,'+
                ' FROM Event' + 
                ' WHERE Owner.Id = '+UserId+' AND RecordTypeId = \'0126A0000004Qle\' And (ActivityDateTime = LAST_N_DAYS:30 OR (ActivityDate = TODAY And ActivityDateTime < ' + system.now() + ' ))';
Error message is "System.QueryExecption: unexpected token:" and then my UserId.
 
I'm creating a VF page for employees to create a record for a custom object. I'm having issues writing the redirect Apex code so that after they hit "Submit", the employees will be redirected to another VF page (that I've created called "SuccessPage") that says "Your profile has been submitted successfully". After five seconds the SuccessPage it automatically redirect to the company's website. But if the employee hits Cancel, it will close the VF page.

Record Code
<apex:page standardController="Object__c"> 
<apex:form >

<div class="header">
    <center><img src="{!$Resource.companylogo}" width="10%"/></center>
  </div> 
 
        <style>
            body .bPageBlock .pbBody .blue .pbSubheader{
                background-color:#154f82;
            
            }
            body .bPageBlock .pbBody .white .pbSubheader h3{
                color:#ffffff;
            }
        </style>
        

<apex:outputPanel styleClass="blue" layout="block">
      <apex:pageBlockSection title="Skills" id="section7">
       <apex:inputField value="{!Employee_Profile__c.Skills__c}"/>        
</apex:pageBlockSection>
</apex:outputPanel>

</apex:pageBlock>

<center><apex:commandButton value="Submit" action="{!save}"/><apex:commandButton value="Cancel" action="{!cancel}"/></center> 


  </apex:form>
</apex:page>
Success VF page
<apex:page >
    <h1>Success</h1>

  
  <script type="text/javascript">
    window.setTimeout("redirectpage();", 5000);    
    function redirectpage(){
    window.top.location.href = 'http://www.website.com';
    }
</script>
</apex:page>




 
Based on this statement in the critical update it would appear that only Process Builder processes that contain an autolaunched flow are affected.  Is that true, or are all Process Builder processes, regardless of whether an action calls an autolaunched flow affected?
 
1. Identify all processes that include a flow action and all integrations that call an autolaunched flow through the Invocable Actions resource in the Salesforce REST API.


Source : https://releasenotes.docs.salesforce.com/en-us/spring18/release-notes/rn_forcecom_flow_invocable_cruc.htm


 
I am using lightning:recordEditForm and lightning:inputField to create a lightning form which I can create a record with.  I am able to view lightning:input values but not lightning:inputField values inside of my Apex controller.  The only way I have found to pass these values is to add them to the Item via the JavaScript before I make the callout to my controller's save method.
 
if (component.find("spaceRequiresCleaning").get("v.value") != undefined) {
  item.Space_Requires_Cleaning__c = component.find("spaceRequiresCleaning").get("v.value");
}
To re-iterate, lightning:input values (from a text field) come accross without having to do the above.  While the lightning:inputField (picklist) needs the above code.
 
<lightning:input aura:id="cubeOfficeLocation" value="{!v.item.Cube_Office_Location__c}" label="Cube/Office Location" name="cubeOfficeLocation" size="10" type="text">
</lightning:input>

<lightning:inputField fieldName="Space_Requires_Cleaning__c" aura:id="spaceRequiresCleaning" name="Space_Requires_Cleaning__c" value="{!v.item.Space_Requires_Cleaning__c}">
</lightning:inputField>
I don't want to have to add the extra JavaScript for all my lightning:inputField tags in order to pass them to the Apex controller.  Any ideas on how to accomplish this another way?

 
We are switching from Attachments to Files. In our community site we allow external users to create Cases. We also allow the users the ability to upload Attachments to their Cases. Switching to Files I am seeing that there is a "Share Settings" button that is appearing. I do not want that for our external users. the upload is being done from a custom VF page that we can edit.

User-added image
I am looking to use Visual Studio Code as a replacment for Sublime/MavensMate.  I would like to be able to edit code in a sandbox (not SalesforceDX scratch orgs) in a similar way that I do witth Sublime.  What I have found so far has mostly shown how to connect  to scratch orgs using SalesforcDX which I do not want to use at this time.
We are about to switch from Attachments to Files.  When you click the "Attach File" button under Notes & Attachments you are brought to a page where you can upload multiple files (one by one).

 /p/attach/NoteAttach

User-added image

I was wondering if there was a version of this for uploading multiple Files.  Mostly asking as we are using the above page to allow users in our Community site to upload multiple files and if this goes away I need another way of doing this or we'll have to ask them to zip up their files first, or I'll have to create a new VF page to replicate the above functionality.
If Email Deliverability is not set to All Email in my sandbox my code will error out when trying to send an email.  How can I check if Email Deliverabitlity is set to All Email in Apex so that I don't receive the NO_MASS_MAIL_PERMISSION errors?
I use Subversion, Sublime and Tortoise SVN and Windows.  I have no plan on chaning to Git (just to get that out there).  

That being said, I am in the process of creating a version control structure for our environment.  Being fairly new to branching and merging I am looking for some feedback.

Here is the directory structure that I have planned.  

Salesforce
    trunk
    branches
            
From what I can tell I need to commit my production code to trunk (stored in src)

Salesforce
    trunk
        config
        src
    branches
        
Then, when I wish to work on a project, I need to create a branch into the branch directory (which makes a copy of everything from the trunk)

Salesforce
    trunk
        config
        src
    branches
        project1
            config
            src
            
I then work in the project1 directory on my local computer.
When I have a change that is completed I then commit it to the project1 branch.
When my code is ready for production I then have to perform a merge to the trunk.  This is where I am having issues.  From what I have seen I have to go to the local copy of the trunk and do a merge and specify the source as the location in the branch of my changed file.  I cannot get it to merge this brand new file into the trunk.  Any ideas of what I am doing wrong?
I have a need to get the User object for the user who logged into SFDC so that I can use it in my community. After using "log in to community as user" how can I use Apex to get the original Salesforce user?

On the Content object page I can see it dispalyed in Kb or other sizes, but when I display the contentsize field on a Visualforce page it shows the size in bytes.  I would like it to appear as Kb, Mb, or Gb.  A contractor had used some JavaScript to calcuate the size on another page, but I'd rather not use JavaScript as I'd like to try and stay server side instead of client side.  What are my options?  Do I use forumula on a second hidden field, is there some Visualforce tag I can use? 

I am getting an error when trying a file into Chatter via RestAPI.

[{"errorCode":"POST_BODY_PARSE_ERROR","message":"Binary data included but file attachment information is missing. If providing rich JSON/XML input in multipart REST, make sure to include Content-Type header in the part."}]

Here is a snippet of my code, what am I missing?
 
DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost;
        MultipartEntity reqEntity;
        httppost = new HttpPost(RES_URL);
        reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        File imageFile = new File(
                "/salesforce/wsdl/test.txt");
        FileBody bin = new FileBody(imageFile);
        reqEntity.addPart("feedItemFileUpload", bin);
        String fileName = "test.txt";
        // file name can be text plain only, though using text/html doesn't breaks
        reqEntity.addPart("fileName", new StringBody(fileName, "text/plain",
                Charset.defaultCharset()));

        httppost.setEntity(reqEntity);

        httppost.setHeader("Authorization",         "OAuth " + logon());

        String response = EntityUtils.toString(httpclient.execute(httppost)
                .getEntity(), "UTF-8");

        System.out.println(response);

 
I have an issue where when you click on "Click here to view HTML version" on an Inbound Email Message in a Case some of the text will not display correctly and gets cut off because Salesforce treats certain special characters as HTML.

Example
files (where 0 <= i <= 6) 
turns to 
files (where 0
 
I have a need to get the User object for the user who logged into SFDC so that I can use it in my community. After using "log in to community as user" how can I use Apex to get the original Salesforce user?
Hello,

I have a button like below on Opportunity object
User-added image
 
<apex:page standardController="Opportunity" extensions="VFC009_CreateContract" lightningStyleSheets="true" docType="html-5.0" >
    <html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <head>
          <apex:slds />
        </head>
        <body>

        </body> 
    </html>
</apex:page>
 
public class VFC009_CreateContract {

    public VFC009_CreateContract(ApexPages.StandardController stdController){
        currentOpp = (Opportunity)stdController.getRecord();
        initPage();
    }

}

If the Created date of opportunity in less than jan 2015, i want to display a message to user to say that "opp is too old cant convert" else the apex code is executed normally.

How can i implement the code ?

Thank you for suggestion !
  • October 16, 2019
  • Like
  • 0
Hi, 

How can we achieve the region details of the logged-in user by using apex?
Hi there,

I am working on a custom APEX trigger that validates whether users have attached a file to a record in a custom object. 

Custom Object: Advice

Context: users must upload a file to their Advice records in order to recieve credit for the record - this is a requirement for reporting. I have created a custom checkbox field called, "Has Attachment" (API: HasAttachment__c) on the Advice object and implemented a trigger that sets HasAttachment__c = true when a file is uploaded. However, I am now trying to add on to the trigger so that it sets HasAttachment__c = false if the file is subsequently deleted. That is, if the record becomes empty again (no file) after there previously was a file uploaded, then the checkbox would be = false.

Here is my trigger code so far...it is on the Content Document Link object: 
 
trigger ContentDocumentLinkTrigger on ContentDocumentLink ( after insert, after update, after delete ) {

    List<ContentDocumentLink> cdls = ( Trigger.new == null ? Trigger.old : Trigger.new );

    Set<ID> parentIds = New Set<ID>();

    for ( ContentDocumentLink cdl : cdls ) {
        parentIds.add( cdl.LinkedEntityId );
}

    for ( List<Advice__c> adviceToUpdate: [ SELECT Id, ( SELECT Id FROM ContentDocumentLinks LIMIT 1 ) FROM Advice__c WHERE Id IN :parentIds ] ) {
        
        for ( Advice__c q : adviceToUpdate) {
            q.HasAttachment__c = true ;
        }

        update adviceToUpdate;

    }

}
If anyone could provide any help, suggestions or guidance, it would be GREATLY appreciated. Thanks in advance.
Apex Method:
public void cartss(){
       Products__c Pro = [Select Id, Name, Brand__c,Deal_Price__c,Model__c,Image__c from Products__c where id =:accId];
     
            Cart__c cartOrder = New Cart__c();
            cartOrder.Name__c =  pro.Name;
            cartOrder.Model__c =  pro.Model__c;
            cartOrder.Brands__c =  pro.Brand__c;
            cartOrder.Image__c =  pro.Image__c;
            cartOrder.Price__c =  pro.Deal_Price__c;
        Insert cartOrder;
        pagereference redirect = new PageReference('/apex/ezshopindex');
    }


Here is my Test class:


 private static testMethod void cartssTest() {
        Category__c cat = new Category__c();
        cat.Name='ss';
        insert cat;
        Sub_Category__c sub = new Sub_Category__c();
        sub.Name='sfdc';
        sub.Category__c=cat.Id;
        insert sub;
        Brands__c br = new Brands__c();
        br.Name='hell';
        br.Sub_Category__c=sub.Id;
        Products__c  testpr = new Products__c();
        testpr.name='testpr';
        testpr.Category__c=cat.Id;
        testpr.Sub_Category__c=sub.Id;
        testpr.Model__c='sfs';
        testpr.Deal_Price__c=8597;
        testpr.Image__c='heloo123';
        testpr.Brand__c=br.Id;
        insert testpr;        
      
        test.startTest();
        PageReference pageRef = Page.ezshopindex;
        SearchInVFController  cart = new SearchInVFController();
        cart.cartss();
        test.stopTest();
    }



Brands__c is lookup for products__c controlling field is Sub_Category__c, 
and Sub_category__c is lookup for products__c and controlling field is Category__c.
Category__c is lookup for Products__c
Hello,

I am new to APEX so thanks in advance for helping a newbie out.

I need an APEX to run at midnight (I will use the SF scheduler) to update a custom field (whatever__c) with a number (42). My end goal is to have this field update (whatever__c = 42) will kickoff a process I created in process builder. 

Thanks again everyone 
I have a batch class that updated a custom object when a trigger runs. 

Sceniro: Someone adds a state to a multi select picklist. The trigger will grab all states, and throw the last state in the variable. I then grab the id of the record in another variable. I pass both of those variables over to a batch class and run a query on another custome object, and update the fields. 

Problem is, when I get to the update part, the first field (Flow_Kick_Off__c) gets the value of the variable, but the other field (Territory__c) does not..... I don't understand why one field is getting updated, but not the other. 

Here is the trigger:
trigger updateFacility on Territory__c (before insert, before update) {
    
    //Adding a state index is -1. Removing a state index is normal.
    
    String[] oldStates;
    String[] newStates;
    Integer countStates;
    Integer countOldStates;
    Integer countNewStates;
    String terrID;
    String terrState;
    
    if(Trigger.isUpdate) {
        for(Territory__c oldTerr : Trigger.old) {
            oldStates = oldTerr.states__c.split(';');
            countOldStates = oldStates.size();
            terrID = oldTerr.Id;
        }
        
    }
    
    else if(Trigger.isInsert) {
        
    }
    
    for(Territory__c newTerr : Trigger.new) {
        newStates = newTerr.states__c.split(';');
        countNewStates = newStates.size();
        
        if(countNewStates > countOldStates) {
            terrState = newStates[countNewStates-1];
            System.debug('TRIGGER ID = ' + terrID);
            System.debug('TRIGGER STATE = ' + terrState);
            FacilityUpdates db = new FacilityUpdates(terrState, terrID);
            database.executeBatch(db, 75);
        }
        
        else {
            
        }
        
    }
    
    
}

Here is the class: The only field that is not updating is (Territory__c)
global class FacilityUpdates implements Database.Batchable<sObject> {
    
    global String terrState;
    global String terrID;
    
    
    global FacilityUpdates(String myStates, String terID){
        terrState = myStates;
        terrID = terID;
        system.debug('STATE = ' + myStates);
        system.debug('ID = ' + terID);
    }
    
    public String query;
    
    global Database.querylocator start(Database.BatchableContext BC){
        
        //String newString = '\'';
        system.debug('INSIDE EXECUTE STATE = ' + terrState);
        
        query = 'Select id, Name, physical_State__c, Territory__c FROM Facility__c WHERE physical_State__c = :terrState';
        //query = 'Select id, Name, physical_State__c, Territory__c FROM Facility__c WHERE Territory__c = :terrId AND physical_State__c includes ' + states;
        
        
        system.debug(query);
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        List<Facility__c> accns = new List<Facility__c>();
        for(sObject s : scope)
        {
            Facility__c a = (Facility__c)s;
            a.Flow_Kickoff__c = terrID;
            a.Territory__c = terrID;
            accns.add(a);
        }
        update accns;
        
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }
    
}

 
Hi All,

I have a VF page with standard controller and extension.This page basically used by salesforce user to enter the values.This form has an email field.Upon saving record an email should trigger to external user on the email id specified during record creation.The email whcih an external user receives will have link to the sites which we have created.Now when user copy paste the site link in browser tab then a new VF page will appear will some fields auto populate.
Basically my VF page is up and running.My site is up and running.For Salesforce users and external users I am displaying the same VF page with some sections (used renedring) but I am not able to auto populate the fieldson site VF.
Lets say in my vf page where salesforce users are entering values(name,email,mobile).When they save record the email will go to the email id specified during record creation. When external user receive email which will have link for the external site and go to that external site I want name and email field will be auto puplate this time and external user can only enter their mobile no 
Below is snippet from my VF page():
<apex:page standardController="Driver_Survey__c" extensions="SurveyForDriverController" sidebar="false" lightningStylesheets="true" showHeader="{! $Profile.Name == 'System Administrator' }" >
    
    
    <apex:form > 
       <!--Below section will be sued by the Salesforce user to enther details and save record-->
            <apex:pageBlockSection columns="1" collapsible="false" title="Driver Information"  rendered="{!IF($Profile.Name =='Profile1'|| $Profile.Name =='Profile2' , true, False)}"   >
                <apex:inputField label="Name" value="{!survey.Name__c}" required="true"/>
                <apex:inputField label="Mobile" value="{!survey.Mobile__c}" required="true" />
                <apex:inputField label="Email" value="{!survey.Email__c}" required="true" />
                
				
  
            </apex:pageBlockSection>
        <!--Below section will be visible on Sites for external user-->

             <apex:pageBlockSection columns="1" collapsible="false" title="Driver Information"  rendered="{!IF($Profile.Name=='Transport Questionnaire Profile',true,false)}"  >
                <apex:inputField label="Name1" value="{!survey.Name__c}"/>
                <apex:outputField label="Mobile1" value="{!survey.Mobile__c}"/>
                <apex:outputField label="Email1" value="{!survey.Email__c}"/>
                
					
  
            </apex:pageBlockSection>
         
            <apex:pageBlockButtons >
             
              
                <apex:commandButton value="Save" action="{!doFullSave}"  />
                    
                    <apex:commandButton value="Cancel" action="{!doCancel}" immediate="true"/>
       
            </apex:pageBlockButtons> 
        </apex:pageBlock>
      
    </apex:form>
</apex:page>
Below is my controller(pasting only required snippet):
public class SurveyForDriverController{
    
    //class variables
    public Driver_Survey__c survey{get;set;}
    Public String name{get;set;}
    Public String ordid;


    public GrabSurveyForDriverController(ApexPages.StandardController controller){
         survey=new Grab_Driver_Survey__c();
        survey=(Grab_Driver_Survey__c)controller.getRecord();
          system.debug('message3>>'+survey );
          Id profileId=userinfo.getProfileId();
            String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
            system.debug('ProfileName'+profileName);
        if(profileName=='Grab Transport Questionnaire Profile'){
            survey.Name__c=ApexPages.currentPage().getParameters().get('ordid');
        }
       
    }
   
  
    
    
    public PageReference doFullSave(){
        system.debug('message1>>'+survey );
       	insert survey; 
   
        SendEmail();
        PageReference pageRef = new PageReference('/'+survey.Id);
        pageRef.setRedirect(true);
        return pageRef;  
        }
    
    public PageReference doCancel(){
        PageReference pageRef = new PageReference('/');
            pageRef.setRedirect(true);
            return pageRef;
    }
    public void SendEmail(){

      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.toAddresses = new String[] { survey.Email__c };
        mail.subject = 'Subject Test Message';
        String body = 'Hi \n  ';
       
        body += + survey.Name__c+ '<br><br>' ;
        body+= +'Request you to kindly fill in the questionnaire'+ '<br><br>';
       body+= +'https://"My siteURL"/myVFpagename;
       
        mail.setHtmlBody(body);
        Messaging.SingleEmailMessage[] mailss =   new List<Messaging.SingleEmailMessage> {mail};
        Messaging.SendEmailResult[] results = Messaging.sendEmail(mailss);
         	if (results[0].success) 
                {
                    System.debug('The email was sent successfully.');
                } else 
                {
                    System.debug('The email failed to send: ' + results[0].errors[0].message);
                }
    }          
}

I am not able to auto populate the name and email on the page which external user will see 

Any help would be greatly appreciated

Kindly help

Mnay thanks in advance
I am trying to write a test class for a simple Controller.. I think I am along the right lines but have an error: Invalid type: OpportunitiesController.. please help!

Custom Controller
public class OpportunityController {
    
    public List<Opportunity> opp {get;set;}

    public OpportunityController() {
        opp = [SELECT Id, Name, CreatedDate, StageName, Placement__c, LDN_Company__c, Description, Job_Title__c, CloseDate, NextStep, Salary__c, Future_Prospects__c, Duration__c, Training_Delivery_Site__c, Qualification_taken__c, Entry_Requirements__c, Key_Responsibilities__c, Skills_Required__c, Account.Name, Account.BillingPostalCode, Account.BillingStreet, Account.BillingCity FROM Opportunity WHERE (StageName = '1 - Qualifying' or StageName = '2 - Booked for CK' or StageName = '3 - Live' or StageName = '4 - Work Trial') AND (Placement__c = 'New Apprentice')];
        	}
}

Test Class method 
 
static testMethod void myUnitTest2() {
    test.startTest();
			        
    Opportunity opp = new Opportunity();
    opp.Name = ' test 001';
			  
    insert opp;
			  		
    PageReference testPage = new pagereference('/apex/Opportunities');
    ApexPages.currentPage().getParameters().put( 'id', opp.id );

    OpportunitiesController OpportunitiesControllerObj = new OpportunitiesController();
	PageReference pageref = OpportunitiesControllerObj.save();
	OpportunitiesControllerObj.getOpportunity();
     test.stopTest();
}

 
public class OpportunityController {
    
    public List<Opportunity> opp {get;set;}

    public OpportunityController() {
        opp = [SELECT Id, Name, CreatedDate, StageName, Placement__c, LDN_Company__c, Description, Job_Title__c, CloseDate, 
				NextStep, Salary__c, Future_Prospects__c, Duration__c, Training_Delivery_Site__c, Qualification_taken__c, Entry_Requirements__c, Key_Responsibilities__c, 
				Skills_Required__c, Account.Name, Account.BillingPostalCode, Account.BillingStreet, Account.BillingCity FROM Opportunity 
				WHERE (StageName = '1 - Qualifying' or StageName = '2 - Booked for CK' or StageName = '3 - Live'
               or StageName = '4 - Work Trial') AND (Placement__c = 'New Apprentice')];
        	}
}

I can't figure out how to approach it for a custom and not standard controller

Thank you

Dear All, 
in the contract object I have two fields. One is a text formula, which fetches the name from the related opportunity. The second one, is a contract text field. 
The problem I have is to detect when the value of the first field changes so that I can update the second one. I thought to a contract trigger:
where I want Customer_Contract_ID__c to get updated every time the value of Contract_Name_ref__c changes. Both are fields from the same contract object. 
For whatever reason I don't see any change.

Thank you for your help.
trigger CustomerContractIDHasChanged on Contract (before update) {

/* Fetch the records that have been udpated */
Map<Id, Contract> m_contract = new Map<Id, Contract> ([SELECT Id FROM Contract WHERE Id IN :Trigger.New]);

If (trigger.isUpdate) {

For (Contract c: Trigger.new) {
    //System.debug('Contract with ID: ', m_contract.size() );
    Contract old_c = Trigger.oldMap.get(c.Id);
    
    System.debug('GIANCAR Contract with Customer Contract ID: ' + m_contract.get(c.Id).Customer_Contract_ID__c );
    System.debug('GIANCAR Contract with Customer Contract Name: ' + m_contract.get(c.Id).Contract_Name_ref__c );

    /*Check if the value has changed, based on the OLD mapping*/
    If (old_c.Contract_Name_ref__c != c.Contract_Name_ref__c) { /*If the value has changed, we update the Customer Contract ID*/
    
        c.Customer_Contract_ID__c = c.Contract_Name_ref__c;
        System.debug('GIANCAR Contract with Customer Contract Name: ' + c.Customer_Contract_ID__c );
    }
}

}

}








 
 there are four objects accounts , policy(custom object) , opportunity , application(custom object). account and policy have masterdetail relationship , account and opportunity also have MD relation. and opportunity have lookup relation with application . every application must have one opportunity assigned.
there is one  field on application called 'status'. 
requiremet :when application status is 'approved by CMS' .  check if related account with opportunity have assigned active  policy?if yes , update application status to "Enrolled" .


code i have written
trigger UpdateApplicationStatusToEnrolled on vlocity_ins__Application__c (before update) {
Map <string,List<vlocity_ins__Application__c>> strMap = new Map <string,List<vlocity_ins__Application__c>>();
set<id> oppid = new set<id>();

for(vlocity_ins__Application__c app :trigger.new)
{
if(app.vlocity_ins__Status__c=='Approved by CMS')
{
oppid.add(app.id);}}




List<opportunity> oppDetails=[SELECT id, AccountId, Account.name ,Account.vlocity_ins__ActivePolicyNumber__c  
 FROM Opportunity where Account.vlocity_ins__ActivePolicyNumber__c >=1 and id IN: oppid];
 
 for(vlocity_ins__Application__c app : Trigger.new)

{
 List<vlocity_ins__Application__c> appList = strMap.containsKey(app.opportunityid) ? strMap.get(app.opportunityId) : new List<vlocity_ins__Application__c>();

                        appList.add(app);

                        strMap.put(app.opportunityId, appList);




 
}

getting error , please help 
  • June 28, 2019
  • Like
  • 0
We have some unused trigger some of active and inactive in production is there a way to delete a trigger in production. 

Thanks
GMASJ
  • June 28, 2019
  • Like
  • 0
I am having a Custom object which sends an email(Process builder does that) to the contact field on the record with a template.

I am trying to 
1. When the contact email clicks reply and fill the template, the response should be returned to the record and linked to the same record.
2. Parse the values in the template and update the record from which email is sent.
I am sure I have to use the inbound email service class but not able to figure on how it works and how to start with.
I had already read on email services and inbound email services but couldn't understand how can I implement that my particular req.

 
Hi Community, 
I'm making my very first steps in triggers and am trying to set up a trigger to save child record data despite of the cascade deletion in master-detail relationship : if a record from the A master object is deleted, if it has any B detail records, those B detail records should be backup in a C record.
I already created a trigger if B is deleted but now can't get the additional trigger on A.
Here is what I did but get an error when trying to get data of the B child records, I must be missing something between the two 'List" ?

trigger BackupAIfAssociated on A (before delete) {
for (A a:trigger.new)
{
    list< B> c = [select B lookup from B where  B lookup=:a.id];
    if (c.size()>0){
    
    List<C> lstToInsrt = new List<C__c>();  
 for(B deletedB : trigger.old)
        {          
        C__c obj = new C__c();
              obj = new C__c();
              obj.B.Name = deletedB.Name

            lstToInsrt.add(obj);
        }
        if(lstToInsrt.size()>0){
            insert lstToInsrt;
        }
        }
}

}

Thank you very much for your help !

I am following the guidelines from the Chatter guide and somehow I can't get the OAuth to work. 

 

It's not working from Java or curl.   Here is what I am doing:

 

mike$ curl --form client_id=3MVG9yZ.WNe6bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxu5AjB4oT9kxi8SEhY --form client_secret=26542xxxxxxxxxxx78  --form grant_type=password --form username=xxxxxxxx@gmail.com --form password=xxxxxxx https://na11.salesforce.com/services/oauth2/token

 

What I am getting is:

{"error":"invalid_grant","error_description":"authentication failure - Invalid Password"}

 

I double checked and I am getting into na11 with the right password.  Is there anything else I need to do?

 

Here are the settings in my remote access:

 



Applicationchatter



Callback URLhttps://na11.salesforce.com/ConnectTest/oauth/_callback /// temp one



No user approval required for users in this organizationNot Checked

 


I am trying build an outer join to display a list of contacts showing if they have a related portal user records or not.

 

I know you can get a list of related contacts from the user object but is it possible to go from contacts to user? 

 

I know this works...Select u.isactive, u.Contact.name From User u but what about Select name, c.user.isactive From Contact c?

 

Any thoughts how I can outer join these two tables and display one list? 

 

Thanks