• Manojjena
  • ALL STAR
  • 6645 Points
  • Member since 2012
  • Sr. Enterprise Application Engineer
  • GE Healthcare

  • Chatter
    Feed
  • 197
    Best Answers
  • 1
    Likes Received
  • 6
    Likes Given
  • 25
    Questions
  • 1492
    Replies
Can any one have idea how to write a formula for two fields which were of picklist type and stage is other than initiated
  • March 10, 2020
  • Like
  • 0
i want to assign 100 different profile with same permission set through code in salesforce 
  • December 18, 2019
  • Like
  • 0
Hi,
I need help to create test class for a TriggerHandler Class.
I will show you my code.
Class Trigger Handler:
public class ContactTriggerHandler {
    
    Public static void newTasks_VisitPlanner(List<Contact> newContacts, Map<Id,Contact> mapOldContacts) {
        
        
        List<Task> NewTasks = new List<Task>();
        for (Contact con: newContacts){
            If(!checkRecursive.SetOfIDs.contains(con.Id)){
                Contact oldContact = mapOldContacts.get(con.Id);
                if(con.Frequency__c != oldContact.Frequency__c){
                    
                    if (con.Frequency__c == '3 Months'){
                        for(Integer i = 1; i < 5; i++){
                            Task newTask = new Task(
                                WhoId = con.Id,
                                WhatId = con.AccountId,
                                OwnerId = con.Assigned_to__c,
                                Subject = 'Rappel : Visite périodique',
                                ActivityDate = Date.today().addMonths(i*3),
                                Priority = 'Normal',
                                Status = 'Not Started',
                                Created_from_Visit_planner__c = true
                            );
                            NewTasks.add(newTask);
                        }
                    }
                    
                    if (con.Frequency__c == '6 Months'){
                        for(Integer i = 1; i < 3; i++){
                            Task newTask = new Task(
                                WhoId = con.Id,
                                WhatId = con.AccountId,
                                OwnerId = con.Assigned_to__c,
                                Subject = 'Rappel : Visite périodique',
                                ActivityDate = Date.today().addMonths(i*6),
                                Priority = 'Normal',
                                Status = 'Not Started',
                                Created_from_Visit_planner__c = true
                            );
                            NewTasks.add(newTask);
                        }
                    }
                }
                checkRecursive.SetOfIDs.add(con.Id);
            }
        }
        
        
        if(NewTasks != null && NewTasks.size()>0){
            insert NewTasks;
        }    
    }
}

Trigger:
trigger NewTasks_VisitPlanner_Trigger on Contact (after update) {
    
    ContactTriggerHandler.newTasks_VisitPlanner(Trigger.new, Trigger.oldMap);
}

Test Class:
@isTest
private class Test_NewTasksVisit_Trigger {
    
    @isTest
    public static void Test_newsTask3Months(){
        Account acc = new Account(Name = 'OPALE', Type = 'Public sector', Main_Role__c = 'Contracting authority' );
        insert acc;
        
        Contact con_A = new Contact(FirstName='Albert',LastName='Roche', AccountId = acc.id);
        insert con_A;

        con_A.Frequency__c='3 Months';
        con_A.Assigned_to__c=con_A.Name;
        update con_A;
        
        con_A.Frequency__c='6 Months';
        con_A.Assigned_to__c=con_A.Name;
        update con_A;
    }
    
    @isTest
    public static void Test_newsTask6Months(){
        Account acc = new Account(Name = 'SOGEA', Type = 'Private sector', Main_Role__c = 'Contracting authority support' );
        insert acc;
        
        Contact con_B = new Contact(FirstName='Jean',LastName='Rabi', AccountId = acc.id);
        insert con_B;
        
        con_B.Frequency__c='6 Months';
        con_B.Assigned_to__c=con_B.Name;
        update con_B;
        
        con_B.Frequency__c='3 Months';
        con_B.Assigned_to__c=con_B.Name;
        update con_B;
    }
}

​​​​​​​​​​​​​​
i Have created the handler for that in the text filed  i want the name but populated the id  following is my code

public class Populatedlookup {


    Public void updateField(List<Lead> leadList){
        /*
        for(lead l : leadList){
            leadId.add(l.Id);
            System.debug('leadid'+ leadId.add(l.Id));
        }
        lead leadOne = [select id, name, Channel_Partner__c from lead where Id IN: leadId];
        if(leadOne.Channel_Partner__c!=null){
        Distributor__c dis = [select id, name from Distributor__c where Id=:leadOne.Channel_Partner__c];
        DistributorName = dis.Name;
*/
        for(Lead leadObj:LeadList){
            if(leadObj.Channel_Partner__c!=null){
                leadObj.Channel_Partner_Text__c=leadObj.Channel_Partner__r.Name;
            }
            else{
                leadObj.Channel_Partner_Text__c='';
            }
            
        }
      
    }
}
Hi Friends,

Please help on below Trigger. I am trying to insert Quote when the attachment is added to Opporunity and the file name contains PDF.

trigger oppattachment on Attachment (after insert, after update) {
    
    Set <Id> oppIds = new Set <Id>();    
    for(Attachment attach : Trigger.new) {
        if(attach.ParentId.getSobjectType() == Opportunity.SobjectType) {
            if(string.valueOf(attach.Name).contains('.pdf')) {
                oppIds.add(attach.ParentId);
            }
        }
    }
    List <Quote> quoteList = [SELECT id, name, opportunityid FROM Quote WHERE Id IN: oppIds];
    for(Attachment attach : Trigger.new) {
        if(quoteList !=null && quoteList.size()>0){
            for(quote q : quotelist){    
                q.name = attach.name;       
            }
            insert quoteList;
        }
    }                
}

Thanks.
I have an Application object an in the Application object I have list with custom CC App records.

When CC App record is edit is executed the beforeUpdate trigger.

I'm using an algorith to calculate average responce time of the record and the calculated value is stored in a custom field of type number.

When I try to save the value

I write CCApp1.averageHours = value; //for instance value = 8.00

For some reason the value is not saved in the field of the record.

I've tried with trigger.new as explained in the following:
http://https://salesforce.stackexchange.com/questions/198273/trigger-not-updating-a-record-field

The value is saved into the field of the current CCApp record.

What I need to achieve is to store and save the value in ALL CCApp records from the CCApp recod list in the Application.

Please advise how this can be achieved?
Hi

we need all the fields (standard&Custom) names,type,length of opportunity into exel

How can we do this?

 
Hi,

Can someone help provide the testclasses for the below wrapper class?

archestain@boom.com

Class 1:


    public with sharing Class OwnerWrapper{
    public Integer Index {get;set;}
    public List<String> tcOwner {get;set;}

        public OwnerWrapper(){
        
        }
}

Class 2:


        public with sharing class AddressWrapper {
    
        public Integer Index {get;set;}
        public List<String> Addressed {get;set;}
        
     
        publicAddressWrapper(){

        }
        
    
    }
I have a reuiqrement i want to have a field in parent record and get the sum of a field from all child record. this is lookup relationship record. how to do in a easy way , please suggest me.
Hi ,
I want to create a Task counter in Opp, the counter should increase/count only if the subject is " Opp  follow-up" ( not for other subjects),  May i know how to do it ?
I was trying PB created on Task object, but couldnt able to put action that increase the " Opp Task Conter " field.
I am trying to write a trigger on Opp, If anyone can suggest , modify my below trigger which is not working to get a proper view, i am new to apex.
 
trigger TaskCount on Opportunity (before insert) {
if(newTaskList[0].WhatId != null && ((String)newTaskList[0].WhatId).substring(0,3)=='006')
        {
            opp = [SELECT Id,Name,OwnerId,Owner.Email,(SELECT Id FROM Tasks WHERE Status != 'Completed' and Subject='Opportunity follow-up) FROM Opportunity WHERE Id = :newTaskList[0].WhatId LIMIT 1];
        }
}



Any suggestions plz. Thnx
Hello
I have two custom objects , fan__c    and   subscription__c

Fan object has fields (ID, email__c)

subscription object has fields(ID,fan_ID__c,mailing_list_name)

subscription object has a lookup to fan object as  : Fan_ID__cLookup(Fan)

pls help in framing the subscription query from child to parent where child is subscription object and parent is fan object.

I want to frame a query on subscription object that will fetch the related email of fan object

pls help me out
thanks
JohnD
 
Hi,
Can anyone offer some assistance with this scenario please.
I have a trigger that should be creating one of each custom object(Project_sheet__c and Project_checklist__c) when the opportunity is saved.
Both custom objects have Opporutnity look ups. The trigger was sort of working, but unfortunately I was getting multiple records being created.
I do have workflows on the Opportunity that fire when the opportunity is saved, as well as an additional trigger that creates an asset for each OLI.
I thought the issue was as this trigger is an 'Update' as well as an 'Insert', it was causing it to re-fire.
I've attempted to add a conditional statement that if there is already a Project checklist or Project sheet associated with the Opportunity then it shouldn't create an additional record.
Unfortunately it's not working at all now.
I've highlighted the additional conditional statement in bold that appears to have stopped the trigger working at all.
Any help would be appreciated.

Current trigger:

trigger InsertProjectDocuments on Opportunity (after insert, after update) {
List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
   
    for(Opportunity opp : Trigger.new) {
        if (opp.IsWon && (opp.Project_sheets_21__r != null) && (opp.project_sheets_21__r != Trigger.oldMap.get(opp.id).Project_sheets_21__r) && (Trigger.oldMap.get(opp.Id).IsWon !=opp.IsWon)) {
            Project_sheet_2__c ps = new Project_sheet_2__c();
            ps.Name = 'Project sheet -' + opp.name;
            ps.PS2_Opportunity__c = opp.id;
            ps.Date_created__c = system.today();  
            ps.Version_Number__c = '1';
            projSheetToInsert.add(ps);            
        }
        if (opp.IsWon && (opp.Project_sheets_2__r != null) && (opp.project_sheets_2__r != Trigger.oldMap.get(opp.id).Project_sheets_2__r) && (Trigger.oldMap.get(opp.Id).IsWon !=opp.IsWon)) {
            Project_checklist__c pc = new Project_checklist__c();
            pc.Name = 'Checklist -' + opp.Name;
            pc.Project_opportunity__c = opp.id;
            projChecklistToInsert.add(pc);
        }
    }
    if(projSheetToInsert.size() >0){
        Database.insert(projSheetToInsert, false);
    }
    if(projChecklistToInsert.size() >0){
    Database.insert(projChecklistToInsert, false);
    }
}
 
hi,
there is an integer list of (1,2,3,4,4). I want to copy this list in another list in such a way that list should not copy the number 4 twice. It should copy in a list not in set. What would be the code ?

thanks
lalit
Hello, 

I have created a field on the Opportunity object called Latest Note. When a user adds a new note to the Opportunitues Notes section I want to copy the Body and insert it to the field "Latest Note". Can a trigger be created on the Note object to handle this?

Thanks for all your help,
Ricky 
 
Hi All,

I m trying to delete a content version record from my java code using REST api using HTTPDelete :

HttpDelete delete = new HttpDelete(baseUri+"/sobjects/ContentVersion/"+v);
where delete.getURI() = https:// xxx.my.salesforce.com/services/data/v35.0/sobjects/ContentVersion/06824000000aAqlAAE

HttpResponse  response = htttpCient.execute(delete);

but i get a status 401 on delete. This same URI works if if i delete a Account object without an issue. Can anyone please help ? I would really appriciate it!

Thank you!
I'm having trouble getting my case before insert trigger to fire when a new case is created via email to case.

I'm just wondering if that it doesnt fire for some reason when they come in via email to case?
Hi peeps,

I'm creating a trigger to update a custom object when another object is updated, inserted or deleted. The class saves fine and passes the test with 100% code coverage but when I try to update the object in salesforce i get the following error:

Apex trigger TrackOpportunityItems caused an unexpected exception, contact your administrator: TrackOpportunityItems: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Class.OpportunityItemsUpdater.addOppItems: line 29, column 1  
 
Here is the code for the class. Any help would be greatly appreciated,

Thanks :)
 
public class OpportunityItemsUpdater {

    public static void addOppItems(List<OpportunityLineItem> lineItems){
        
        List<Opportunity_Item__c> OppItems = new List<Opportunity_Item__c>();
    
        List<Id>  productIds = new List<Id>();
        for(OpportunityLineItem a : (List<OpportunityLineItem>)lineItems) {
            productIds.add(a.Product2Id);
            System.debug(productIds);
        }
        
        List<Product_Item__c> productItemsList = [SELECT Id, Quantity__c, Product__c, Item__c FROM Product_Item__c WHERE Product__c IN :productIds ];
        System.debug(productItemsList);
        
        //Map<ProductID, List<Product Items that lookup to that product>>
        Map<Id, List<Product_Item__c>> productItemMap = new Map<Id, List<Product_Item__c>>();
        for(Product_Item__c pi : productItemsList) {
            if(productItemMap.get(pi.Product__c ) == null) {
                productItemMap.put(pi.Product__c, new List<Product_Item__c>());
            }
            productItemMap.get(pi.Product__c).add(pi);
            System.debug(productItemMap);
        }
        
        
        for (OpportunityLineItem a : (List<OpportunityLineItem>)lineItems) {
            
            for(Product_Item__c pi : productItemMap.get(a.Product2Id)) {
                System.debug(productItemMap);
                Opportunity_Item__c oppItem = new Opportunity_Item__c();
                //oppItem.Opportunity_Product_Id__c = a.Product2Id;
                oppItem.Opportunity_Product_Id__c = a.Id;
                oppItem.Item_Id__c = pi.Item__c;
                oppItem.Quantity__c = a.Quantity * pi.Quantity__c;
                System.debug(pi);
                OppItems.add(oppItem);
                System.debug(oppItems);
            }
            
            
        }
        Insert OppItems;
        System.debug(OppItems);
    }
    
    public static void deleteOppItems(List<OpportunityLineItem> oldlineitems) {
        System.debug('delete');
        Set<Id> DeletedOppLineItemIds = new Set<Id>();
        for (OpportunityLineItem a :  oldlineitems) {
            DeletedOppLineItemIds.add(a.Id);
            
        }
        Delete [SELECT Id FROM Opportunity_Item__c WHERE Opportunity_Item__c.Opportunity_Product_Id__c IN : DeletedOppLineItemIds];

    }
}

 
I am not getting any error  on opportunity object and created task,but the same code is not working on contact
it giving error like this
exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Related To ID: id value of incorrect type: 0032800000NuHm0AAF: [WhatId]: T
Thanks in advance ,  Please give me solution for this 
trgger autocreatetask on Contact (after  insert , after update)  {
  
    list<task> tasklist = new list<task>();    
        for(contact con : trigger.new){
          task t = new task();
          t.whatid=con.id;
          t.Status = 'In Progress';
          t.Subject='call';
          t.Priority = 'High';
          t.ownerid= con.ownerid;

            tasklist.add(t);
        }
        
        insert tasklist ;     
    
    }
Hello,

I have a custom field for a lookup to a field. It only shows the objects that are created by me and i cannot see everything.

How can i solve it ?
  • April 20, 2016
  • Like
  • 0
Hi,

I need input on how to start with for the pop-up screen attached here.

I need to show a pop-up on a button click from an account detail page as shown in snapshot
User-added image


instead of showing any other page as pop-up, would like to create this purely in javascript/jQuery.
Thanks in advance!
HI All ,

I am getting this error while caaling a apex method from onclick javascript  from a custom button .

Please suugest how to get session .
HI All ,
We have overridden case view button to redirect to custom page/standard layout  based on record type conditiion . 
After overriding the button when console user opens mor ethen onne case either through omni channel or clicking on multiple case link scroll bar for few case layout is not working .

Please advice solution , if you have faced same problem before or any work around to solve this issue .
Thanks 
Manoj
HI All ,

I have a visualforce page ,where I am creating case .After creating case I am adding some other records as a child object to the case and  showing as a related list using <apex:relatedlist> component . Also standard attachment componenet is also there . however both records time zone is different for both ,though created by same user .

Parent records in GMT and child records in IST also format is diffrent .If any one faced this issue kindly help me .

Thanks 
Manoj
Hi All ,

I am trying to comunicate between facebook and salesforce by using the facebook toolkit .I have installed the toolkit and configure as per the below link .

https://github.com/developerforce/Force.com-Toolkit-for-Facebook

Now I am getting error (Recieved 400 from https://graph.facebook.com/me/home?access-token=null{"error":{"message":"Invalid OAuth access token",""type":"OAuthException","code":190,"fbtrace_id":DPGea\/xO92S})

Please suggest incae any one already fixed this issue .

Thanks 
Manoj
Hi All ,
In my organisation partner community is enabled ,So one profile which is the Sales Area Manager ,bacically he is a salesforce user .We have made that user as partner account owner .
When He/She loged in as asfdc user .He can use the global header to swip in to community as in community his profile is added .
Issue is I need to identify where actually he loged in whethere he is in community or Salesforce .How can I identify in apex .

 
HI All ,

I am creating a visual force email template ,in which am and using an component to use custom controller .I ahve added debug on that .However while using the template I am not able to view the debug log .Can any one suggest me .
Any suggestion is highly appreciated .

Thanks
Manoj
Hi All ,

I am working on quote ,I want to generate the quote in the form of doc file .I want to remove the header from first page only .
Any help is highly appreciated
Hi All ,
While  redering  Quote as word file ,I am facing a problem like ,Header is repeting twice in first page and footer  is repeating twice in last page .
Can nay one suggest me how to solve this issue .
Below is my code snipnet .



<apex:page sidebar="false" showChat="false" showHeader="false" contentType="application/msword#Test.doc" cache="true"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <style> @page Main { mso-header:h1; mso-footer:f1; } div.Main{ page:Main; } p.MyFoot, li.MyFoot, div.MyFoot{ mso-pagination:widow-orphan; tab-stops:center 216.0pt right 432.0pt; } p.MyHead { } </style> </head> <body> <div class="Main"> <div style="mso-element:header" id="h1"> <img src="https://c.cs17.content.force.com/servlet/servlet.ImageServer?id=015g000000044RX&oid=00Dg0000003MfeB&lastMod=1421154746000" style="height:10px;width:10px"/> </div> <div>Ashutosh Kumar Srivastava</div> <br style="page-break-after: always;"/> <div style="mso-element:footer" id="f1"> <img src="https://c.cs17.content.force.com/servlet/servlet.ImageServer?id=015g000000044RS&oid=00Dg0000003MfeB&lastMod=1421154652000" style="height:10px;width:10px"/> </div> </div> </body> </html> </apex:page>


Any help is heartily appreciated .
 
Hi All ,

I want  to track  location of the user, when he/she is updating event or posting status via portable devices such as smart phone or tablet.

Any solution is highly appreciated .

Thanks
Manoj
Hi All,

My code is returning a expression in string format. I need the calculated value in integer /double format.

String str = '25*5';
Integer result=Integer.valueOf(str);

Throwing error as Ivalid type exception.

Please help me on this .
I am facing an issue while uploading data in china language .It is uploading data but not in proper format .It is uploading with some spacial character .

Please help me on this .

Thanks ,
Manoj
Hi All,

I have reset auto number field in production after 2 records it is automatically jump to 33/35 like this .Can any one help me on this .

Thanks in advance.


Can any one help me on this,I am working on community need to modify the login page ?

I am following the documment but not able to complete the job.

Any suggesion is appreciated.

Hi All,

 

I want to save pdf  in to  local drive by the help of apex class.

 

Can any one suggest me how to fix this

 

Thanks in advance.

HI All,

 

I am craeting  a dynamic table in VF.In the table in each row first 2 column is generating from parent record and the rest four column is generating from child.For this I am iterating with two repeat .But the issue is , my td in table is gerating according to the size of the child record. I want every time the table should comlete whether the record is there or less in child object.

 

Can any one suggest me for this.

Thanks

Situ

 

Hi All,

 

  I need to give access to partner objcet without ViewAllData Access to a particular profile.Can any one help me on this.

 

Thanks In Advance

Situ

Hi All,

 

   I am facing a issue like in task Edit Mode I am able to view the Attach File for new Attachment in Attachment ralated List ,but not in detail mode in same record.Can any one help me on this.

 

Thanks in advance

Situ

Hi All,

 

     I have a query in that one condition  is there, like ' where  isSyncing=true' .In my test class I am not able to assign value to that isSyncing field .Can any one suggest me how to solve the issue .

 

Thanks In adavce.

Situ

Hi All,

 

 I am working on a pdf ,In the pdf  the table has a lot of records so it is creating more then 10 page .I need the table header in each page .also in the last page I don't need the header .Can any one suggest me some solution for this .

 

 

Thanks

Situ.

HI All,

 

I have declared a global variable in outer class and trying to access that varibale in inner class method it is showing error.

 

Can any one help me plz it very urgernt.

global class GlobalTest{   

    global String value='Situ';      

    public class Myclass{            

          public void  gtestMethod(){                  

               System.debug(value);     

          }

      }  

}

Error is like Variable does not exist: value at line 6 column 24

Thanks

Situ

I am facing an issue while uploading data in china language .It is uploading data but not in proper format .It is uploading with some spacial character .

Please help me on this .

Thanks ,
Manoj
Can any one have idea how to write a formula for two fields which were of picklist type and stage is other than initiated
  • March 10, 2020
  • Like
  • 0

Hello,

I need help creating an Apex Trigger in order to bring in a merge field into an email template. 

When Opportunities become "Closed Won", I want to create an email template (and then an alert) that would pull in the Account Billing Address on that Opportunity as well as the Main Contact's Name, Phone Number, and Email Address into the email.

When I reached out to Sales Support about this, they told me that I would need set up an Apex trigger to query the contact role then get the value from there.. because contact role is a junction object.

Can anyone offer any assistant to me with this? I would greatly appreciate it!!

Really confused newbie here.

I have read the following info provided by salesforce but its making me more confusing.

https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_groupmember.htm?search_text=Public%20Group

Because the share button doesnt work in Lightning, I have built following system.

Custom Object: Notification__c and NotificationShare__c
Flow: sharetoQueue

In the flow

1. User opens a flow screen in the Notification__c record and chooses a queue to share it with

2. Once queu is chosen and clicked "next", the Id of the queue user selected is retrieved

3. the record of GroupMember where the GroupId matches the Id retrieved in #3 is searched

4. Once match is found, the flow retrieves the UserOrGroupId of the match

5. Using the Object_Share, A child record of the Notification__c's record is created in  NotificationShare__c and UserOrGroupId is set to the data retrieved in #4

6. Other users in the chosen queue can now view the Notification__c record




Can anyone explain what GroupMember object and UserOrGroupId  is exactly with examples?
Diagrams or drawn images would be really appreciated.

Thanks in advance.
  • January 08, 2020
  • Like
  • 0
Query in Developer Console:
select count() from RecordAction where ActionDefinition!=null

Error Message: 
An unexpected error occurred. Please include this ErrorId if you contact support: 1892670731-238612 (-1863376665)

When I execute same query in batch job, I got below error:
14:38:37.0 (11628419)|SYSTEM_METHOD_EXIT|[15]|BatchableContextImpl
14:38:37.0 (11636572)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:12
14:38:37.0 (11641144)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
14:38:37.0 (11644929)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:4
14:38:37.0 (11651159)|VARIABLE_SCOPE_BEGIN|[31]|this|Database.BatchableContextImpl|true|false
14:38:37.0 (11720780)|VARIABLE_ASSIGNMENT|[31]|this|{}|0x2d9895fe
14:38:37.0 (11727467)|VARIABLE_SCOPE_BEGIN|[31]|jobId|Id|false|false
14:38:37.0 (11833691)|VARIABLE_ASSIGNMENT|[31]|jobId|"7076g00000BKmtGAAT"
14:38:37.0 (11839995)|VARIABLE_SCOPE_BEGIN|[31]|childJobId|Id|false|false
14:38:37.0 (11861408)|VARIABLE_ASSIGNMENT|[31]|childJobId|"7076g00000BKmk3AAD"
14:38:37.0 (35565779)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:38:37.0 (178500415)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:38:37.0 (267469628)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:38:37.0 (353732986)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:38:37.0 (476538181)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:38:37.0 (564648158)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8
14:38:37.0 (579395805)|FATAL_ERROR|Internal Salesforce.com Error


 
trigger IssuerUpdate on Issuer__c (before insert,before update)
{
    //Recursive Trigger So using this 
    if(trigger_handler.runOnce()){
        //New Record Insert 
        for(Issuer__c n : trigger.new)
        {
            //Checking the Condtion Status Feild
            if(n.Status__c== 'Approved'){
                //Getting the Query Already existing All feilds
                list<Issuer__c> iss = [SELECT Id,RevQ1__c,RevQ3__c,RevQ0__c,RevQ2__c FROM Issuer__c where id =:n.id];
                for(Issuer__c is :iss){
                    //RevQ0 values 1
                    n.RevQ3__c= n.RevQ1__c;
                    n.RevQ2__c= is.RevQ1__c;
                    n.RevQ3__c=is.RevQ2__c;
                    n.RevQ4__c=is.RevQ3__c;
                    //Rev 2
                   
                }if(n.Status__c== 'Approved'){
                    n.RevQ0__c=0;
         }
            }
        }
    }
}
  • January 07, 2020
  • Like
  • 0
Hi,

I am stuck in map.
Map-1 contactsAndEnrollmentMap  
     which contain           contactsAndEnrollmentMap.put(mc.hed__Contact__r.id,enRollmentId);

Map --2 programEnrollmentAndProgramCodeMap
which contain
 programEnrollmentAndProgramCodeMap.put(pe.id,programCode);

Now I want to create new map which contain programCode(Key ) and hed__Contact__r(Value);


Thanks
Hey all, I am new to to Apex code and wanted to see if anyone could help me with a test class for this trigger..  also thanks to whoever wrote this.. the community is awesome.
I just need to match entitlement to a case based on the account in lighning. thanks in advance. 

trigger DefaultEntitlement on Case (Before Insert, Before Update) {
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){
    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;
                        }
                    } 
                }
            } 
        } 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;
                            }
                        } 
                    }
                } 
            }
        }
    } 
}
i want to assign 100 different profile with same permission set through code in salesforce 
  • December 18, 2019
  • Like
  • 0
Hi,
I need help to create test class for a TriggerHandler Class.
I will show you my code.
Class Trigger Handler:
public class ContactTriggerHandler {
    
    Public static void newTasks_VisitPlanner(List<Contact> newContacts, Map<Id,Contact> mapOldContacts) {
        
        
        List<Task> NewTasks = new List<Task>();
        for (Contact con: newContacts){
            If(!checkRecursive.SetOfIDs.contains(con.Id)){
                Contact oldContact = mapOldContacts.get(con.Id);
                if(con.Frequency__c != oldContact.Frequency__c){
                    
                    if (con.Frequency__c == '3 Months'){
                        for(Integer i = 1; i < 5; i++){
                            Task newTask = new Task(
                                WhoId = con.Id,
                                WhatId = con.AccountId,
                                OwnerId = con.Assigned_to__c,
                                Subject = 'Rappel : Visite périodique',
                                ActivityDate = Date.today().addMonths(i*3),
                                Priority = 'Normal',
                                Status = 'Not Started',
                                Created_from_Visit_planner__c = true
                            );
                            NewTasks.add(newTask);
                        }
                    }
                    
                    if (con.Frequency__c == '6 Months'){
                        for(Integer i = 1; i < 3; i++){
                            Task newTask = new Task(
                                WhoId = con.Id,
                                WhatId = con.AccountId,
                                OwnerId = con.Assigned_to__c,
                                Subject = 'Rappel : Visite périodique',
                                ActivityDate = Date.today().addMonths(i*6),
                                Priority = 'Normal',
                                Status = 'Not Started',
                                Created_from_Visit_planner__c = true
                            );
                            NewTasks.add(newTask);
                        }
                    }
                }
                checkRecursive.SetOfIDs.add(con.Id);
            }
        }
        
        
        if(NewTasks != null && NewTasks.size()>0){
            insert NewTasks;
        }    
    }
}

Trigger:
trigger NewTasks_VisitPlanner_Trigger on Contact (after update) {
    
    ContactTriggerHandler.newTasks_VisitPlanner(Trigger.new, Trigger.oldMap);
}

Test Class:
@isTest
private class Test_NewTasksVisit_Trigger {
    
    @isTest
    public static void Test_newsTask3Months(){
        Account acc = new Account(Name = 'OPALE', Type = 'Public sector', Main_Role__c = 'Contracting authority' );
        insert acc;
        
        Contact con_A = new Contact(FirstName='Albert',LastName='Roche', AccountId = acc.id);
        insert con_A;

        con_A.Frequency__c='3 Months';
        con_A.Assigned_to__c=con_A.Name;
        update con_A;
        
        con_A.Frequency__c='6 Months';
        con_A.Assigned_to__c=con_A.Name;
        update con_A;
    }
    
    @isTest
    public static void Test_newsTask6Months(){
        Account acc = new Account(Name = 'SOGEA', Type = 'Private sector', Main_Role__c = 'Contracting authority support' );
        insert acc;
        
        Contact con_B = new Contact(FirstName='Jean',LastName='Rabi', AccountId = acc.id);
        insert con_B;
        
        con_B.Frequency__c='6 Months';
        con_B.Assigned_to__c=con_B.Name;
        update con_B;
        
        con_B.Frequency__c='3 Months';
        con_B.Assigned_to__c=con_B.Name;
        update con_B;
    }
}

​​​​​​​​​​​​​​
Hi i have desinged a vf page to add multiple accounts records for a particular contact using related accounts at same time. 

 But now i also have to delete existing relationships in the related accounts for the contact at the same time. 
Since the account contact relationship object doesnt have an ID field, also the account ID and contactID lookup are not editable fields.

So how can i delete the accountcontactrelationship record without deleting the associated contact or account ?

Please let me know.

Thanks,
Malhar Ulhas Agale.
Hello everyone,

i'm developing a webservice in rest and i have no idea about how write a test class in this case and this is my code.Please anyone help.

@RestResource(urlMapping='/BulkPatientDeactivationResponse/*')
global class BulkPatientDeactivationResponse {
    @HttpPost
    global static void doPost() {
        if (RestContext.request.requestBody != null) {
            Savepoint sp = Database.setSavepoint();
            try {
                String environmentCode = Utility.getEnvironmentCode(UserInfo.getUserName());
                
                String reqBody = RestContext.request.requestBody.toString();
                if (reqBody.contains('Header')) {
                    TranRes res = (TranRes)JSON.deserialize(reqBody, BulkPatientDeactivationResponse.TranRes.class);
                    String fileName = 'Unknown', type = 'Unknown', status = 'Unknown';
                    if (res.Response.Header.FileID != null) {
                        fileName = res.Response.Header.FileID;
                    }
                    if (res.Response.Header.TransactionType != null) {
                        type = res.Response.Header.TransactionType;
                    }
                    if (res.Response.Header.Status != null) {
                        status = res.Response.Header.Status;
                    }
                    List<TransactionDetail__c> tranList = [select Id, Transaction_Status__c, Response_JSON__c, HUB_Practice__c, HUB_Provider__c, Comments__c, Request_JSON__c from TransactionDetail__c where FileID__c = :fileName and Name = :type Limit 1];
                    
                    if (res.Response.ResponseType.AccountCode != null && res.Response.ResponseType.AccountCode != '') {
                        List<Account> lstAccount = [Select Id, Model_Number__c from Account where BluestarId__c =: res.Response.ResponseType.AccountCode and Enviornment_Code__c = :environmentCode Limit 1];
                        if (lstAccount.size() > 0) {
                            TransactionDetail__c transDetail = tranList.get(0);
                            BulkPatientDeactivationController.BulkPatientDeactivation bulkPatientDeactivationUser = (BulkPatientDeactivationController.BulkPatientDeactivation)JSON.deserialize(transDetail.Request_JSON__c, BulkPatientDeactivationController.BulkPatientDeactivation.class);
                            
                            if (res.Response.ResponseType.SuccessUsers != null && res.Response.ResponseType.SuccessUsers != '') {
                                Attachment file = new Attachment();
                                file.name = bulkPatientDeactivationUser.Request.Patient.Data + '-SuccessBulkDeactivationUsers' + '.json';
                                file.parentId = lstAccount[0].Id;
                                file.body = Blob.valueOf(res.Response.ResponseType.SuccessUsers);
                                insert file;
                                
                                String successUsersContent = '{"User":' + res.Response.ResponseType.SuccessUsers + '}';
                                Users successUsers = (Users)JSON.deserialize(successUsersContent, BulkPatientDeactivationResponse.Users.class);
                                Integer userCount = successUsers.User.size();
                                
                                List<String> lstBlueStarIDs = new List<String>();
                                for (Integer i = 0; i < userCount; i++) {
                                    lstBlueStarIDs.Add(successUsers.User[i].BlueStarID + '__' + environmentCode);
                                }
                                
                                List<Hub_Patient__c> lstPatients = [select Id, BlueStarID__c from Hub_Patient__c where BlueStarID__c in :lstBlueStarIDs];
                                
                                List<Hub_Patient__c> lstPatientsToDeactivate = new List<Hub_Patient__c>();
                                List<Id> deactivationPatients = new List<Id>();
                                for (Hub_Patient__c usr:lstPatients){
                                    deactivationPatients.Add(usr.Id);
                                    
                                    //Update Patient Status
                                    usr.Product_Status__c = 'Inactive';
                                    usr.ProductStatusReason__c = bulkPatientDeactivationUser.Request.Patient.DeactivateReason;
                                    usr.Status__c = Label.HubStat_Inactive;
                                    lstPatientsToDeactivate.Add(usr);
                                }
                                                                
                                //CheckAndCloseAllTaskForPatients
                                List<Task> lstTask = [select Id, Type, Status from Task where WhatId in :deactivationPatients and Type != :Label.TaskType_PatientDrivenFailure and Status != 'Closed'];
                                if (lstTask.size() > 0) {
                                    for (Integer j = 0; j < lstTask.size(); j++) {
                                        lstTask[j].Status = 'Closed';
                                    }
                                    update lstTask;
                                }
                                
                                List<TransactionDetail__c> lstTran = new List<TransactionDetail__c>();
                                if (lstPatientsToDeactivate.size() > 0) {
                                    List<Database.SaveResult> lstResult = Database.update(lstPatientsToDeactivate, false);
                                    for (Integer i = 0; i < lstResult.size(); i++) {
                                        if (!lstResult[i].isSuccess()) {
                                            String message = null;
                                            Database.Error[] errs = lstResult[i].getErrors();
                                            for (Integer j = 0; j < errs.size(); j++){
                                                message = message + '\\n' + errs[j].getStatusCode() + ': ' + errs[j].getMessage() + '.'; 
                                            }
                                            TransactionDetail__c tran = new TransactionDetail__c();
                                            tran.Name = 'BulkPatientDeactivationFailure';
                                            tran.Transaction_Type__c = 'Inbound';
                                            tran.Transaction_Status__c = 'Exception';
                                            tran.Account__c = lstAccount[0].Id;
                                            tran.Request_JSON__c = JSON.serialize(successUsers.User[i]);
                                            tran.Response_JSON__c = message;
                                            lstTran.add(tran);
                                        }
                                    }
                                }
                                if (lstTran.size() > 0) {
                                    Database.insert(lstTran, false);
                                }
                            }
                            
                            if (res.Response.ResponseType.FailureUsers != null && res.Response.ResponseType.FailureUsers != '') {
                                Attachment file = new Attachment();
                                file.name = bulkPatientDeactivationUser.Request.Patient.Data + '-FailureBulkDeactivationUsers' + '.json';
                                file.parentId = lstAccount[0].Id;
                                file.body = Blob.valueOf(res.Response.ResponseType.FailureUsers);
                                insert file;
                                
                                TransactionDetail__c tran = new TransactionDetail__c();
                                tran.Name = 'BulkPatientDeactivationFailure';
                                tran.Transaction_Type__c = 'Inbound';
                                tran.Transaction_Status__c = 'Exception';
                                tran.Account__c = lstAccount[0].Id;
                                tran.Request_JSON__c = 'Error Deactivating Users in product. Error Deactivation Users details : ' + res.Response.ResponseType.FailureUsers;
                                tran.Response_JSON__c = 'Error Deactivating Users in product.';
                                Database.insert(tran);
                            }
                        }
                    }
                    
                    if (tranList.size() > 0) {
                        TransactionDetail__c tran = tranList[0];
                        tran.Transaction_Status__c = status;
                        tran.Response_JSON__c = reqBody;
                        update tran;
                    }
                    else {
                        BlueStarTransactionDetails.CreateUnknownTransactionResponse(fileName, status, reqBody);
                    }
                }
                else if (reqBody.contains('SchemaError')) {
                    SchemaErrorTran schemaErr = (SchemaErrorTran)JSON.deserialize(reqBody, BulkPatientDeactivationResponse.SchemaErrorTran.class);
                    System.debug(schemaErr);
                    if (schemaErr.Response.SchemaError.FileName != null) {
                        String fileName = schemaErr.Response.SchemaError.FileName.replace('SD_WD_', '').replace('_', '.').replace('.xml', '');
                        String tranStatus = 'Failure: ';
                        if (schemaErr.Response.SchemaError.ErrorText != null) {
                            if (schemaErr.Response.SchemaError.ErrorText.length() > 23) {
                                tranStatus = tranStatus + schemaErr.Response.SchemaError.ErrorText.substring(0, 22);
                            }
                            else {
                                tranStatus = tranStatus + schemaErr.Response.SchemaError.ErrorText;
                            }
                        }
                        List<TransactionDetail__c> tranList = [select Id, Transaction_Status__c, Response_JSON__c from TransactionDetail__c where FileID__c = :fileName Limit 1];
                        if (tranList.size() > 0) {
                            TransactionDetail__c tran = tranList[0];
                            tran.Transaction_Status__c = tranStatus;
                            tran.Response_JSON__c = reqBody;
                            update tran;
                        }
                        else {
                            BlueStarTransactionDetails.CreateUnknownTransactionResponse(schemaErr.Response.SchemaError.FileName, tranStatus, reqBody);
                        }
                    }
                    else {
                        BlueStarTransactionDetails.CreateUnknownTransactionResponse('Unknown', 'Unknown', reqBody);
                    }
                }
                else {
                    BlueStarTransactionDetails.CreateUnknownTransactionResponse('Unknown', 'Unknown', reqBody);
                }
            } catch (Exception ex) {
                Database.rollback(sp);
                String resp = RestContext.request.requestBody.toString();
                BlueStarTransactionDetails.CreateErrorProcessingTransactionResponse('Unknown', 'Exception', resp, ex.getMessage());
            }
        }
    }
    
    public class TranHeader {
        public String TransactionType;
        public String TimeStamp;
        public String FileID;
        public String Status;
    }
    
    public class ResType {
        public String HubCode {get;set;}
        public String BlueStarID {get;set;}
        public String AccountCode {get;set;}
        public String SuccessUsers {get;set;}
        public String FailureUsers {get;set;}
        public String FailedUsers {get;set;}
    }
    
    public class TranResp {
        public TranHeader Header;
        public ResType ResponseType;
    }
    
    public class TranRes {
        public TranResp Response;
    }
    
    public class SchemaErr {
        public String FileName {get;Set;}
        public String ErrorText {get;set;}
    }
    
    public class SchemaErrorResp {
        public SchemaErr SchemaError;
    }
    
    public class SchemaErrorTran {
        public SchemaErrorResp Response;
    }
    
    public class Users {
        List<DeactivationUser> User {get;set;}
    }
    
    public Class DeactivationUser {
        String Email {get;set;}
        String BlueStarID {get;set;}
    }
}

Please any one help me.

Thanks Inadvance
public with sharing class DataTableController {
    
    @AuraEnabled
    public static DataTableWrapper initRecords(String ObjectName, String fieldSetName, String Orderby, String OrderDir) {
        
        DataTableWrapper dtw = new DataTableWrapper();
        List<LabelDescriptionWrapper> labelList = new List<LabelDescriptionWrapper>();
        List<String> fieldSet = new List<String>();
        Set<String> fieldNameSet = new Set<String>(getFieldSet(ObjectName, fieldSetName).split(','));
        system.debug('fieldNameSet11'+fieldNameSet);
        
        if(Schema.getGlobalDescribe().containsKey(ObjectName) ) {
            //sObject sObj = Schema.getGlobalDescribe().get(ObjectName).newSObject() ;
            //system.debug('sObj+++++++++++++++++++'+sObj);
            
            //get all the labels for sObject fields and put them in a map, keyed to the field api name
            Map<String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get(ObjectName).getDescribe().fields.getMap();
            //fieldmap contains all fields name of an sObject in proper naming case.
            system.debug('fieldMap++++++++'+fieldMap);
            Map<Schema.SObjectField,String> fieldToAPIName = new Map<Schema.SObjectField,String>();
            system.debug('fieldToAPIName+++++++++'+fieldToAPIName);
            Map<String, String> apiNameToLabel = new Map<String, String>();
            Boolean loopFlag = false;
            for(String fieldName :  fieldNameSet){
                if(loopFlag == false && fieldMap.containsKey(fieldName)){
                    fieldSet.add(fieldName);
                    labelList.add(new LabelDescriptionWrapper(fieldMap.get(fieldName).getDescribe().getLabel(), 
                                                              fieldName == 'Name' ? 'LinkName' : fieldName,  
                                                              'url',
                                                              new typeAttributesWR(new labelWR(fieldName), '_self'),
                                                              true));
                    loopFlag = true; 
                    continue;
                }
                if(fieldMap.containsKey(fieldName)) {
                    fieldSet.add(fieldName);
                    //labelList.add(new LabelDescriptionWrapper(fieldMap.get(fieldName).getDescribe().getLabel(), fieldName, fieldMap.get(fieldName).getDescribe().getType().name().toLowerCase(), true ));
                    labelList.add(new LabelDescriptionWrapper(fieldMap.get(fieldName).getDescribe().getLabel(), 
                                                              fieldName, 
                                                              'text', null,
                                                              //fieldMap.get(fieldName).getDescribe().getType().name().toLowerCase(), 
                                                              true ));
                }
            }
            
            //call method to query
            List<sObject> sObjectRecords = getsObjectRecords(ObjectName, fieldSet, 20, '', Orderby, OrderDir);
            system.debug('labelList '+labelList);
            dtw.ldwList     = labelList;
            dtw.sobList     = sObjectRecords;
            dtw.fieldsList     = fieldSet;
            dtw.totalCount  = Database.countQuery('SELECT count() FROM '+ObjectName);
        }
        system.debug('dtw+++++++'+dtw);
        //returns wrapper datatype and fieldset fields properties.
        return dtw;
    }
    
    @AuraEnabled
    public static List<sObject> getsObjectRecords(String ObjectName, List<String> fieldNameSet, Integer LimitSize, String recId, String Orderby, String OrderDir) {
        
        OrderDir = String.isBlank(OrderDir) ? 'asc' : OrderDir;
        String query = 'SELECT '+String.join(fieldNameSet, ',')+' FROM '+ObjectName;
        if(String.isNotBlank(recId)) {
            recId = String.valueOf(recId);
            query += ' WHERE ID >: recId ';
        }
        
        query += ' ORDER BY '+Orderby+' '+OrderDir+' NULLS LAST';
        
        if(LimitSize != null && Integer.valueOf(LimitSize) > 0) {
            LimitSize = Integer.valueOf(LimitSize);
            query += ' Limit '+LimitSize;
        }
        system.debug('query++++++++++'+query);
        system.debug('query++++++++++'+Database.query(query));
        //this will return all the sObject records with all fieldset fields values.
        return Database.query(query);
    }
    
    @AuraEnabled
    //get api name of the fields of a fieldset
    public static String getFieldSet(String sObjectName, String fieldSetName) {
        String result = '';
        SObjectType objToken = Schema.getGlobalDescribe().get(sObjectName);//metadata 
        Schema.DescribeSObjectResult d = objToken.getDescribe();
        Map<String, Schema.FieldSet> FieldsetMap = d.fieldSets.getMap();//<fset name, label>
        system.debug('objToken+++++++++'+objToken);//returns the name of the sobject.
        if(FieldsetMap.containsKey(fieldSetName))
            for(Schema.FieldSetMember f : FieldsetMap.get(fieldSetName).getFields()) {
                if(string.isNotBlank(result)){
                    result += ',';
                }
                result += f.getFieldPath();
            }
        system.debug('result *****'+result);
        return result ;//returns the name of the fields in  a fieldset.
       
    }

    public class DataTableWrapper {
        @AuraEnabled
        public List<LabelDescriptionWrapper> ldwList;
        @AuraEnabled
        public List<sObject> sobList;
        @AuraEnabled
        public List<String> fieldsList;
        @AuraEnabled
        public Integer totalCount;
    }
    
    public class LabelDescriptionWrapper {
        @AuraEnabled
        public String label;
        @AuraEnabled
        public String fieldName;
        @AuraEnabled
        public String type;
        @AuraEnabled
        public typeAttributesWR typeAttributes;
        @AuraEnabled
        public boolean sortable;        
        
        public LabelDescriptionWrapper(String labelTemp, String fieldNameTemp, String typeTemp,  typeAttributesWR typeAttributesTemp, boolean sortableTemp) {
            label       = labelTemp;
            fieldName = fieldNameTemp;
            type       = typeTemp;
            typeAttributes = typeAttributesTemp;
            sortable  = sortableTemp;            
        }            
    } // end LabelDescriptionWrapper
    public class labelWR {
        @AuraEnabled
        public String fieldName;
        public labelWR(String fieldNameTemp){
            fieldName = fieldNameTemp;
        } 
    }
    
    public class typeAttributesWR {
        @AuraEnabled
        public labelWR label;
        @AuraEnabled
        public String target;
        
        public typeAttributesWR(labelWR labelTemp, String targetTemp){
            label = labelTemp;
            target = targetTemp;
        } 
    }
}
I want to delete dupicate accounts below code for your reference. Attached is the error
global class DuplicateRecords implements Database.Batchable<SObject>  {

     

  Global Map<String , Account__c> AccountNumberBookmap = new Map<String ,  Account__c>();

     

    global Database.QueryLocator start(Database.BatchableContext BC){

      return Database.getQueryLocator([Select AccountNumber__c from Account__c where AccountNumber__c != null]);

      }

     

     

     

    global void excute(Database.BatchableContext BC , List<AccountNumber__c> scope){

         

      

         

         

      // Map<String , AccountNumber__c> AccountBookmap = new Map<String , AccountNumber__c>();

         

        List<AccountNumber__c> duplicatelist = new List<AccountNumber__c>();

        for(AccountNumber__c s : scope){

            if(! AccountBookmap.containsKey(s.Account__c)){

                AccountBookmap.put(s.Account__c , s);

            }

            else{

                duplicatelist.add(s);          

            }                       

        } 

                

        

       system.debug(duplicatelist);

        if(duplicatelist.size() > 0){

            delete duplicatelist;

        }

    }

     

    global void finish(Database.BatchableContext BC){

         

    }

         

 

}
User-added image
I tried but my code is not working
trigger AttachmentTrigger on Attachment (before insert) {
    Set<Id> attid = new Set<Id>();  
    for(Attachment att : Trigger.new){
        attid.add(att.parentId);
        
    }
    Map<Id,Account> acMap = new Map<Id,Account>([select id,(select id,parentId from attachments) from Account where Id IN : attid]);

    for(Attachment att : Trigger.New){
       
        if(acMap.get(att.parentId).attachments.size() > 4 ){
            
            att.adderror('You can not add more than 4 attachments!');
        }
    }
}

Can someone help me on this
how to make a number  field(total units__c) as a read only, non editable and that field should have default value. for example , if (total units__c) is set to a default value 10.whenever a status__c(picklist) is selected as sold,the (total units__c) should decrease by 1
  • April 30, 2019
  • Like
  • 0
Hi All,

How to write a scheduler class for daily and weekly for below Batch Apex
  • IF the recent Recharge record for 'Internet Plan' record was made 1 day ago and its 'Data Plan' = 'Daily', then create Recharge record.
  • IF the recent  Recharge for 'Internet Plan' was made 6 days ago and 'Data Plan' = 'Weekly', then create Recharge record.
    global class batchCreateRecharge implements Database.Batchable<sobject> {
      
        global Database.QueryLocator start(Database.BatchableContext bc){
          
            String query = 'SELECT Id, Data_Plan__c,Total_Amount__c FROM Internet_Plan__c';
            return Database.getQueryLocator(query);
        }
          
        global void execute(Database.BatchableContext bc, List<Internet_Plan__c> scope) {
          try {
         List<Recharge__c> rcList = new List<Recharge__c>();
            for(Internet_Plan__c IP : scope) {
               Recharge__c rc = new Recharge__c();
              rc.Amount__c = IP.Total_Amount__c;
               rc.Internet_Plan__c= IP.id;
             rcList.add(rc);
             System.debug('******Recharge list'+rcList);
            }
       insert rcList;
     }
             
                catch( DmlException e ) {
                    // HANDLES EXCEPTIONS RELATED TO DML STATEMENTS.
                    System.debug( 'QueryException:-\n' + e.getMessage() + '\nLine Number:-\n' + e.getLineNumber() );
                }
                catch( Exception e ) {
                    // HANDLES EXCEPTIONS OTHER THAN ABOVE SUCH AS NULL POINTER EXCEPTIONS OR ETC.
                    System.debug( 'QueryException:-\n' + e.getMessage() + '\nLine Number:-\n' + e.getLineNumber() );
                }
    
        } 
          
        global void finish(Database.BatchableContext bc) {
          
        }
    }

    Kindly Support and Suggest
Thanks
  • April 30, 2019
  • Like
  • 0
I am deploying my Trigger and test classes to Production but i am getting the error  too much soql queries 101....and the test classes that are already in production are failing ... and as i have checked the error lines of Test class the method of class is callling and there is no problem of anywhere of SOQL query.. please explain me what happening?
I'm trying display a field and line break only if a certain checkbox, ".Activity_Completed__c",  is unchecked, otherwise I don't want it to display anything.

<apex:outputText rendered="{!IF(OR(ISBLANK, 'cx.Activity'), !NOT(cx.Activity_Completed__c)), NULL, '{!cx.Activity__c}<br/>'}" />
<apex:outputText rendered="{!IF(OR(ISBLANK, 'cx.Activity1'), !NOT(cx.Activity_Completed1__c)), NULL, '{!cx.Activity__c}<br/>'}" />
<apex:outputText rendered="{!IF(OR(ISBLANK, 'cx.Activity2'), !NOT(cx.Activity_Completed2__c)), NULL, '{!cx.Activity__c}<br/>'}" />
<apex:outputText rendered="{!IF(OR(ISBLANK, 'cx.Activity3'), !NOT(cx.Activity_Completed3__c)), NULL, '{!cx.Activity__c}<br/>'}" />
...

I'm very new to visualforce so I'm not sure if I'm going in the right direction
I need to look for changes in a list of fields in a record using a trigger. How can I reference the list of fields and append it to the trigger.new and the trigger.old references?

Below is code I've tried to use, but my variable "s" is not recognized. Thanks for any help you can provide.
Map<Id, lda_Opportunity__c> MPPMap = new Map<Id, lda_Opportunity__c>();

list<Schema.SObjectField> FieldList = new list<Schema.SObjectField>();
FieldList.add(lda_Opportunity__c.Location__c); // Many more fields to add
        
for (integer i=0; i < trigger.new.size(); i++){
   for (Schema.SObjectField s : FieldList){
      if (trigger.new[i].s != trigger.old[i].s){
         MPPMap.put(trigger.new[i].Id, trigger.new[i]);
      }
   }
}

 
We are looking for a Salesforce Admin/PM with non-profit experience for a client in Maryland.  Long term, on-site contract opportunity.  Please email phil@tech2resources.com if interested.

Not really a question, but  solution I thought might be helpful to others:

 

Due to the nature of most backoffice (and frontoffice, for that matter) systems, the standard Address object in salesforce does not work well with integrations, especially if you are using Salesforce.com as the system of record for some addresses.  Most of these systems use a dedicated field for each address line.   We need our street address field to fit into our accounting system limitations, which are:

1. Maxium of 30 characters per line

2. No more than two lines

 

Anyway, the answer for me was some fairly basic Regex for the BillingStreet Field:

NOT(
OR(
REGEX(
BillingStreet,
".{0,30}"
),
REGEX(
BillingStreet,
".{0,30}\r\n.{0,30}"
)
)
)

My regex logic:

Must be:
Empty or Single line less than 31 characters:
.{0,30}
Two lines with less than 31 characters each line:
.{0,30}\r\n.{0,30}

You can also do this with negative enforcement, but the positive model is much cleaner (example shown with 60 character limit instead of 30):

NOT:
2 or more CRLFs
(.*\r\n){2,}.*
More than 60 characters on single line
.{61,}
More than 60 characters on first line of two
.{61,}\r\n.*
More than 60 characters on second line of two
.*\r\n.{61,}

I learned the following about SF regex while doing this:

1. It does not appear to operate in multi-line mode (IE the $ zero-width match does not match the end of each line, just the end of the field)

2. The dot (.) does not match EOL characters (\r and \n)

3. Your regex has to match the entire field - all lines to be true.   In other workds, .* will not match a multi-line field.

4. To match the entire field regardless of the number of lines you would use (.*\r\n){*}

5. SF Address field uses \r\n as their EOL for the purposes of regex (I think this is different than the export, which is supposed to use just \n).

 

Enjoy,

 

Brandy Peterson