• Vamsi
  • SMARTIE
  • 1199 Points
  • Member since 2015


  • Chatter
    Feed
  • 32
    Best Answers
  • 4
    Likes Received
  • 6
    Likes Given
  • 34
    Questions
  • 369
    Replies
does schedule job runs exactly at given time that we have mentioned?
When a User record is deactivated, we need to auto-populate any existing Opty records with their active manager (as noted in the user record), so those Opty records always have an active owner and are not sitting in limbo with a de-active user.  We want to automate this process.  
Any suggestions on best approach? 
Thank you, 
T
 
trigger contactTrigger on Contact (before insert,before Update) {
  if(RecursiveTrigger.isFirst){
       if(Trigger.isInsert || Trigger.isUpdate){
           List<String>  emailList = new List<String>();
           for(Contact c:Trigger.new){
             emailList.add(c.Email);
           }
           
           System.debug('email====>>>>'+emailList);
           
           Map<String,User> userMap = new Map<String,User>();
           List<User>  objUser = [Select id,email,FullPhotoUrl from User where Email in: emailList];
           for(User u:objUser){
            if(u.FullPhotoUrl != null)
               userMap.put(u.email,u);
           }
           List<Contact> objContactList = new List<Contact>();
           for(Contact c:Trigger.new){
            if(userMap.containskey(c.Email))
            
             c.Photo_Url__c = userMap.get(c.Email).FullPhotoUrl;
              
           }
           
       }
  }
}
  • June 07, 2018
  • Like
  • 0
Hi ,I have 2 objects "Positions" and "Employment Websites" having many to many relationship between them with "Job Posting" as a junction object.
->I have a case "C1" on "Position" 
->Position "P1" is posted to 3 Employement Websites "W1" ,"W2" and "W3"
->My requirement is to show case "C1" on Employement Website "W1" ,"W2" and "W3"

I have written a trigger for the above requirement but i am stuck
Objects :
Position
Employment Websites
Job Posting (Junction object for Position and Employement Websites)
CaseRelatedList( junction object between case and employement websites)
case (look up to Position)
I am trying to copy case related list from Position to Employment Websites .
Trigger :
trigger CloneCaseRelatedList on Case (after insert) {
    set<string> posId = new set<string>();
    Map<string,Job_Posting__c> posEmpWebsite = new Map<String,Job_Posting__c>();
    if(Trigger.isInsert)
    {
        for(Case c : Trigger.new)
        {
            posId.add(c.Position__c);
                system.debug(posId);
        }
        
    }
    for(Job_Posting__c j : [Select Position__c ,Employment_Website__c from Job_Posting__c where Position__c in : posId ])
    {
        posEmpWebsite.put(j.Position__c, j);
        system.debug(posEmpWebsite);
    }
    //I am stuck at this point How I can loop through all employmemt websites that position have
        
    }
1.I have created CaseRelatedList as a junction object for Employement Website and Case
2.Created trigger on case and from there I am getting positions
3.finding employemnt websites related to position through junction object 'Job Posting'
4.Need to loop through result of step 3. 
How can I loop through it so that I can insert case and employment website on junction object caseRelatedList.
Thanks in advance!!
Error message: "Error: Compile Error: Expression cannot be assigned at line 208 column 36"

Objective: I want to assign two different values to two different fields based on one conditional statement (programmatically) 

Code #1:

The code below works as expected but when I tried to add "&&" in Code #2 the code didn't not run.
 
// Determine coverage 
        
        if (insuranceType == 'BLA') {
             l.Insurance_type__c = 'Bla bla' l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else if(NonAcceptedPlans.contains(groupName)) {
             l.Insurance_type__c = 'Bla bla Bla bla';
        } else if(planDescription == '') {
             l.Insurance_type__c = 'TTT';
        } else {l.Insurance_type__c = 'Bla bla Bla bla Bla bla';}

Code #2:

When adding "&&" to my output part of the conditional statement the code stops working. I get an message: "
Error: Compile Error: Expression cannot be assigned at line 208 column 36"
 
// Determine coverage 
        
        if (insuranceType == 'BLA') {
             l.Insurance_type__c = 'Bla bla' l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else if(NonAcceptedPlans.contains(groupName)) {
             l.Insurance_type__c = 'Bla bla Bla bla' && l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else if(planDescription == '') {
             l.Insurance_type__c = 'TTT' && l.Qualification_message__c = 'Bla bla Bla bla Bla bla Bla bla';
        } else {l.Insurance_type__c = 'Bla bla Bla bla Bla bla' && l.Qualification_message__c = 'Bla bla Bla blaBla bla";}
Hi, 

  I want to update entitlement fields from opportunitylines below is the code written not sure what the issue is it is not firring the update. Please suggest me the change.
 
trigger update_entitlement_product on OpportunityLineItem (after insert, after update) {

   system.debug('Opportunity Line Items Trigger Started.....');

   EntitlementUtil.UpdateEntitlementDate(trigger.new);

}
public with sharing class EntitlementUtil {

public static void UpdateEntitlementDate(List<OpportunityLineItem> newLst){

 set<id> oppid = new set<id>();
 list<entitlement> ent = new list<entitlement>();
 
  for(OpportunityLineItem opp: newLst){
   oppid.add(opp.id);
  }
  
 for(opportunity ops: [select NS_Start_Date_Min__c,NS_End_Date_Max__c from opportunity where id in :oppid]){
    system.debug('Opportunity Lines NS_Start_Date_Min__c :' + ops.NS_Start_Date_Min__c);
    system.debug('Opportunity Lines NS_End_Date_Max__c :' + ops.NS_End_Date_Max__c);
    
   for(entitlement etl : [select Opportunity__c,StartDate,EndDate from Entitlement where Opportunity__c in :oppid]){
    system.debug('Entitlement StartDate :' + etl.StartDate);
    system.debug('Entitlement EndDate :' + etl.EndDate);
    
      etl.StartDate = ops.NS_Start_Date_Min__c;
      etl.EndDate = ops.NS_End_Date_Max__c;
      ent.add(etl);
    }  
  }
 
  if(ent.size() > 0){
    system.debug('Entitlement dates are updated');
    update ent;
  }
  
}
}
Thanks
SD

 
  • June 01, 2018
  • Like
  • 0
I am trying to figure out how to have a if statement on a visualforce page check for two words in a text field. If the conditions are true display a message. I cant firgure out how to do this correctly to work. Below is the code to the field that does not work. Any help would be greatly appreciated.
 
<div class="lost message" style="display:{!IF(AND(CONTAINS(Opportunity.Describe_what_you_need_quoted__c , "Acme"), CONTAINS(Opportunity.Describe_what_you_need_quoted__c , "Inc")),"","none")}" >
      <h2>Opportunity:This is an ACME Opportunity!              
 </h2>
    </div>

 
I am new to SalesForce.  I have created my first Apex Class.  The goal of the class is to read through all ccrz__E_Order__c that are in 'Order Submitted' status.  For each order, read the items.  If all items are currently in 'Received' status, then update the status on the order to 'Order Received'.  I want this to be a batch process ran daily.

Following questions being a first time creator of an Apex Class.
  • Is the best way to trigger this process to run by going into Apex Class and Schedule Apex?  Or is there a more appropriate way to schedule?
  • When testing, I have used Developers Console and executed the class.  However, I run into limits.  Even when I have scheduled in our test environments, i have hit limits.  There are only a couple hundred orders in this status but it hits Too many SOQL queries system limit exception.  Is there a way to test the entire process w/o exceeding these limits?  Are they the same limits when going to production?  When testing I enter specific orders (you'll see commented out line below in the code), but when i read all orders i am hitting these limits.
  • Is there a system log that i can write totals too?  As you can see on the code below i have written beginning / ending / total information into the debug log.  But when going to production, i will comment these out - is there a traditional way to look at this kind of information in a salesforce log.  
I am including the code i have created and appreciate any feedback since this is my first attempt.

Thanks in advance for any advise.  

Dan

/*
 * @Name: Batch_OrderStatus
 * @Author: Dan Norfleet
 * Updates : 02/12/2018 - Dan Norfleet - Created Apex Class
 */
    global class Batch_OrderStatus Implements Schedulable
    {
      global void execute(SchedulableContext sc)
      {
        execute();
      }

      global void execute() 
      {
          System.debug('Batch_OrderStatus BEGIN');
          //  Create a list of Orders in status of 'Order Submitted'
          List<ccrz__E_Order__c> orders = 
                [SELECT Id, Name, ccrz__orderstatus__c 
                FROM ccrz__E_Order__c 
                WHERE ccrz__orderstatus__c = 'Order Submitted'];
//                WHERE ccrz__orderstatus__c = 'Order Submitted' AND Name = 'O-0000112447'];
          Integer total_orders_cnt = 0;
          Integer update_cnt = 0;
          Integer notupdated_cnt = 0;
          String status_received = 'Received';
          String status_order_received = 'Order Received';
          
          // Loop through the list of orders
          for(ccrz__E_Order__c ord : orders)
          { 
            total_orders_cnt = total_orders_cnt + 1;
            String order_id = ord.Id;
            // For each order, see how many items are in 'Received' status
            integer ItemsReceived = 
                    [SELECT COUNT() 
                    FROM ccrz__E_OrderItem__c 
                    WHERE ccrz__orderitemstatus__c = :status_received
                    AND ccrz__order__c = :order_id];
          
            integer ItemsNOTReceived = 
                    [SELECT COUNT() 
                    FROM ccrz__E_OrderItem__c 
                    WHERE ccrz__orderitemstatus__c != :status_received
                    AND ccrz__order__c = :order_id];
          
            if (ItemsReceived > 0)
                    { 
                if (ItemsNOTReceived == 0)
                        { 
                        ord.ccrz__orderstatus__c = status_order_received;
                        System.debug('    UPDATE Order - ID = ' + order_id + ' / Order Name = ' + ord.Name + ' / Items Received = ' + ItemsReceived + ' / ItemsNOTReceived = ' + ItemsNOTReceived);
                        update_cnt = update_cnt + 1;
                        update orders;
                        }
                    else
                        {
                        notupdated_cnt = notupdated_cnt + 1;
                        }
                    }
                
          }
          System.debug('TOTAL ORDERS IN SUBMITTED STATUS = ' + total_orders_cnt);
          System.debug('TOTAL UPDATED = ' + update_cnt);
          System.debug('TOTAL NOTUPDATED = ' + notupdated_cnt);
          System.debug('Batch_OrderStatus END');
      }
}
i have created a student object (child object ) which is in master detail relationship with Course object (parent ) and Student object is not visible in OWD. Why is this? If i want to edit OWD settings of Student object how is that possible.?
I need help writing a validation rule in Accounts that works like this:
If the Creator User has the Business_Unit_c field equal to "TSEB", then theCommercial_DiscountC field must be filled in. And if the Commercial_discount_c field is equal to "Yes", then the Discount_C field must also be filled in.
I have an example class I've just created for illustravive purposes that updates an acount name via a remote action.

I need to be able to write a test class to cover it, and it also needs to contain a system assert/assertequals?

I have written the test class but how do I cover it with a system assert?

Method:
@RemoteAction
global static void updateAccountName (String supplierId, String newName) {

    Account acc = [Select Id, Name From Account Where Id = : supplierId];

    acc.name = newName;
    
    update acc;

}
Test class:
@isTest
public class updateSupplierTest { 

	static testMethod void test () {

        updateAccount con = new updateAccount();

    	//Create an Account
        List<Account> accts = new List<Account>();
        Account b = new Account(Name='Test Buyer',type = 'Account');
        accts.add(b);
        insert accts;

        //Remote actions
        updateAccount.updateAccount(r.id, 'New Account Name');
        System.assertEquals(????); 

    }

}

Thanks
 
  • November 06, 2017
  • Like
  • 0
Hi Guyz,

I just want to create one simple vvalidation rule for a picklist value,

I am inserting a Library Name , once i fill the name, then there is Location with different picklist value.
For Eg: If user enter a name as "Mumbai Library"(Name Would be anything everytime), then location i would be selecting as "Mumbai", records get saved. but while editing the same record,it should not make me change to other location rather than Mumbai...
how it can be done...

I have wriiten below formula, but its not working as per my requirement

AND( ISPICKVAL( Location__c , "Mumbai"), NOT(ISBLANK( Name )) )

please help me to sort out

Regards
Pranav Shah

 
I have a trigger that updates a lookup field based on the value of a text field.  It's working great with the bulk uploads I'm doing, except when the bulk uploads reference the same record for lookup.  The lookup field (Customer Product Mix) populates on the first record, but fails to do so on subsequent records only when the same lookup record is referenced.

User-added image

Here is the code we're using, which I thought was bulkified since all other records populate just fine on a bulk upload.  Any help would be greatly appreciated.
 
trigger UpdateCustomerProductMix on Sales_Order_Line_Item__c (before insert, before update ){
 
    Map<String, Sales_Order_Line_Item__c> CPMToSOLIMap = new Map<String, Sales_Order_Line_Item__c>();

    for(Sales_Order_Line_Item__c soli:Trigger.new)
    {
        CPMToSOLIMap.put(soli.Customer_Product_Mix_UploadID_HIDDEN__c, soli);
 
    }
 
    List<Customer_Product_Mix__c> cpmLst = [SELECT ID, Name FROM Customer_Product_Mix__c where Name in :CPMToSOLIMap.keySet()];
 
    for(Customer_Product_Mix__c cpm : cpmLst){
        CPMToSOLIMap.get(cpm.Name). Customer_Product_Mix__c = cpm.ID;
    }
}



 
  • September 25, 2017
  • Like
  • 0
Hi,
       There is 2 custom object A & B, it's in a master-detail relationship. From the 3rd object, there is 2 lookup field to object A & B. I need to display records in B based on the record in lookup field to object A.
Hello,
I have created a custom object that we use to track different issues. Just like any custom object, I have the notes and attachements related list on there. On the object, there is a multi-select picklist field that contains a few different values. I wrote the following apex trigger to send an email notification when a new NOTE is added. The email will be sent to specific address based upon the value in the muli-select picklist. I am trying to figure out how to add a secuence to the subject line. So everytime a note is added the subject shows that it is the first, third, eighth, etc. 

Example: A new custom object record is created. The user creates a new note, which will trigger and send an email notification to a specified email. Since that was the first note added for that record, the subject line should say, "Update 1: A new note has been added to Custom Object Record. When another note is added, the subject like should say, "Update 2: A new note has been added to Custom Object Record". The number should increment for every new note added.

Any help one this would be great! Thanks!
trigger NoteAddedNotification on Note (after insert) 
{
    
    Set<ID> noteids = new Set<ID>();
    
    for (Note n:Trigger.new)
    {
        
        noteids.add(n.parentID);
    }
    
    List<Custom_Object__c> notelist = new List<Custom_Object__c>([SELECT Id, Name, MultiSelect_Picklist__c FROM Custom_Object__c WHERE ID in:noteids]);
    
     Messaging.SingleEmailMessage NoteToCS = new Messaging.SingleEmailMessage();
    
    	String[] toAddresses1 = new String[]
        {
        	'email1@test.com'
    	};
            
        String[] toAddresses2 = new String[]
        {
            'email2@test.com', 
        };    
        
        String[] toAddresses3 = new String[]{
        	'email3@test.com'    
        };
           
    for(Custom_Object__c c:notelist)
    {
    
        NoteToCS.setSubject('A note has been added to Custom Object: ' +c.Name);
        
        String stringURL  = URL.getSalesforceBaseUrl().toExternalForm()+ '/'+ c.Id;
        
        String body = 'A new note was added to ' + c.Name + '<br/>';
        body += 'Multi-Select Picklist: ' + c.MultiSelect_Picklist__c + '<br/>';
        body += 'Please click on the link to take a look:' + '<br/>';
        body += stringURL;
        
        
         if(String.isEmpty(c.MultiSelect_Picklist__c) && c.MultiSelect_Picklist__c == null)
         {
            
                c.addError('Please select a value for Multi-select Picklist before adding a 
                note.');

         }
        else
        {
               if(c.MultiSelect_Picklist__c.contains('Value1'))
               {
            		NoteToCS.setToAddresses(toAddresses1);
            		NoteToCS.setSaveAsActivity(false);
            		NoteToCS.setHtmlBody('<p style="font-family:Calibri;font-size:24px !important;">' + body + '</p>');
        	 		Messaging.sendEmail(new Messaging.Email[] {
             			NoteToCS
             		});
        		}
        		else if(c.MultiSelect_Picklist__c.contains('Value2'))
                {
            		NoteToCS.setToAddresses(toAddresses2);
            		NoteToCS.setSaveAsActivity(false);
            		NoteToCS.setHtmlBody('<p style="font-family:Calibri;font-size:24px !important;">' + body + '</p>');
        	 		Messaging.sendEmail(new Messaging.Email[] {
             			NoteToCS
             		});
        		}
        		else if(c.MultiSelect_Picklist__c.contains('Value3'))
                {
        			NoteToCS.setToAddresses(toAddresses3);
            		NoteToCS.setSaveAsActivity(false);
            		NoteToCS.setHtmlBody('<p style="font-family:Calibri;font-size:24px !important;">' + body + '</p>');
        	 		Messaging.sendEmail(new Messaging.Email[] {
             			NoteToCS
             		});	                             
        		}
        }
        
    }
update notelist ;
}
Hello,

We have a process which upon Opportunity creation, creates a record entry for a custom object which is linked via Lookup to the opportunity.
I now want to get the ID of the created lookup record and store it in a dedicated field on the opportunity. 
Any idea if I can achieve this with the standard feature of Process Builder or whether APEX is needed?
Many thanks! 
Hi there,

I want to make a trigger that fires when a custom field called "Behaviour Score" hits 100 and above. The trigger will change the current lead owner to a new lead owner that is a queue to be distributed between agents. Can anyone help me? 
my requirement:

Owner id should be changed on them when child of custom object are upserted. Owner Id on these should be updated with the owner id of account to which the upserting record belongs.

Please give me the solution it is very urgent to me. I hope you people will give me solution as soon as possible.
I am new to salesforce... please help... I have requirement like: one custom object Employee having three field Name,Account,Contact. Now I am creating a vf page with this three fields... but when I am saving my record from vf only employyee name is reflected. it is showing account and contact blank. And also i want to go redirect at record page which i am creating through vf when saved.
vf and controller as follows
vf 
<apex:page StandardController="EmployeeA__c" extensions="classes" >
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlock title="Employee Page">
                <apex:PageBlockSection >
                    <apex:inputText value="{!Name}"/>
                    <apex:inputField value="{!EmployeeA__c.Account__c}"/>
                    <apex:inputField value="{!EmployeeA__c.Contact__c}"/>
                </apex:PageBlockSection> 
                <apex:pageBlockSection >
                    <apex:commandButton value="Save" action="{!Save}"/>
                    <apex:commandButton value="Cancel" action="{!Cancel}"/>
                </apex:pageBlockSection>
            </apex:pageBlock>
        </apex:pageBlock>
    </apex:form>
</apex:page>

controller

public with sharing class classes {

    public String Name { get; set; }

    public  String Account {get; set;}
    
    public String Contact {get; set;}
    
   

     
      VAD03__EmployeeA__c objdlt;
     private ApexPages.StandardController controller;
    public classes(ApexPages.StandardController controller) {
    this.controller = controller;
    

    }

public PageReference save() {
        /*
        VAD03__EmployeeA__c objdlt = new VAD03__EmployeeA__c();
        objdlt.Name=Name;
        objdlt.VAD03__Account__c=Account;
        objdlt.VAD03__Contact__c=Contact;
        insert objdlt;
        */
        controller.cancel();   
        PageReference congratsPage = Page.Congratulations;
        congratsPage.setredirect(true);
        return congratsPage;
    }
    
        public PageReference Cancel() {
            
            controller.cancel(); // This takes care of the details for you.
            PageReference congratsPage = Page.Congratulations;
            congratsPage.setRedirect(true);
            return congratsPage;
}
}
 
Hey there,

I'm super new to developing with Salesforce - so it's entirely possible I missed something easy. But with this code as reference: https://help.salesforce.com/articleView?id=entitlements_auto_add.htm&language=en_US&type=0 - I put it in my sandbox as a Case Trigger. It saved correctly (I had to make some bracket changes), and says code coverage 0%.  However when I email for email-to-case, the active entitlement is not applied to the case. Code below...help? :)
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
trigger defaultEntitlement on Case (Before Insert, Before Update) {
   /*
   If the Entitlement Name is not set then, check to see if the Contact on the Case has an active Entitlement
    and select the first one.  If not then check to see if the Account on the Case has an active Entitlement.
   */
   List<Id> contactIds = new List<Id>();
   List<Id> acctIds = new List<Id>();
   for (Case c : Trigger.new){
      if (c.EntitlementId == null && c.ContactId!= null && c.AccountId != null){
         contactIds.add(c.ContactId);
         acctIds.add(c.AccountId);
      }
   }
   if(contactIds.isEmpty()==false || acctIds.isEmpty()==false){
      /* Added check for active entitlement */
      List <EntitlementContact> entlContacts = [Select e.EntitlementId,e.ContactId,e.Entitlement.AssetId From EntitlementContact e
                                                Where e.ContactId in :contactIds
                                                And e.Entitlement.EndDate >= Today And e.Entitlement.StartDate <= Today];
      if(entlContacts.isEmpty()==false){
         for(Case c : Trigger.new){
            if(c.EntitlementId == null && c.ContactId != null){
               for(EntitlementContact ec:entlContacts){
                  if(ec.ContactId==c.ContactId){
                     c.EntitlementId = ec.EntitlementId;
                     if(c.AssetId==null && ec.Entitlement.AssetId!=null)
                        c.AssetId=ec.Entitlement.AssetId;
                     break;
                  }
               } // end for
            }
         } // end for
      } else{
         List <Entitlement> entls = [Select e.StartDate, e.Id, e.EndDate, e.AccountId, e.AssetId
                                     From Entitlement e
                                     Where e.AccountId in :acctIds And e.EndDate >= Today And e.StartDate <= Today];
         if(entls.isEmpty()==false){
            for(Case c : Trigger.new){
               if(c.EntitlementId == null && c.AccountId != null){
                  for(Entitlement e:entls){
                     if(e.AccountId==c.AccountId){
                        c.EntitlementId = e.Id;
                        if(c.AssetId==null && e.AssetId!=null)
                           c.AssetId=e.AssetId;
                        break;
                     }
                  } // end for
               }
            } // end for
         }
      }
   } // end if(contactIds.isEmpty()==false)
}

 
Hi,

We are making a callout to external endpoint from Salesforce to get the attachments. when attachment size is more than 6 MB its throwing me Heap size limit error and we are running this callout from future method, where we are having this limit as 12 MB.

Please advise .... on any workarounds to overcome this ..
 
@future(callout=true)
    public static void SendAttachmentsToCase(Map<string,string> Initialres,ID CaseID,ID UserID,string UserName,string Password,string ticketNumber,string jobtime)
    {

                // Performs another callout to get appropriate attachment 
               List<attachment> FinalAttachmentList = new List<attachment>();
               for(string sg : Initialres.Keyset()) // Map of attachment Names and endpoint
               {
                Http h2 = new Http();
                HttpRequest req2 = new HttpRequest();
                Blob headerValue = Blob.valueOf(UserName+':'+Password);
                String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
                req2.setHeader('Authorization', authorizationHeader);
                req2.setHeader('Content-Type','application/json');
                req2.setEndpoint(Initialres.get(sg));
                req2.setMethod('GET');
                req2.setTimeout(60000);
                try
                {
                system.debug('heap size before req'+' '+ Limits.getHeapSize());
                HttpResponse res2 = h2.send(req2);
                system.debug('resposne'+ ' '+res2.getBody());
                                system.debug('heap size after req'+' '+ Limits.getHeapSize());

                blob image = res2.getBodyAsBlob(); 
                Attachment a = new Attachment (ParentId = CaseID,
                                           Body = image,
                                           OwnerId = UserID,
                                           CreatedById = UserID,
                                           Name = sg);
               FinalAttachmentList.add(a);
                }catch (Exception e)
                {
                    system.debug('exception message at 2nd callout level'+ ' '+ e.getMessage());
                 }
              }

              insert FinalAttachmentList;
    }

 
  • April 17, 2018
  • Like
  • 0
Hi All,

We have created a new User few days back. Now he is being notified of case assignment notification realted to a Queue and to which he doesn't belongs but he is a manager of queue member for that queue. Not sure how he is being notified.

I have reviewed all the workflow and process builder emails alert notification, but didn't find any tracess for this users.

Can someone please let me know, how can we exclude notifications for this users from the Queue.
 
  • November 28, 2017
  • Like
  • 0
We have a requirement that when a customer logs in to customer portal and when they click on the link they should be logged in to 3rd party application automatically with same portal credentials and redirect to a page on 3rd part application.
I was able to get this working from salesforce using connected app but how can we do the same for customer portal.
Please share some thoughts on this...!!!
  • July 13, 2017
  • Like
  • 0
Hi ,

We have a public page embeded with VF page that captures the Customer portal user ID and password to login to customer portal. Now we would like to have these users automatically logged in to Zendesk once they login to customer portal from public web site. I am not sure of how to login to Zendesk via API.

Any thoughts on this would be highly appreciated .....!!!!!
  • July 07, 2017
  • Like
  • 0
Hi,

Could someone please provide any suggestions to acheive the load balancing of cases being assigned to set of users in round robin manner. I have installed the Round robin record assignment (unmanaged) app exchange application. I have modified the code to work for logged in users only and now I need to perform load balancing among the logged in users.

Any thoughts would be helpful...!!!
  • January 30, 2017
  • Like
  • 0
Hi All,

I have installed a round robin record assignment (Un managed package) application from app exchange and now I woud like to modify the code to have this work only for logged in users in salesforce, I have tried retrieving the session info from "Authsession" object but I could see a multiple sessions opened for a user and I am not sure whether a user is currently logged in or not and our ORG has a session time out set to 12 hours.

Any thoughts would be really appreciated...!!!!
Thanks in advance ..!!!
  • January 25, 2017
  • Like
  • 0
Hi All,

I have a requirement to bring up the same look and feel for a custom look-up field (Faculity) (lookup to user object) similar to record owner change. I mean, we would like to have a similar page opened like record owner change, when a user clicks on the Faculity custom look-up field instead of standard user look-up page. Also the Send notificaion email button should send an email to faculity if its marked true.

record owner change​ page 
User-added image
We would like to have above page opened, when an user clicks on the Faculity look-up field .
User-added image

Any thoughts would be highly appreciated...!!!

Thanks in advance ...!!!
  • November 04, 2016
  • Like
  • 0
Hi,

Can someone please let me know, Can we override the standard save and close button on case edit page or remove from page layout 
  • August 30, 2016
  • Like
  • 0
Hi,

I have a test class, which seems to be passed when run through the developer console but when I run through the apex test execution it fails 

Any thoughts would be appreciiated 

Thanks..!!!
  • August 25, 2016
  • Like
  • 0
HI,
I have a class the returns the set of records based on createddate. So how to write a test class and test the results of that class ..
In a test class, If I instantiate a class and call the method then it covers me 100%. But when I try to verify the results it doesn't return me any records.

Also I have gone through some blog and got that we can provide values to created date on test class using test.setcreateddate(recordid,datetime)

Can someone please help me ...!!!
 
public with sharing class UnclaimCases
{
    public list<case> caseami {get;set;}
    public string strhours = Label.DateFilter; // custom label stores values in hours 
    public integer hours = integer.valueof(strhours);
    Datetime currenttime = system.now();
    datetime  acttime  = currenttime.addhours(-hours);
    public final static Id custid = Schema.SObjectType.case.getRecordTypeInfosByName().get('Support').getRecordTypeId();   

    public UnclaimCases()
    {

     caseami = [Select CaseNumber,Priority,Response_Due_Date__c,Response_time_elapsed__c from case where RecordTypeID =:custid AND (Status = 'Unclaimed' OR Status ='Escalated' ) AND Product_Type__c = 'A' AND Owner.Name = 'T Queue' AND Createddate>: acttime  AND Createddate< : currenttime  ORDER BY Priority  LIMIT 10000 ];
    }

    public pagereference inc()
     {
         Datetime currenttimeami = system.now();
         datetime  acttimeami  = currenttime.addhours(-hours);
         caseami = [Select CaseNumber,Priority,Response_Due_Date__c,Response_time_elapsed__c from case where RecordTypeID =:custid AND (Status = 'Unclaimed' OR Status ='Escalated' ) AND Product_Type__c = 'A' AND Owner.Name = 'T Queue' AND Createddate>: acttimeami  AND Createddate<: currenttimeami ORDER BY Priority LIMIT 10000 ];

         system.debug('caseami' + caseami );
         system.debug(' current datetime value ' + currenttimeami );
         system.debug(' act datetime value ' + acttimeami );
        return null;
    }


}
Test class 
@isTest
public class TestUnclaimCases 
{

    @isTest static void Unclamethod()
        {

            Id queueId =[select Id from Group where Name = 'T Queue' and Type = 'Queue'].Id;

            Id custid = Schema.SObjectType.case.getRecordTypeInfosByName().get('Support').getRecordTypeId(); 

            case c1 = new case(RecordTypeId = custid, Status = 'Unclaimed', Product_Type__c = 'A',Priority = 'SEV 1' , ownerid=queueId);
              insert c1;
    datetime delay1 = datetime.now.addhours(-2);
          Test.setcreateddate(c1,delay1);
            case c2 = new case(RecordTypeId = custid, Status = 'Rep On Site', Product_Type__c = 'A',Priority = 'SEV 2' , ownerid=queueId);
           insert c2;
  datetime delay2 = datetime.now.addhours(-2);
          Test.setcreateddate(c2,delay2);
            case c3 = new case(RecordTypeId = custid, Status = 'Escalated', Product_Type__c = 'A',Priority = 'SEV 2' );
            insert c3;
          datetime delay3 = datetime.now.addhours(-2);
          Test.setcreateddate(c3,delay3);

            UnclaimCases uc = new UnclaimCases();
            uc.inc();
            //list<case> fuc.caseami;
            system.assertEquals(2,uc.caseami.size());


        }
    }

 
  • August 24, 2016
  • Like
  • 0
Hi,

I have a class the returns the set of records based on lastmodified date. So how to write a test class and test the results of that class ..

In a test class, If I instantiate a class and call the method then it covers me 100%. Not sure how to verify the results 

In the below class I am using custom labels to store the number of hours 
Apex class
 
public with sharing class UnclaimCases
{
    public list<case> caseami {get;set;}
    public string strhours = Label.DateFilter;
    public integer hours = integer.valueof(strhours);
    Datetime currenttime = system.now();
    datetime  acttime  = currenttime.addhours(-hours);
    public final static Id custid = Schema.SObjectType.case.getRecordTypeInfosByName().get('Support').getRecordTypeId();   
    
    public UnclaimedAMICases()
    {
     
     caseami = [Select CaseNumber,Priority,Response_Due_Date__c,Response_time_elapsed__c from case where RecordTypeID =:custid AND (Status = 'Unclaimed' OR Status ='Escalated' ) AND Product_Type__c = 'A' AND Owner.Name = 'T Queue' AND LastModifiedDate >: acttime  AND LastModifiedDate < : currenttime  ORDER BY Priority  LIMIT 10000 ];
    }
    
    public pagereference inc()
     {
         Datetime currenttimeami = system.now();
         datetime  acttimeami  = currenttime.addhours(-hours);
         caseami = [Select CaseNumber,Priority,Response_Due_Date__c,Response_time_elapsed__c from case where RecordTypeID =:custid AND (Status = 'Unclaimed' OR Status ='Escalated' ) AND Product_Type__c = 'A' AND Owner.Name = 'T Queue' AND LastModifiedDate >: acttimeami  AND LastModifiedDate <: currenttimeami ORDER BY Priority LIMIT 10000 ];
         system.debug('caseami' + caseami );
         system.debug(' current datetime value ' + currenttimeami );
         system.debug(' act datetime value ' + acttimeami );
        return null;
    }
    

}

 
  • August 19, 2016
  • Like
  • 0
Hi,

I am having issue with group of users. when they create a new case they are being redirected to knowledge articles, but they dont have knowledge user licence.

Any thoughts would be highly appreciated...!!!
  • August 17, 2016
  • Like
  • 0
Hi,

Can someone please help me in covering the test class for the below code and I have tried a lot to cover it to 100% but I am getting 81% 

public with sharing class COCaseComment
{
    public String test2 {get;set;}
    public String test1 {get;set;}
    public string status {get;set;}

    public void save() {
        Id caseId = ApexPages.currentPage().getParameters().get('caseid');
        SavePoint sp = Database.setSavePoint();
        status = 'unsaved';
        try {
            Case c = [SELECT Id,status,xyz1__c, xyz2__c FROM Case WHERE Id = :caseId FOR UPDATE];
            c.Status = 'Closed';
            insert new casecomment(ParentId = caseId, commentbody = 'Question:'+ '\n' + test1 + '\n' + 'solution :'+ '\n'+ test2 , IsPublished = true);
            update c;
            status = 'saved';
        } catch(Exception e) {
            Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, e.getMessage()));
            Database.rollback(sp);
        }
    }
}

Test class 

@isTest
public class TestCustomerOperationsCaseComment
{
    @isTest public static void withcaseid() {
        case c = new
        case (status = 'New', Origin = 'Phone', xyz1__c= 'AMR', xyz2__c = 'Charting Issues');
        insert c;
        case ca = [select id, status, xyz1__c ,xyz2__c from case where status = 'New'];
        Test.setCurrentPage(page.COcaseComment);
        COCaseComment cs = new COCaseComment();
        cs.Test1 = ('test1');
        cs.Test2 = ('test2');
        apexpages.currentPage().getparameters().put('caseid', ca.id);
        if (ca.id != null) {
            cs.save();
        }
        casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
        string str = 'Question:'+ '\n' + test1 + '\n' + 'solution:'+ '\n'+ test2 ;
        system.assertEquals(str, cm.CommentBody);
        system.assert(true, cm.ispublished);
        case g = [select Status from case where ID = :ca.Id ];
        system.assertEquals('Closed', g.status);
    }


    @isTest static void caseWithoutproduct() 
   {
      
            case c = new
            case (status = 'New', Origin = 'Phone', xyz2__c = 'Charting Issues');
            insert c;
            pagereference pr = page.COcaseComment;
            pr.getParameters().put('caseid', c.Id);
            test.setCurrentPage(pr);
            COCaseComment cc = new COCaseComment();
            cc.save();
          System.assert(ApexPages.hasMessages(ApexPages.SEVERITY.Error));
         System.assertEquals('unsaved', cc.status);
    
    }
}



 
  • July 28, 2016
  • Like
  • 1
Hi,

I have a soql query where I am using custom labels to specify the date range in string example : THIS_WEEK or something else in future and binding it to the lastmodified date time. when I bind it throws me the below error any thoughts would be appreciated.
In apex

soql query :
  Select status ,CaseNumber,Priority from case where LastModifiedDate =:Label.Thisweek (Thisweek contains a value : THIS_WEEK)

error : Invalid bind expression type of String for column of type Datetime 
 
  • July 22, 2016
  • Like
  • 0
Hi,

I have a requirement to build a bar chart with
1. x-axis labelled "Cases grouped by week"contains the case last modified date grouped by each week (Starting from saturday - friday) from last 6 Months and data need to be grouped by case product type "X" and "Y".
2. Y -axis with % of records passed by case products "X" and "Y"  (I have another custom fields on case records named pass/fail it is a formula field and it will output pass or fail .So based on this I need to calculate the % of records passed only) .

Could someone please suggest me that can we acheive the above scenario using VF charting ??

In the standard report builder I am able to acheive the above except the case last modified date grouped by week starting from Saturday to Friday (In standard grouping of calender week I can see week starting from Sunday - Saturday i.e 7/3/2016 to 7/9/2016 ). But i need week starting from Saturday to Friday as 7/2/2016 to 7/8/2016 , 7/9/2016 to 7/15/2016.

 
  • July 06, 2016
  • Like
  • 0
Hi,

I have written a test class that covers 86% leaving out the apexpages.addmessage () in catch block, but majorly it throws the validation exceptions on that object when I try to update a record.(Here I am updating case status to closed and I have some custom fields to be filled out while closing the case).

My test class has 2 methods. 1st method is having the case with all the fields filled this covers all the code except catch block and 2nd method without the required fields while closing the case and even though it doesn't cover my test class to full 100% 

Can someone please provide any suggestions .

In my case I am updating the case status to closed and while closing the case I have 2 custom fields that should not be "null" 1. xyz1__c and 2.xyz2__c (Their are validation rules written on the case obejct and therse throwing me the exceptions if these fields are null while updating the case) I am not sure how to cover the validation exception in catch black in Test class 


Apex controller 
public with sharing class OCaseComment
{
    public String test2 { get; set; }
    public String test1 { get; set; }
    public string status {get;set;}
    public casecomment ca;
    public case c ;
    public ID caseId ;
    
    public pagereference save() 
    {
        
        caseId = ApexPages.currentPage().getParameters().get('caseid');
        system.debug('case id entered' + caseId);
        ca = new casecomment();
        ca.ParentId= caseId;
        ca.commentbody = 'question:'+ test1 + '\n' + 'solution:'+ test2 ;
        ca.IsPublished = true;
        list<case> c = [select Status, xyz1__c, xyz2__c from case where ID=:caseId];
        list<case> cg = new list<case>();
        for(case cd : c)
        {
            cd.Status = 'Closed';
            cg.add(cd);   
        }
       
        try{   
             if(cg.size() > 0 && cg[0].xyz1__c!= null && cg[0].xyz2__c !=null)
        {
            insert ca;
        }
            update cg;
            status = 'saved'; 
            system.debug('status value'+ status);
           
        }catch(DmlException d)
        {
            Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;  
            status = 'unsaved';
        }
        return null;
    }
    
    
}

Test class 

@isTest
public class TestClassOCaseComment
{
    @isTest public static void withcaseid()
    {
        
            case c = new case(status = 'New',Origin = 'Phone',xyz1__c= 'Stats',xyz2__c= 'Issues');
            insert c;
            case ca = [select id, status,xyz2__c from case where status = 'New'];
            Test.setCurrentPage(page.SCaseComments);
            OCaseComment cs = new OCaseComment();
            cs.Test1=('test1');
            cs.Test2=('test2');
            apexpages.currentPage().getparameters().put('caseid', ca.id);
            if(ca.id != null)
               {
                 cs.save();
               }
       
            casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
            string str = 'Question:'+ cs.test1 +'\n'+ 'Solution:'+ cs.test2 ;
            system.assertEquals(str , cm.CommentBody);
            system.assert(true, cm.ispublished);
            case g = [select Status from case where ID =: ca.Id];
            system.assertEquals('Closed', g.status);
     
     }
    
    @isTest static void caseWithoutproduct()
    {
        try{
            case c = new case(status = 'New',Origin = 'Phone', xyz2__c= 'Issues');
        insert c;
        pagereference pr = page.SCaseComments;
        pr.getParameters().put('caseid',c.Id);
        test.setCurrentPage(pr);
       OCaseComment cc = new OCaseComment();        
            cc.save();  
        }catch (Exception e){     
              System.Assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));
            System.Assert(e.getMessage().contains('xyz1__c'));
                               }
}
}
  • June 22, 2016
  • Like
  • 0
Hi,

I have written a test class that covers 86% leaving out the apexpages.addmessage () in catch block, but majorly it throws the validation exceptions on that object when I try to update a record.(Here I am updating case status to closed and I have some custom fields to be filled out while closing the case).

My test class has 2 methods. 1st method is having the case with all the fields filled this covers all the code except catch block and 2nd method without the required fields while closing the case and even though it doesn't cover my test class to full 100% 

Can someone please provide any suggestions .


 
  • June 20, 2016
  • Like
  • 0
Hi,

I have a requirement to put a case record link in email template. so that it can be accessed by the customer portal users.

I have tried appending the record id to my customer portal url, but it throws me an error.

Any thoughts would be appreciated.
  • June 16, 2016
  • Like
  • 0
Hi ,

Can someone please help me to cover the below 2 lines in catch block in my contoller class 

  Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;
            status = 'unsaved';
I have used the below code in my class but its entering the catch block while testing, but not sure how to cover those lines.
if(Test.isRunningTest())
              integer intt = 10/0;

Apex class 

public with sharing class mycasecom {

    public String test2 { get; set; }
    public String test1 { get; set; }
    public string test3 {get;set;}
    public string status {get;set;}
    public casecomment ca;
    public case c ;
    public ID ID ;
       
     public void save() 
     {
     
     id = ApexPages.currentPage().getParameters().get('caseid');
     system.debug('case id entered' + ID);
      ca = new casecomment();
      ca.ParentId= id;
      ca.commentbody = test1 + '\n' + test2 + '\n' + test3;
      ca.IsPublished = true;
      list<case> c = [select Status from case where ID=:ID];
      list<case> cc = new list<case>();
      for(case cd : c)
      {
          cd.Status = 'Closed';
          cc.add(cd);
      }
      try {
             insert ca;
              update cc;
           status = 'saved';
         system.debug('status value'+ status);
       
          if(Test.isRunningTest())
              integer intt = 10/0;
       }catch(DmlException d)
      {
       Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;
            status = 'unsaved';
      }

}
}

Test Class 

@isTest
public class PopupTestClass 
{
    @isTest public static void withcaseid()
    {
        
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        case ca = [select id, status from case where status = 'New'];
        pagereference p = page.casecomment;
        test.setCurrentPage(p);
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
   
        apexpages.currentPage().getparameters().put('caseid', ca.id);
        cs.save();
        
        casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
        string str = cs.test1 +'\n'+ cs.test2 +'\n' +cs.test3;
        system.assertEquals(str , cm.CommentBody);
        system.assert(true, cm.ispublished);
        case g = [select Status from case where ID =: ca.Id];
        system.assertEquals('Closed', g.status);
        
        
            }
    
    @isTest static void withoutcaseid()
    {
        
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        pagereference p = page.casecomment;
        test.setCurrentPage(p);
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
       
        apexpages.currentPage().getparameters().put('caseid', null);
        cs.save();
       
        system.assertEquals('unsaved', cs.status);
        
   }
}
  • June 15, 2016
  • Like
  • 0
Hi ,

I have a requirement where I need to display a vf page as pop -up  on button click on case and the vf page would include some text questions and once these are answered and user clicks on save button , then these text values should be inserted as a new comment to that particular case.

I have started working on this but when I create a new case comment by supplying required fields Parentid and commentbody. It throws me an error : Parentid doesn't exist or some time commentbody doesn't exists.

Can someone please help me....


Error: test Compile Error: Variable does not exist: CommentBody at line 13 column 8

public with sharing class test 
{
    public string text {get;set;}
    private CaseComment c ;
    
    public test ()
    {
        c = new CaseComment ();
    }
   public PageReference save() 
   {
       c = new CaseComment();
       c.CommentBody = text ;   ***** error *********
       c.ParentId = '5009000000dza7i';
       insert c ;
        
        return null;
   }

    
    
    
}
 
  • June 10, 2016
  • Like
  • 0
Hi,

Can someone please help me in covering the test class for the below code and I have tried a lot to cover it to 100% but I am getting 81% 

public with sharing class COCaseComment
{
    public String test2 {get;set;}
    public String test1 {get;set;}
    public string status {get;set;}

    public void save() {
        Id caseId = ApexPages.currentPage().getParameters().get('caseid');
        SavePoint sp = Database.setSavePoint();
        status = 'unsaved';
        try {
            Case c = [SELECT Id,status,xyz1__c, xyz2__c FROM Case WHERE Id = :caseId FOR UPDATE];
            c.Status = 'Closed';
            insert new casecomment(ParentId = caseId, commentbody = 'Question:'+ '\n' + test1 + '\n' + 'solution :'+ '\n'+ test2 , IsPublished = true);
            update c;
            status = 'saved';
        } catch(Exception e) {
            Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, e.getMessage()));
            Database.rollback(sp);
        }
    }
}

Test class 

@isTest
public class TestCustomerOperationsCaseComment
{
    @isTest public static void withcaseid() {
        case c = new
        case (status = 'New', Origin = 'Phone', xyz1__c= 'AMR', xyz2__c = 'Charting Issues');
        insert c;
        case ca = [select id, status, xyz1__c ,xyz2__c from case where status = 'New'];
        Test.setCurrentPage(page.COcaseComment);
        COCaseComment cs = new COCaseComment();
        cs.Test1 = ('test1');
        cs.Test2 = ('test2');
        apexpages.currentPage().getparameters().put('caseid', ca.id);
        if (ca.id != null) {
            cs.save();
        }
        casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
        string str = 'Question:'+ '\n' + test1 + '\n' + 'solution:'+ '\n'+ test2 ;
        system.assertEquals(str, cm.CommentBody);
        system.assert(true, cm.ispublished);
        case g = [select Status from case where ID = :ca.Id ];
        system.assertEquals('Closed', g.status);
    }


    @isTest static void caseWithoutproduct() 
   {
      
            case c = new
            case (status = 'New', Origin = 'Phone', xyz2__c = 'Charting Issues');
            insert c;
            pagereference pr = page.COcaseComment;
            pr.getParameters().put('caseid', c.Id);
            test.setCurrentPage(pr);
            COCaseComment cc = new COCaseComment();
            cc.save();
          System.assert(ApexPages.hasMessages(ApexPages.SEVERITY.Error));
         System.assertEquals('unsaved', cc.status);
    
    }
}



 
  • July 28, 2016
  • Like
  • 1
When an Opportunity Owner is creating a New Opportunity, if they press the “Enter” key, the user will receive the following message “Do you want to save this Opportunity?” with buttons for “Yes” and “No”.
 
  • If the user selects “Yes” and all required fields have been completed, the opportunity will save and the opportunity owner will be taken to the newly created Opportunity Record.
  • If the user selects “Yes” before all required fields have been completed, the opportunity owner will receive the normal errors that state certain fields are required.
  • If the user selects “No”, the user will be taken to the “Opportunities” section.
Hi! I have a problem - when I change the opportunity probability from 75% to 100%, automatically changes business date. Up to now everything was okay - the business date stayed the same as it supposed to be. Can anyone help me with this?
hi all,

     I need to create a way to capture when the first response. I then need to measure how long time between when the Case was opened and       when it was first responded. 

I created two fields: 
Time_to_First_Response__c 
First_Response__c

I need to capture the first response and measure the time to first response in a trigger . 

First Response is defined as when the case owner user makes any edit to the case or logs an activity against the case. 

Time to First Response Calculation: 
I need to NOT include when office is closed (nights, weekends, holidays) in calculation. 
Hi All,
         I know this is popular error message, but I need to understand something about this error.

         I have an Apex Controller used in a vf page.
         This class has 4 SOQL queries.
        1) select id,name from object1__c where id=:ids --> 5000 records
        2) select id,name from object2__c where id =:ids --> 8000 records
        3) select id,name,(select id,name from object3_1__c ) from object3__c where id =:ids --> 2000 records
        4) select id,name from object4__c where id =:ids --> 8000 records

      From Debug logs, I could see below when a button is clicked, which inturn calling the Apex Class:

       Number of query rows: 32000 out of 50000

       
I read from the document that for sub-queries/ queries with parent child relationship, the record count would be 3 or more times the actual records returned. But, can I know how exactly this "Number of query rows" be calculated ?

Thanks.
/*
End Date of subscrition  and total membership fee Calculation :

Term__c is picklist and values are 12,24,36,48
Start_Date__c  is Start Date of  subscrition .
Rate__c  is number field for per month fee

I want have two Formula field should work like
End_date      = Start_Date__c + Term__c
Total_Amount = Rate__c * Term__c
*/

/*Formula for End Date formula(Date) Field is : */

IF(ISPICKVAL(Term__c, "12"), ADDMONTHS(Start_Date__c,12),
  IF(ISPICKVAL(Term__c, "24"), ADDMONTHS(Start_Date__c,24),
      IF(ISPICKVAL(Term__c, "36"), ADDMONTHS(Start_Date__c,36),
           IF(ISPICKVAL(Term__c, "48"), ADDMONTHS(Start_Date__c,48),null))))
           
/*Formula for Total Amount formula(currency) Field is : */

CASE(TEXT(Term__c),
         "12", (12* Rate__c) ,
          "24", (24* Rate__c) ,
          "36", (36* Rate__c) ,
          "48", (48* Rate__c) ,
0)

What is test away to rewrite this two formula function that is more dynamic . like i dont' need to set 12,36 ... in my formula.

 
I have created a custom object for attachment with Opportunity as the parent. I want to link opportunity stage to this object. One should be able to mark the stage as closed won only when the custom object has some attachment. Need a validation rule for this. Have tried this script
AND(ISPICKVAL(StageName,"Closed Won"),  ISBLANK($ObjectType.OpportunityAttachment__c.Fields.Name))
It shows no syntax error, but does not function while marking the stage as closed won
I want to create test class for this trigger: 
trigger TriggerApprovalCommentOpp on Opportunity (before update) {
if(trigger.isUpdate){
             List<Opportunity> opptyList =  [Select id,
                                                   (Select Id, 
                                                         IsPending, 
                                                         ProcessInstanceId, 
                                                         TargetObjectId, 
                                                         StepStatus, 
                                                         OriginalActorId, 
                                                         ActorId, 
                                                         RemindersSent, 
                                                         Comments, 
                                                         IsDeleted, 
                                                         CreatedDate, 
                                                         CreatedById, 
                                                         SystemModstamp 
                                                    FROM ProcessSteps
                                                ORDER BY CreatedDate DESC) 
                                                    From opportunity
                                                WHERE Id IN : Trigger.new];

             if(opptyList.size() > 0){

               for(Opportunity opp : opptyList){
              
                for(Opportunity opp1 : Trigger.new) {
                  
                         //check copy comment is true
                         if(opp.id == opp1.id && opp1.CopierCommentaires__c) {
 
                           if (opp.ProcessSteps.size() > 0) {
                            
                         opp1.Drniercommentairedapprobation__c = opp.ProcessSteps[1].Comments;
                         opp1.CopierCommentaires__c = false;
                         
                
                           }
                           
                        }
                 
                    }
               }
             }   
        }  
}

Can you help me.
  • June 13, 2018
  • Like
  • 0
Hi All,
I have two triggers in quote and Quote line item
Quote Trigger; v2_QuoteTaxUpdate
Quote line Item Trigger: RolluplineitemTrigger

while testing the RolluplineitemTrigger in QuotelineItem am  getting the following error

User-added image

kindly Let me know where am doing mistake
RolluplineitemTrigger;

trigger RolluplineitemTrigger on QuoteLineItem  (after insert, after update) {

    List<Id> VQuoteID = new List<Id>();
    
    for(QuoteLineItem p: Trigger.new) {
        VQuoteID.add(p.QuoteiD);
    }
    
    AggregateResult[] groupedResults = [SELECT Sum(Stock_Not_Available__c) lineItemCOunt, QuoteiD FROM QuoteLineItem 
    WHERE QuoteiD in :VQuoteID  GROUP BY QuoteiD];
    
    Map<id,Quote> QuoteMap = new Map<Id,Quote>([SELECT id, No_of_Products_Stock_Not_Available__c 
    FROM Quote WHERE Id in :VQuoteID]); 
    
    for(AggregateResult ar: groupedResults) {
    
    QuoteMap.get((Id)ar.get('QuoteiD')).No_of_Products_Stock_Not_Available__c = (decimal) ar.get('lineItemCOunt');

       
    }
    
    //try {
        update QuoteMap.values();
    //}   catch(DmlException e) {
        //System.debug(e.getMessage());
    //}

}

v2_QuoteTaxUpdate:

trigger v2_QuoteTaxUpdate on Quote (after insert, after update) {

    list<QuoteLineItem> lstUpdateQLI = new list<QuoteLineItem>();
    set<id> setQuoteId = new set<id>();
     set<id> setQuoteIdTaxUpd = new set<id>();
    set<id> setQLIId = new set<id>();
    set<String> setHSNCode = new set<String>();  
    List<Id> VQuoteID = new List<Id>();  
    map<string, list<Tax_Master__c>>mapTaxMasToTaxKey = new map<string, list<Tax_Master__c>>();    
        
    for(Quote iQLI : Trigger.New){   
        If(Trigger.Isinsert) {
        
            if(iQLI.Tax_Classification__c !=''){
            
                setQuoteId.add(iQLI.id);
                setQuoteIdTaxUpd.add(iQLI.id);
                system.debug('****setQLIId'+setQLIId);       
                
            }
        }
        
        if(Trigger.isupdate) {
        
         if(iQLI.Tax_Classification__c!=''){
            
                setQuoteId.add(iQLI.id);
                setQuoteIdTaxUpd.add(iQLI.id);
                system.debug('****setQLIId'+setQLIId);       
          }            
          if(iQLI.Discount_Amount__c!=Null){  
          
              setQuoteId.add(iQLI.id);
              system.debug('****setQLIId'+setQLIId);  
          }
        
        }
        
    }
    
        
    
    if(setQuoteId.size() > 0){
    
        for(Quote iQuot : [SELECT id,(SELECT id, Product2.HSN_Code__c FROM QuoteLineItems ) 
            FROM Quote WHERE Id IN :setQuoteIdTaxUpd]){
        
            for(QuoteLineItem iQLI : iQuot.QuoteLineItems){
                  
                    if(iQLI.Product2.HSN_Code__c != ''){
                    
                        setHSNCode.add(iQLI.Product2.HSN_Code__c);
                    }    
            }   
            system.debug('****setHSNCode'+setHSNCode);                    
        }
        
        if(setHSNCode.size() > 0){
        
            if(setHSNCode.size() > 0){
            
                for(Tax_Master__c iTM : [SELECT id, Product_Family__c,Product_Sub_Family__c,HSN_Code__c, IGST__c, CGST__c, SGST__c, Active__c,Start_Date__c,End_date__c FROM Tax_Master__c  WHERE HSN_Code__c IN :setHSNCode ]){
                
                     String ikey = iTM.HSN_Code__c;
                    if(!String.isblank(iTM.Product_Family__c))
                    {
                        ikey = ikey + iTM.Product_Family__c;                         
                    } 
                    if(!String.isblank(iTM.Product_Sub_Family__c))
                    {
                        ikey = ikey + iTM.Product_Sub_Family__c;                         
                    } 
                    list<Tax_Master__c> lstTax = new list<Tax_Master__c>();
                    lstTax.add(iTM);
                    if(mapTaxMasToTaxKey.containskey(ikey))
                    {
                        lstTax.addall(mapTaxMasToTaxKey.get(ikey));
                    }
                    mapTaxMasToTaxKey.put(ikey, lstTax); 
                                 
                 }   
                    system.debug('****mapTaxMasToTaxKey'+mapTaxMasToTaxKey);                    
 
            }  
            
                  
            
            for(Quote iQuot : [SELECT id, Tax_Classification__c, Discount_Amount__c,Anki_total_Amt__c,
                (SELECT CreatedDate,Product2.family, Product2.Sub_Family__c,Product2.HSN_Code__c, Tax_Master__c, IGST__c, CGST__c, SGST__c FROM QuoteLineItems) 
                FROM Quote WHERE Id IN :setQuoteId]){
            
                for(QuoteLineItem iQLI : iQuot.QuoteLineItems){  
                       
                       system.debug('****iQuot.Discount_Amount__c'+iQuot.Discount_Amount__c); 
                       system.debug('****iQuot.Anki_total_Amt__c'+iQuot.Anki_total_Amt__c); 
                          
                          if(iQuot.Discount_Amount__c <= 0 ){
                                iQLI.Q_Discount__c = 0;    
                          
                            } else {
                                if(iQuot.Discount_Amount__c != null && iQuot.Anki_total_Amt__c !=null){
                                iQLI.Q_Discount__c =(iQuot.Discount_Amount__c/iQuot.Anki_total_Amt__c) * 100;
                                
                                }
                            } 
                                                       
                         system.debug('****Q_Discount__c'+iQLI.Q_Discount__c);
                        Date myDate =  date.parse('11/10/2017');
                        Date myDate2 = date.parse(iqli.CreatedDate.day()+'/'+iqli.CreatedDate.month()+'/'+iqli.CreatedDate.year());
                        
                        Tax_Master__c itax = new Tax_Master__c();
                        
                        
                        if(mapTaxMasToTaxKey.containsKey(iQLI.Product2.HSN_Code__c+iQLI.Product2.Family+iQLI.Product2.Sub_Family__c) && myDate2 >= myDate ){
                            for(Tax_Master__c irow : mapTaxMasToTaxKey.get(iQLI.Product2.HSN_Code__c+iQLI.Product2.Family+iQLI.Product2.Sub_Family__c))
                            {
                                if(irow.Start_Date__c <= iqli.CreatedDate && irow.End_Date__c  >= iqli.CreatedDate)
                                {
                                
                                    itax = irow;
                                    break;
                                }
                            }
                        }
                        else if(mapTaxMasToTaxKey.containsKey(iQLI.Product2.HSN_Code__c+iQLI.Product2.Family) && myDate2 >= myDate ){
                            
                            for(Tax_Master__c irow : mapTaxMasToTaxKey.get(iQLI.Product2.HSN_Code__c+iQLI.Product2.Family))
                            {
                                if(irow.Start_Date__c <= iqli.CreatedDate && irow.End_Date__c  >= iqli.CreatedDate)
                                {
                                
                                    itax = irow;
                                    break;
                                }
                            }
                        }else if(mapTaxMasToTaxKey.containsKey(iQLI.Product2.HSN_Code__c))
                        {
                            for(Tax_Master__c irow : mapTaxMasToTaxKey.get(iQLI.Product2.HSN_Code__c))
                            {
                                if(irow.Start_Date__c <= iqli.CreatedDate && irow.End_Date__c  >= iqli.CreatedDate)
                                {
                                
                                    itax = irow;
                                    break;
                                }
                            }
                        }
                        
                        if(!String.isblank(itax.id)){
                    
                        iQLI.Tax_Master__c = itax.id;
                        
                        
                        
                        if(iQuot.Tax_Classification__c == 'IGST'){
                        
                            iQLI.IGST__c = itax.IGST__c;
                            iQLI.SGST__c = 0; 
                            iQLI.CGST__c = 0;
                            //iQLI.Q_Discount__c = iQuot.Ankidyne_Discount_Percentage__c;
                        } 
                        
                        if(iQuot.Tax_Classification__c == NUll){
                        
                            iQLI.SGST__c = 0;
                            iQLI.CGST__c = 0;    
                            iQLI.IGST__c = 0;  
                            //iQLI.Q_Discount__c = iQuot.Ankidyne_Discount_Percentage__c;                      
                        }
                        if(iQuot.Tax_Classification__c == 'SGST'){
                        
                            iQLI.SGST__c = itax.SGST__c;
                            iQLI.CGST__c = itax.CGST__c;    
                            iQLI.IGST__c = 0;  
                            //iQLI.Q_Discount__c = iQuot.Ankidyne_Discount_Percentage__c;                      
                        }                       
                        
                        lstUpdateQLI.add(iQLI);                            
                    }    
                                         
                }    
            }  
            
            if(lstUpdateQLI.size() > 0){            
                update lstUpdateQLI;
            }          
        }
    }
}

 
Hi,
I am getting an error when testing and trying to deploy the below trigger
How do I change the list to a map as I think thats the error.  I am not an apex coder and am trying to learn

first trigger which updates a contact  record to customer upon the opportunity setting to won (contact role): -
trigger UpdateContactToCustomer on Opportunity (after insert, after update) {

        OpportunityContactRole ocr;
        Contact contact;
        Opportunity opp = Trigger.new[0];
        
        list<Contact> listToUpdate = new list<Contact>();
        
        if(opp.StageName == 'Complete - Live'){

            
            for(OpportunityContactRole iterating_oppConRole : [SELECT o.Role, 
                                                                      o.OpportunityId, 
                                                                      o.IsPrimary, 
                                                                      o.Id, 
                                                                      o.ContactId,
                                                                      o.Contact.Marketing_Prospect_Level__c
                                                              FROM OpportunityContactRole o where o.OpportunityId =: opp.id])
                                                              {
                Contact tempContact = new Contact(id=iterating_oppConRole.ContactId, Marketing_Prospect_Level__c = 'Customer');
                               
                listToUpdate.add(tempContact);
               
           }
        }

        if(!listToUpdate.isEmpty())
            update listToUpdate;
}

Hi All,

I have two queries find it as follows:

String partid;
String proId;
id ProcessId = ApexPages.currentPage().getParameters().get('id');
proId = [select id,part__c,part_id__c from process_sheet__c where id=:ProcessId].Id;
partid = [select id,part__c,part_id__c from process_sheet__c where id=:ProcessId].part_id__c ;
att=[Select a.Id,a.ContentType,a.ParentId,a.Parent.Type,a.Parent.Name,a.BodyLength From Attachment a where  a.parent.Id=:partid ];
attch = [Select a.Id,a.ContentType,a.ParentId,a.Parent.Type,a.Parent.Name,a.BodyLength From Attachment a where  a.parent.Id=:proId ];
Now I need a result where parent.Id matches with both proId and partid. Please help me!!!

Thanks in advance 


    

when Account is set as inctive(picklist) , all underlying Contacts should automatically be marked as incative(picklist) and the Expiredate on the Accountt  should be blank.
Hi All.
I'm now trying to make method that is callable from outside of Salesforce.

The scenario is :
1. There is our website and it has customer's info.
2. Everytime, customer's info is changed, website call Salesforce's method.
3. This method update salesforce record details.

How can I make this kind of method?
I saw 'Webservice' concept on Salesforce Developer Guide, However, there is no sample code based on scenario.
Hi all,

I am dealing with this question about how to implement the third part of the requirement:

1. If the following conditions are met, Type will be A

Category=Best AND No. of hotels > 20
OR
Category = Good AND Target Segment = Four stars
OR
Category = Medium AND Target Segment = Three stars

This is not difficult with a workflow or process builder.

2. If the following conditions are met, Type will be B:

Category=Best AND No. of hotels > 50
OR
Category = Good AND Target Segment = Two stars
OR
Category = Medium AND Target Segment = One star

Also already implemented with the process builder

3. If none of the conditions above apply, then Type is C

I see this part is difficult, because you have to find the intersection in all conditions or a combination of them in order to update the field Type to C.
The field Type is a picklist with the values A,B and C. When you see on the Account Layout you will also see the value "None" in the picklist.

I am not sure about how to be implement best the third part. Any suggestions?
Hi Guys,

I'm trying to build a Visualforce page on the opportunity record that allows users to update a few fields on the parent account. I have built the visualforce page, but can't get the newly input values to save back to the account. I'm fairly sure that Opportunity should be the standard controller and I'll need an extension. That's the part I'm having some trouble on.

Can someone point me in the right direction on how I'd accomplish this?

Thanks,
Nick
Hello Everybody,
I have a question about Bulkification in Flows.
I do not understand how exacty bulkification works as explained in this article: https://help.salesforce.com/articleView?id=vpm_admin_bulkification.htm&type=5

I created a little test:
1) I have a flow called CaseFlow 
User-added image
The flow has 1 input (caseId).
In the first block I query for the case with Id=caseId.
In the second block I insert a child case of the retrieved one.
2) I call the flow 400 times with the following code:
        List<Case> cases = Database.query('Select id from case limit 400');
        for(case c : cases){
            Map<String,Object> inputs = new map<String,Object>{'caseId' => c.Id};
            Flow.Interview.createInterview('CaseFlow', inputs).start();  
        }    

How many DML am I performing with this code?

In the log (In the debug level, set Workflow to Finer) I have something like:

11:05:54.705 (38705612167)|FLOW_BULK_ELEMENT_LIMIT_USAGE|1 DML statements, total 400 out of 150
11:05:54.705 (38705630521)|FLOW_BULK_ELEMENT_LIMIT_USAGE|1 DML rows, total 400 out of 10000
11:05:54.705 (38705704180)|FLOW_BULK_ELEMENT_END|FlowRecordCreate|CreateChild|1|43

I do not understand if the execution of the flow interviews count as separated (and I am executing 400 DML out of 150) or they are bulkified and I am executing a fewer number of DMLs (in this case, which is the batch size)???
I am successfully creating the 400 child cases so, apparently, I'm executing 400 DMLs.....

Thank you in advance
Marco
 
Hi all,
Here is my scenario. I need to give access to the users to children records B if they have access to the parent record A. A and B are in lookup relation. and the owner of A is not this user. Its an admin user. Does anyone have any code sample or starting point I can refer to(other than documentation)? I know it will be a trigger but the problem is the child record won't even exist when they have access to the parent record. The child records are created later,So  I can give access to child record on creation of child records but I am trying to figure out what happens when the user looses access to parent record, they shouldnt see child records either. 
Any help is highly appreciated.

Thank you
Hi there,

I just thought I'll write the results of my journey through the Salesforce APEX REST world. This is not a question, rather a documentation. Please note that I'm more of a newbie rather than an experienced programmer. I'll try to be precise but sometimes I might simply don't know better. In the end it did work for me - after several hours of looking, testing and reading.
What do I want to do?
The primary intention is to offer a form on my web server (NOT Salesforce) for people to register. In our case we already have Accounts and Contacts in our Salesforce system and we want to ask (some) of the contacts to go to our web-site and apply for the restriceted area. They would be supplying their email address, their account number and a password.
Later - after their request has been approved - they gain access to the web server's restricted site (again - NOT Salesforce) by checking the Salesforce data.
What was my first thought?
Easy, I thought. Create some Javascript. The customer loads the JS into his browser. Upon the button pressed event it takes the data from the form and does post it against a REST endpoint at Salesforce. There I would have a REST service - simply a very basic APEX class with some special "comments" - and this class would be doing the thing.
What I did forget...
was that stuff with the security.
First trap was the so-called CORS stuff (Cross-Origin Resource Sharing). The customer's browser is loading code from my web server. And the JS code loaded from this server, running on the customer's client, would be calling something on a different domain - Salesforce. So browsers do not allow this. Unless - well - unless the second server allows it --> you have to whitelist the web server.
I tried this - but it did not work. Basically the message is: you are not allowed to call an APEX REST service if you didn't authenticate yourself. So - how would we be doing this?
Use OAUTH...
Salesforce offers several so-called flows to authenticate a user. It is really worth spending a few minutes to read the help here - https://help.salesforce.com/articleView?id=remoteaccess_authenticate.htm&type=5 . The thing is that - at least to the extend I understood the documentation - you either prompt the user for a SALESFORCE UserId and Password throught the standard login screen (which isn't really nice, and which requires every user to have corresponding SALESFORCE license), or you do use some kind of pre-shared secret (my understanding is based upon docs like this: https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/extend_code_cors.htm where it says at the bootom: „CORS does not support requests for unauthenticated resources, including OAuth endpoints. You must pass an OAuth token with requests that require it.“)
I decided to go with the so-called Java Web Token JWT. Well - nice - but then my Javascript would have the pre-shared secret somewhere on the browser. And if it's on the browser it's no secret anymore.... So I did
Get rid of CORS
and decided to implement the connectivity to Salesforce not with Javascript in the browser on the customer's client but using PHP on web server.
The JWT scenario works like this:
- you set up a so-called "Connected app" in Salesforce (Set-up -> Build --> Create --> Apps
- I did specify to use OAuth
- the OAuth policy included:
* Admin approved users are pre-authorized
* Scope includes "Perform requests on your behalf at any time" and "Access and manage your data"
* a digital certificate - I created a selfsigned certificate using openssl (openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365) - I did upload the cert.pem to Salesforce - and the key.pem on my webserver - surely not into the webroot - you know – this file should be kept REALLY confidentially...
- I then did create a permission set to include the connected app and assigned the permission set to a user (AFAIK the APEX REST class to do the work for the service runs at system level - so who-ever this user is - he/she can do a LOT...
So now - what happens?
The PHP code on the server creates a request. It addresses a well-know endpoint and fills in some data. It signs the data with the private key that we did generate earlier. Then it calls the endpoint. Salesforce checks the signature using the certificate, finds the connected app based upon the data in the request and provides a token - a "newly generated password" back to the PHP code.
The PHP code uses this token to authenticate the request that it sends to the Salesforce APEX REST endpoint.
The code
Let me give you some example.
The HTML file on the web server
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>Integration to Salesforce - Test</title> 
</head>
<body>
<!-- Form -->
<form name="applicant" id="applicant" autocomplete="off">
<p>
<label>Email</label><input type="text" id="email" size="64" autofocus>
</p>
<p>
<label>Ext.Account No.</label><input type="text" id="kdnr" size="64">
</p>
<p>
<label>Password</label><input type="password" id="password" size="64">
</p>
<p><button class="btn btn-success" id="btnSubmit" type="button" onclick="btnSubmitOnClick()">Submit</button></p>


<p><span id="insertresult"></span></p>
</form>
<script type="text/javascript" src="md5.min.js"></script>

<script type="text/javascript" src="testsf.js"></script>

</body>
</html>
The testsf.js Javascript on the webserver (md5.min.js is a tool library that also resides on the server - get it in the internet..)
function btnSubmitOnClick() {
	var email = document.getElementById( "email").value;
	var kdnr = document.getElementById( "kdnr").value;
// we won't be storing the password anywhere in clear text - use the md5 coded value - and yes I know - this is NOT secure - but this is a demonstration only
	var password = md5( document.getElementById( "password").value);

// and yes - we should be doing some checks here to make sure we do not get malformed data --> https://stackoverflow.com/questions/295566/sanitize-rewrite-html-on-the-client-side/430240#430240
    
	var xhr;
	var data = 'email=' + email + '&kdnr=' + kdnr + '&password=' + password;

	xhr = new XMLHttpRequest();
	xhr.open( "POST", "jwtbearer.php", true);
	xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded");
	xhr.addEventListener( "load", display_insert);
	xhr.send( data);

	function display_insert() {
		document.getElementById( "insertresult").innerHTML = xhr.responseText;
	}
}
Now for the PHP code in jwtbearer.php on the web server:
<?php
// ini_set('display_errors', 'On');
// error_reporting(E_ALL | E_STRICT);
$email = $_POST ['email'];
$kdnr = $_POST ['kdnr'];
$password = $_POST ['password'];

// documentation in https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm&type=5
// code based upon https://developer.salesforce.com/forums/?id=906F00000005HTiIAM

// the following values ought to be defined via $_SERVER ['variables']
// this is the client ID in the connected app
define('CONSUMER_KEY', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXXXXXXXXXXXXX');
// and this is the secret of the connected app - actually we do not use it
define('CONSUMER_SECRET', '99999999999999');
// the subject is a name of a user. Make sure that
// - the connected application is set to "Admin approved users are pre-authorized"
// - there exists a permission set that has the right to access the connected application
// - this user is assigned to the permission set
// - the connected application has at least the following two scopes: "Access and manage your data (api)", "Perform requests on your behalf at any time (refresh_token, offline_access)"
// - the connected app has attached the certificate for the private key further down
define('SUBJECT', 'user@domain.test');

define('LOGIN_BASE_URL', 'https://test.salesforce.com');

// First step: get an authorization token from Salesforce that allows us to later call the APEX REST service
// we do this using the so-called JWT bearer flow --> https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm&type=5

// this is where we'll getting the token from
$token_url = LOGIN_BASE_URL.'/services/oauth2/token';

// JSon Header
$h = array(
	"alg" => "RS256"	
);

$jsonH = json_encode(($h));	

// ATTENTION: it has to be base64URL encoded!!!
$header = rtrim(strtr(base64_encode($jsonH), '+/', '-_'), '=');

// Create JSon Claim/Payload
$c = array(
	"iss" => CONSUMER_KEY, 
	"sub" => SUBJECT, 
	"aud" => LOGIN_BASE_URL, 
	"exp" => strval(time() + (5 * 60))
);

$jsonC = (json_encode($c));	

$payload = rtrim(strtr(base64_encode($jsonC), '+/', '-_'), '='); 

$jwtToBeSigned = $header.'.'.$payload;

// This is where openssl_sign will put the signature
$signature = "";

// get the private key from a file (and supply the password for this key - ought to be stored in a S_SERVER variable as well
$pkeyid = openssl_pkey_get_private("file:///etc/php5/apache2/mykey.pem", "9999999999");

// Sign the header and payload
openssl_sign($jwtToBeSigned, $signature, $pkeyid, OPENSSL_ALGO_SHA256);
openssl_free_key($pkeyid);

// Base64URL encode the signature
$secret = rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');

// construct the "assertion" that Salesforce will use to test
$assertion = $header.'.'.$payload.'.'.$secret;

// and from this construct the array of fields to post
$post_fields = array(
	'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
	'assertion' => $assertion
);

// now prepare the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Make the API call, and then extract the information from the response
$token_request_body = curl_exec($ch);
if ( $token_request_body === FALSE) {
    echo "<pre>";        
    echo "Error from curl_exec during JWT bearer token request: " . curl_error( $ch);
    echo "</pre>";   
    return;
}

// so now we got the token - let's extract the relevant info
$token_request_array = json_decode( $token_request_body, true);

$theToken = $token_request_array[ 'access_token'];
$theInstance = $token_request_array[ 'instance_url'];

curl_close($ch);

// now start the real Service call
// salesforce will tell us where EXACTLY we have to ring...
$token_url = $theInstance . '/services/apexrest/hpp/v1';

// remember: the APEX class in salesforce defines the path; the methods in this class correspond to the various types like POSt, GET....
// Content-type has to be correct
$headers = array( 
            "POST " . "/services/apexrest/test/v1". " HTTP/1.1",
            "Content-type: application/json", 
            "Accept: */*", 
            "Cache-Control: no-cache", 
            "Pragma: no-cache",
            "Authorization: Bearer " . $theToken
        ); 

// these are the fields we want to submit to the APEX REST service
$post_fields = array(
	'email' => $email,
	'kdnr' => $kdnr,
	'password' => $password
);


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

$service_request_body = curl_exec($ch) ;
   
if ( $service_request_body === FALSE) {
    echo "<pre>";        
    echo "Error from curl_exec during APEX REST call: " . curl_error( $ch);
    echo "</pre>";    
    return;
}
    
curl_close($ch);
echo "Success!";
Now to Salesforce. I addedd two checkbox fields to the Contact standard object - Applied_for_web_access__c and Granted_web_access__c. I also added a text(32) field to store the hashed password: Web_Hash__c.
Here is the sample code for the APEX class serving as the REST service:
@RestResource(urlMapping='/test/*')
global with sharing class testRestInterface {
    @HttpPost
    global static String createApplicationForAccess( String email, String kdnr, String password) {
        Contact[] cList = [Select Id From Contact Where Email = :email and Account.ExtAccountNo__c = :kdnr];
        if ( !cList.isEmpty()) {
            Contact aContact = cList[0];
            aContact.Applied_for_web_access__c = true;
            aContact.Web_Hash__c = password;
            update aContact;
        } else {
/* here I decided to create a lead... */
            Lead aLead = new Lead( Lastname='Unknown web access requestor', Company='unkonwn company', Applied_for_web_access__c = true, Web_Hash__c = password);
            insert aLead;
        }
        return 'SUCCESS';
    }

}
Later in the project I did use Email Actions with Email Templates that get send upon Changes to the Checkboxes caught in Process Builder - but that's another story....

Lessons learned:
- no APEX REST access without authentication
- authentication done on the web server - not on the client
- base64URL encoded values in the JWT bearer section
- pre-authorized users, with permission set

So - hopefully I did not state something totally wrong here and hopefully too this will help somebody someday.





 
Salesforce.com could not email the report to any of the specified recipients. Check that recipients are specified and that they have the appropriate permissions to view the report.

If you get this ^error:

Make sure you also check:
Setup > Customize > Reports & Dashboards > Email Notifications > Allow Reports and Dashboards to Be Sent to Portal Users

Posting this here since it took me a long time to find this checkbox.
 
We have come up with an interesting case management solution using the templates and algorithms of Prediction IO

Step 1: Using email-to-case feature a customer will mail his/her issue to a routing email-address and a Case will get created with Email Subject as Case Subject and Email body as Case Description
 
Step 2: As soon as case is created, Prediction IO will predict the most relevant article from the set of Article Management for the case. After the article is predicted, it will get attached to the Created Case and the status of Case will move to ‘On Hold’. We have trained a model in PredictionIO using the 'text classification' template and as a input to that template we are sending the Case Subject of Closed cases and Article Title associated with those closed cases based on whcih for any new case the most relevant article is predicted.
 
Step 3: After the article is attached to case, an email will be sent to the Case Creator based on predefined SFDC template with the solution article attached as pdf file with the mail. User will be asked whether the solution case article is relevant for your problem or not. And if yes, the case can be closed.

Step 4: If the customer replies that the article seems to be relevant and case can be closed, then the case will get automatically closed.

The best part of this is that it is completely automated, customer just have to mail theproblem