• Vamsi
  • SMARTIE
  • 909 Points
  • Member since 2015


  • Chatter
    Feed
  • 23
    Best Answers
  • 4
    Likes Received
  • 2
    Likes Given
  • 33
    Questions
  • 277
    Replies
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,
I have Contract object, and Payments as the related onject on it. In Payment, i have the amount and the paid dates. New records keep getting on in this once a payment been made.
I want that in contract , i have a field " latest paid" where only the latest paid amount will get reflected. May i know how to do this.
I tried creating a PB in Payment object, with criteria as when status is Paid, But in action i am not able to know how to goahead with the formula as i am not comparing with any  date fields, can anybody suggest plz.
Hello,

I have created two picklist, one controlling and another dependent.

I would like to deliver from one sandbox to other sandbox..how can i transfer them with guarding the dependencies..

Thanks for suggestion !
Hi,
I am having trouble with the Trailhead project Build a Community with Knowledge and Chat, specfically the Enable and Configure Lightning Knowledge. The badge says to create a Knowledge Record Type of 'FAQ'. I do not see anywhere, where you can create a Record Type for the Knowledge Object.

There are Knowledge Article types, which have the fields that are displayed in the example. But there is no way to create a Record Type for them.

I can create Record Types for the Linked Articles, which I did, but when I verify this step, the error message comes back and says:
Challenge Not yet complete... here's what's wrong: 
Could not find a Knowledge recordtype named 'FAQ'.

Am I doing this correctly or are there issues with this Trail due to Summer '17? It's a brand new badge, so it must be me.

Thanks!
Employee object is in lookup relation with account,When we will create Event Record with Condition (Event Status = Closed) and once we click on save ,it should create Employee record automatically.What will be the trigger for it?
Program_Member_Stage_MVN__c stagesequence = [select Stage_Number__c from Program_Member_Stage_MVN__c where id=:PId];

how to i get Stage_Number__c from the above list to assign it to where clause in the below soql query ==here(Stage_Number__c<????)

        List<Program_Member_Stage_MVN__c> Pstages=new List<Program_Member_Stage_MVN__c>([select id,Stage_Number__c,Parent_Stage__c,Status_MVN__c,Parent_Program_Member_Stage_MVN__c from Program_Member_Stage_MVN__c where Program_Member_MVN__c=:Pm.id and Parent_Stage__c='Parent_Stage_MVN' and Parent_Program_Member_Stage_MVN__c!=:PId and Stage_Number__c<????]);
 
Can someone help me figure out my syntax issues? 
Looking to have the formula evaluate if the created date is greater then the date, run the first calucaltion, if the date was prior, run the second calcualtion.

IF(DATEVALUE(CreatedDate)>(6/20/2017), 
(Total_Material_Cost__c*(1+Proposal__r.Opportunity__r.Account.Mark_upproject__c)),
((Total_Material_Cost__c * 1.7241 ) * 1.07526))
Trying to write a validation rule where: 

Picklist value Status of Completed is chosen on RecordTypeID 012d0000001lA4R or 012d0000002MB5S or 012d0000003NC6D or 012d0000004OD7E, the AcitivityDate must not be NULL. 

Here is my attempt, but have not succeded: 
 
AND
(ISPICKVAL(Status,"Completed"),
 AND(RecordTypeId,"012d0000001lA4R","012d000003NC6D","0120000002MB5S"),
ISBLANK(ActivityDate)
)



 
  • August 20, 2016
  • Like
  • 0
I have one custom object that contains two fields -

1- Age  ,  2- status

I want if the age of the person is less that or equal to 17 then the status should be YES automatically otherwise status Field value will be NO.

PLEASE SUGGEST ME WORFLOW OR WHATEVER ... I NEED TO SHOW THE TASK TO CLIENT ASAP. PLEASE
In account object rating field ........wen user are select the rating picklist as HOT  expect that rest of options{warm,cold} should be trough an error by using  validation rule ???
how to write a validation rule of this ?
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 All,
When I hover over the account on the case record the pop-up keeps loading in my organization...

Any suggestions would be of great help...!!!!

 
  • May 31, 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

I'm new to SF Developement. I'm trying to get Account Name in the Opportunity for some scenario.
I'm getting Null value when I'm trying this code
 

for(Opportunity opp:trigger.New){
                if(opp.Quote_Category__c != 'Choose One'){
                    oppJobList.add(opp.AccountId.Name);
                }
            }
 

Help me on this. Thank you.

  • January 17, 2018
  • Like
  • 0
Hello Friends,

I have a 3 Lists of Account 'acclist1' , 'acclist2', & 'acclist3'
'acclist1' has 3 records.
'acclist2' has 2 records which are also present in 'acclist1'.

and I have a third list 'acclist3' in which i want to add that record which is not present in 'acclist2'.
So How can i acheive this scenario in Apex Code?

Any Example or Code assitance will be greatly appreciated.
I have a visualforce page with the following code:
<apex:page showHeader="false" sidebar="false" controller="cc_AppChecklist_List" standardStylesheets="false" html-lang="en-US">  
    <c:cc_App_Header />
    <c:cc_App_TopNav activeSection="Personal" />
    <div class="gridlock gridlock-16 appPage">
        <div class="page page_container clearfix"> 
            <div class="row page_row">
                <div class="content page_content max-push-1 max-14 desktop-push-1 desktop-14 tablet-full mobile-full margined">
                    
                    <div class="row page_row content_block background">
                        <div class="desktop-12 tablet-6 mobile-6 min-full left" >
                            <h1 style="margin: 0;">My Application Checklist Items</h1>
                        </div>
                        
                        <apex:pageBlock title=""> 
                            <apex:pageBlockTable value="{!Records}" var="Record" style="width:100%"> 
                                <apex:column style="width:35%"> 
                                    <apex:facet name="header">Checklist ID</apex:facet> 
                                    <apex:outputText value="{!Record.Id}"/> 
                                </apex:column> 
                                <apex:column style="width:35%"> 
                                    <apex:facet name="header">Checklist Name</apex:facet> 
                                    <apex:outputText value="{!Record.CC_Document_Name__c}"/> 
                                </apex:column> 
                                <apex:column style="width:10%"> 
                                    <apex:facet name="header">Status</apex:facet> 
                                    <apex:outputText value="{!Record.CC_Document_Status__c}"/> 
                                </apex:column> 
                                <!-- apex:column > 
                                    <apex:facet name="header">Date Requested</apex:facet> 
                                    <apex:outputText value="{0, date, MMMM d','  yyyy}">
                                        <apex:param value="{!Record.CC_Date_Requested__c}" /> 
                                    </apex:outputText>
                                </apex:column> 
                                <apex:column > 
                                    <apex:facet name="header">Date Due</apex:facet> 
                                    <apex:outputText value="{0, date, MMMM d','  yyyy}">
                                        <apex:param value="{!Record.CC_Due_Date__c}" /> 
                                    </apex:outputText>
                                </apex:column --> 
                                <apex:column style="width:15%"> 
                                    <apex:facet name="header">Date Received</apex:facet> 
                                    <apex:outputText value="{0, date, MMMM d','  yyyy}">
                                        <apex:param value="{!Record.CC_Date_Received__c}" /> 
                                    </apex:outputText>
                                </apex:column>
                                <apex:column style="width:40%"> 
                                    <apex:facet name="header">Action</apex:facet> 
                                    <apex:form >
                                         <apex:inputFile title="file_upload" value="{!file.body}" fileName="{!file.name}" id="file_upload" onchange="return checkFileSize(this);"/>
                                         <apex:commandButton styleClass="btn app-btn-success" value="Upload" action="{!uploadFile}" />
                                    </apex:form> 
                               </apex:column> 
                               
                            </apex:pageBlockTable> 
                        </apex:pageBlock> 
                   </div>
                
                    

                </div>
            </div>
        </div>
    </div>
   
    <!-- <c:App_Footer /> -->
</apex:page>

Control class:
public with sharing class cc_AppChecklist_List{ 

    public List<Application_Checklist__c> Records {get; set;} 
    String AppID = ApexPages.currentPage().getParameters().get('appid');
    
    public cc_AppChecklist_List(){ 
    Records = 
    [SELECT Id, Name, CC_Document_Name__c, CC_Document_Status__c, CC_Date_Received__c,CC_Date_Requested__c, CC_Due_Date__c FROM Application_Checklist__c WHERE Application_CC__c = :AppID];    
    }
    
    // system.debug('-----ChecklistID')
    // Upload Code
    private Id itemId {get; set;}
    public Application_Checklist__c item {get; set;}
    public SObject obj {get; set;} 
    public Attachment file {
        get {
            if(file == null) {
                file = new Attachment(ParentId = itemId);
            }
            return file;
        } 
        set;
    }
    private Boolean isOld {get; set;}

    public PageReference uploadFile() {
        PageReference pr = null;
        try {
            system.debug('-----ChecklistID'+itemId);
            insert file;
            if(isOld) {
                item.CC_Date_Received__c = Date.today();
                update item;
            } else {
                obj.put('CC_Date_Received__c', Date.today());
                obj.put('CC_Document_Status__c','Received');
                update obj;
            }
            pr = Page.cc_App_Status;
        } catch (Exception ex) {
            cc_App_BaseController.addError(Label.Upload_Attachment_Error);
            System.debug(ex.getMessage());
        } finally {
            file = null;
        }
        return pr;
    }
}

What I am trying to do is make the {!Record.Id} value for each row in the visualforce page pass across to the "itemId" value so the upload button will upload to the correct record. The upload function works when I hard code a value but I am having trouble passing the data to the variable when the upload button is selected. The goal of this is to query an application id and display all checklist items on the visualforce page with an upload button for each item. 
Hi 
plz help me in solving this code 
trigger Testordersopp on Order (after insert,after update) {
        // Get all related opportunities from orders
    Set<Id> opportunityIds = new Set<Id>();
   List<Order> orderList = new List<Order>();
    for(Order o : Trigger.new)
    {
        if(o.QuoteId != NULL)
        {
            opportunityIds.add(o.QuoteId);
            orderList.add(o);
        }
    }

    // Query for all opportunities with their related opportunity line items
    //Map<Id,Quote> oppsWithLineItems = new Map<Id,quote>([SELECT Id, (SELECT Description,Id,ListPrice,Name,QuoteId,Product2Id,ProductCode,Quantity,TotalPrice,UnitPrice FROM QuoteLineItems) WHERE Id IN :opportunityIds]);
    Map<Id, Quote> oppsWithLineItems = new Map<Id, Quote>([SELECT Id, (SELECT Description,Id,ListPrice,Name,QuoteId,Product2Id,ProductCode,Quantity,TotalPrice,UnitPrice FROM QuoteLineItems) WHERE Id IN :opportunityIds]);

    if(opportunityIds.size() > 0)
    {
        // Loop through orders
        List<OrderItem> orderItemsForInsert = new List<OrderItem>();
        for(Order o : ordersList)
        {
            // For each order get the related opportunity and line items, loop through the line items and add a new order line item to the order line item list for each matching opportunity line item
            Quote oppWithLineItem = oppsWithLineItems.get(o.QuoteId);
            for(QuoteLineItem oli : oppWithLineItem.QuoteLineItems)
            {
                orderItemsForInsert.add(new OrderItem(AvailableQuantity=Quantity,OrderId=o.Id));
            }
        }
        // If we have order line items, insert data
        if(orderItemsForInsert.size() > 0)
        {
            insert orderItemsForInsert;
        }
    }


}

lokking for your reply
Thanks​
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 have to pass parametet with commandbutton which is outside of table.
this is my vf: 
<apex:form styleClass="myFormStyle " >
  <center>
  <!----------------pageBlock--------------------------------------->
  <apex:pageBlock title="My Bucket"  >
  
  <apex:pageMessages id="msg"> </apex:pageMessages>
  <!-------------first section-display table and take quantity from user----------------->
  <apex:pageblockSection >
  <apex:pageBlockTable value="{!itemInBucket}" var="i">
   <apex:column value="{!i.Product_Name__c}" />
   
    <apex:column value="{!i.price__c}"  />
    
    <apex:column value="{!i.Quantity__c}" headerValue="Available Quantity"/ >
    
    <apex:column headerValue="Required Quantity" >
    <apex:commandButton value="+" action="{!incrementCounter}" reRender="bucket"/>
    <apex:inputText value="{!count}" style="width: 25px !important;" styleClass="qty " id="bucket"/>
    <apex:commandButton value="-" action="{!decrementCounter}" reRender="bucket"/>
    </apex:column>
    
    <apex:Column >
    <apex:commandLink value="Place Order" action="{!placeOrderForSinglePro}" >
    <apex:param name="Pname" value="{!i.Product_Name__c}"/>
    <apex:param name="price" value="{!i.price__c}" />
     <apex:param name="quantity" value="{!i.Quantity__c}" />
    </apex:commandLink>
    </apex:column>
    
    <apex:Column >
    <apex:commandLink value="cancel" action="{!cancelOrder}" rendered="true" >
    </apex:commandLink>
    </apex:column>
    </apex:pageBlockTable> 
    </apex:pageblockSection>
    <!---------------------second section- take address and name from user--------------->
    <apex:pageBlockSection >
    <apex:inputText value="{!n}" label="Name" />
    <apex:inputTextarea title="Address" value="{!a}" label="Address"/>
    </apex:pageBlockSection>
   
   <!---------------commandButton is in pageBlock------------------------------->
   <apex:commandButton value="Place Order for All Products" action="{!placeOrderForAllPro}"/>
  </apex:pageBlock>
  </center>
  
  <apex:commandLink value="View Order" action="{!openOrderPage}"/>
  <apex:commandLink value="Previous Page" style="float:right;" action="{!redirect}"/>
  </apex:form>
</apex:page>

here i am taking quantity name and address from user and storing all that into Order__C object. now my inputFileds are in diffrent pageBlockSection and my command button is in pageBlock. so how can i insert  that  to Order__c when i click on commandButton.
 list<Account> ACC = [select id,  (select ID, Name from Contacts) from Account];

From the above statement how to retrive and assign contact name to a Apex variable?
 
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
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.

Hello Friends!

I am in need of some help. I have been wracking my brains trying to figure out how to create a validation rule that will work for the below scenario.

Desired steps and outcome:

1. Enters new oppty & saves.
2. Enters products (w pricing) using Products related list.
3. Amount field (on Oppty in $) auto-calculated based on products and pricing entered.
4. Contract Terms entered into related object called Contract Terms.
5. Contract Terms Total field (Rollup Summary on Oppty in $) auto-calculated based on Terms entered.
6. If Contract Terms Total does not equal Amount, validation rule should trigger.

Sounds like it should be easy, but it is not because the error would continue to fire every time I add another Term. Unless the Term equaled the amount on the Contract Term entry.

NOTE: There can be multiple Contract Terms that should all roll up into the Contract Terms Total field.

I hope this makes sense? Please let me know if you can help.

Thanks!


Shannon

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

 
trigger EST on Development_Item__c (before insert, before update, after update) {

map<ID,string> releasemap=new map<ID,string>();
for( Development_Item__c di:Trigger.new)
    {
        if(trigger.isbefore)
        {
            if(trigger.isinsert)
            {
                if(di.Sign_off_Date__c!=null)    
                {    
                    di.Status__c='Ready for PROD';
                }
                if(di.Business_Ananlyst__c==null)
                {
                    di.adderror('Pls select BA');
                }
            }
            else if(trigger.isupdate)
            {
                if(di.Sign_off_Date__c==null && trigger.isbefore )
                {
                    di.Status__c='In UAT';
                }   
            }
            di.Estimated_QA_hrs__c=0.4*di.Estimated_QA_hrs__c;
    }
    if(trigger.isafter)
        {
            system.debug(' debug is ' + di.name );
            releasemap.put(di.Release__c,di.Name);
        } 
    }
        list<release__c> releaselist=new list<release__c>();
        releaselist=[select id,name,Latest_Updated_Dev_Item__c from release__c where id in: releasemap.keyset() ];
        system.debug('release is' + releaselist);
        for(release__c DE:releaselist)
        {
            DE.Latest_Updated_Dev_Item__c=releasemap.get(DE.ID);
        } 
        update releaselist;
}


THIS IS MY ORIGINAL CODE.
1. Update your trigger logic to use Database.update and set allornone to false.
2. Iterate through the save result, collect all the errors and store the error into the Error Log object. Collect release record id that has the error and the error message. 
3.User-added imageInsert the errors into error log object
Being an administrator with no developer experience is quite the challenge.  Would anyone be so kind to help me with this?
public class DmlExample{
    public account acc{get;set;}
    public DmlExample(){
        acc=new account();
    }
    public pagereference DmlExam(){
        integer c=[select count() from account where name=:acc.Name];
        if(c>0){
            apexpages.Message msg=new apexpages.Message(apexpages.Severity.ERROR,'duplicate is trying to insert');
            apexpages.addmessage(msg);
            return null;
        }
        else{
         	insert acc;
        	pagereference p=new pagereference('/'+acc.id);
        	return p;
        }
    }
    public void cancelling(){
        acc=null;
    }
}

 
  • October 21, 2017
  • Like
  • 0
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
My requirement was to look for all the records deleted by a particular user spanning mulitple objects and delete those records from recycle bin. I tried to come up with this code and it worked, but when there is too much of data it hits Apex governor limit. I am new to coding and don't know how to circumvent that. I initially tried writing my query in start method but I was not able to query multiple objects there using for loop.

I am using custom setting (EmptyRecycleBinBatch) to hold object API names.. Any suggestion is appreciated!

global class EmptyRecycleBinBatch implements Database.Batchable<sObject>, Schedulable {

    global Database.QueryLocator start(Database.BatchableContext BC) {
        String Query='Select Id, ObjectAPIName__c From EmptyRecycleBinBatch__c';
         return database.getquerylocator(Query);
   }

    global void execute(Database.BatchableContext BC,List<EmptyRecycleBinBatch__c> sObjRecords) {
        System.debug('in execute method');
        User userid= [Select Id, Name from User where User.Name= ' test user' And isActive= true Limit 1];
        String Query;
        
        for(EmptyRecycleBinBatch__c sOb: sObjRecords){ 
        
        SYstem.debug('object name :'+sOb.ObjectAPIName__c); 
          Query = 'SELECT ID from '+sOb.ObjectAPIName__c+' where isDeleted = true AND CreatedById = \''+userid.Id+'\' all rows';
        system.debug('query '+Query );            
        List<Sobject> sObjtocreate = new List<Sobject>();    
        sObjtocreate = Database.query(Query);
            System.debug('list of items to delete'+sObjtocreate);
      if(sObjtocreate != null && !sObjtocreate.isEmpty()) { 
          
     try{
         //system.debug(' deleting :'+sObjtocreate);
           Database.emptyRecycleBin(sObjtocreate); 
            if(test.isRunningTest())
            {
                 throw new applicationException('Exception');
            }
        }
        catch(Exception e){
            System.debug('ERROR on Delete:' + e);
        }
       }
      }
     }     
    public class applicationException extends Exception 
    {
    
    } 
    global void finish(Database.BatchableContext BC) {
        
    }
    global void execute(SchedulableContext sc) {
        database.executebatch(new EmptyRecycleBinBatch());
    }
}
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