+ Start a Discussion
Harjeet Singh 28Harjeet Singh 28 
Hi All,

I have developed an apex class whcih basically assign users to queue dynamically.I have a VF page which will launch from a custom VF tab.This VF page shows few users and with the checkbox.When checkbox against the username is marked and hit Save button then seleected users will go to the queue defined in class.
Below is my clas:
public class TodayTelesalesDetails {

public Date Today { 
    get { 
        return Date.today(); 
    }
}
public List<wrapAgent> wrapAgentList{get; set;}
public List<User> selectedAgents{get;set;}

public TodayTelesalesDetails (){
   
    if(wrapAgentList == null) {
        wrapAgentList = new List<wrapAgent>();

        for(User teleSalesAgent: [select Id, Name, Email from User where Name IN('Steve Waugh','Yuvraj Singh')]) {
            // As each agent is processed we create a new wrap object and add it to the wrapAgentList
            wrapAgentList.add(new wrapAgent(teleSalesAgent));
    }
}
}

public PageReference doFullSave(){

    set<id> userSetId = new set<id>();
    list<GroupMember> gmm = new list<GroupMember>();
    List<GroupMember> toBeDeleted= [SELECT Id, GroupId, UserOrGroupId FROM GroupMember where GroupId = '00G9D000000toPYUAY'];
    delete toBeDeleted;
    List<User> userlist=[select Id, Name from User where Name IN('Steve Waugh','Yuvraj Singh')];
   
    for(User u : userlist)
    { 
    system.debug('message3>>'+u);
         for(wrapAgent wrapAccountObj : wrapAgentList) {
             
            if(wrapAccountObj.selected == true) {
                userSetId.add(wrapAccountObj.teleAgent.id);
                
            }
        }

    }
      
    for(User us : [select id from User where id =: userSetId])
    {
       
        for(Group gg : [select id,name from Group where type = 'Queue' and Name = 'TeleSales Queue'])
        {
            GroupMember gm = new GroupMember();
            gm.groupId = gg.id;
            gm.UserOrGroupId = us.Id;
            gmm.add(gm);
        }
        
    }
            
     
    insert gmm;
    PageReference pageRef = new PageReference('/');
            pageRef.setRedirect(true);
            return pageRef;
    }
   
   
    
 public PageReference doCancel(){
         
         PageReference pageRef = new PageReference('/');
            pageRef.setRedirect(true);
            return pageRef;
    }


 public class wrapAgent{
    public User teleAgent {get; set;}//Please put the custom metadata names
    public Boolean selected {get; set;}


    //This is the contructor method. When we create a new object we pass a telesales metadata member that is set to the acc property. We also set the selected value to false
    public wrapAgent(User teleSalesAgent) {
        teleAgent = teleSalesAgent;
        selected = false;

    }
}
}
and below is my test class:
@isTest
public class Test_TodayTeleSalesDetails {

    public static testMethod void validateusersinqueue() {
    Group testGroup = new Group(Name='test group', Type='Queue');
	insert testGroup;

	System.runAs(new User(Id=UserInfo.getUserId()))
	{
    QueuesObject testQueue = new QueueSObject(QueueID = testGroup.id, SObjectType = 'Lead');
    insert testQueue;
	}
   	Test.startTest();
     TodayTelesalesDetails telesalesDetails=new TodayTelesalesDetails();
       telesalesDetails.doFullSave();
        telesalesDetails.doCancel();
    Test.stopTest();
}
}

I am not able to cover below lines of code:
for(User us : [select id from User where id =: userSetId])
    {
        system.debug('message6>>'+us);
        for(Group gg : [select id,name from Group where type = 'Queue' and Name = 'TeleSales Queue'])
        {
            GroupMember gm = new GroupMember();
            gm.groupId = gg.id;
            gm.UserOrGroupId = us.Id;
            gmm.add(gm);
        }
        
    }
Below is the screenshot for the same:
Lines of Code is not covering
My current code coverage stands at 73%

Many I request to help me on same to get a code coverage above 75%

Many thanks in advance

Thanks & Regards,
Harjeet
Best Answer chosen by Harjeet Singh 28
Ajay K DubediAjay K Dubedi
Hi Harjeet,

If you want to keep "selected" of wrapAgent as false and want to increase your code coverage then you can use Test.isRunningtest() in your code. You can update your code as below:
 
for(User u : userlist)
        { 
            system.debug('message3>>'+u);
            for(wrapAgent wrapAccountObj : wrapAgentList) {
                if(!Test.isRunningTest()){                          
                    if(wrapAccountObj.selected == true) {
                        userSetId.add(wrapAccountObj.teleAgent.id);
                    }
                }else{
                    userSetId.add(wrapAccountObj.teleAgent.id);
                } 
                
            }
            
        }

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com
Marvin Castro 8Marvin Castro 8 
Hello.  I'm new to salesforce.  How do I create a trigger that will update the lead status to working when an activity is created (event, task, call)?  I saw this code while doing research, and it works for logging a call, but does not update the status if I schedule an event.  Any help will be appreciated.

trigger changeLeadStatus on Task (before insert, before update) {
    String desiredNewLeadStatus = 'Working';

    List<Id> leadIds=new List<Id>();
    for(Task t:trigger.new){
        if(t.Status=='Completed'){
            if(String.valueOf(t.whoId).startsWith('00Q')==TRUE){//check if the task is associated with a lead
                leadIds.add(t.whoId);
            }//if 2
        }//if 1
    }//for
    List<Lead> leadsToUpdate=[SELECT Id, Status FROM Lead WHERE Id IN :leadIds AND IsConverted=FALSE];
    For (Lead l:leadsToUpdate){
        l.Status=desiredNewLeadStatus;
    }//for
    
    try{
        update leadsToUpdate;
    }catch(DMLException e){
        system.debug('Leads were not all properly updated.  Error: '+e);
    }
}//trigger
 
Best Answer chosen by Marvin Castro 8
UC InnovationUC Innovation
Hello Marvin,

You need to create the same trigger on the Event Object. Events and Tasks are both activities, but they are separate objects (They are special in that way). You already have the code, just copy it for Events and you should be good!

Hope this helps!
Sajjan T SSajjan T S 
I am trying to write a batch apex to schedule and delete cases that were created before 18 months along with the related files. Can someone help me with formulating the query, please?
Best Answer chosen by Sajjan T S
Sajjan T SSajjan T S
The working batch class code below:

Global class OldCaseDeleter implements Database.Batchable<SObject> {
    Public List<SObject> allRecords;
   Global Database.QueryLocator start(Database.BatchableContext BC) {
       String query = 'SELECT Id FROM Case WHERE CreatedDate = today and Exempt_From_Deletion__c = false';
       System.debug('query -> ' + query);
       return Database.getQueryLocator(query);
   }
   Global void execute(Database.BatchableContext BC, List<SObject> records) {
       List<Case> caseList = (List<Case>)records;
       Set<Id> caseID = new Set<Id>();
       for(Case c: caseList) {
           caseId.add(c.Id);
       }
       List<ContentDocumentLink> files = [SELECT ContentDocumentId, LinkedEntityId
                                          From ContentDocumentLink
                                          WHERE LinkedEntityId IN :caseId];
       Set<Id> conId = new Set<Id>();
       for(ContentDocumentLink cd : files) {
           conId.add(cd.ContentDocumentId);
       }
       List<ContentDocument> files1 = [SELECT Id, Title
                               FROM ContentDocument
                               WHERE Id IN : conId];
           allRecords = new List<SObject>();
        allrecords.addAll((List<SObject>)files1);
        allrecords.addAll((List<Case>)caseList);
        Delete allrecords;
   }
   Global void finish(Database.BatchableContext BC) {
   }
}

 
EtienneCoutantEtienneCoutant 

Hi,

 

Can someone help, I keep getting the error:

System.DmlException: Insert failed. First exception on row 0 with id 00oS0000000AOgYIAW; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

 

But I am pretty sure that there is no Id specified in my insert call.

Here is my code:

 

 

public PageReference save() { List<OpportunityLineItemSchedule> revenueSchedulesToUpdate = new List<OpportunityLineItemSchedule>(); List<OpportunityLineItemSchedule> revenueSchedulesToInsert = new List<OpportunityLineItemSchedule>(); for(revenueSchedulesDate revenueSchedulesDate:revenueSchedulesDates){ for(OpportunityLineItemSchedule revenueSchedule:revenueSchedulesDate.getRevenueSchedules()){ if(revenueSchedule.get('Id') == null) revenueSchedulesToInsert.add(revenueSchedule); else revenueSchedulesToUpdate.add(revenueSchedule); } if(revenueSchedulesToUpdate.size() > 0) update revenueSchedulesToUpdate; if(revenueSchedulesToInsert.size() > 0) insert revenueSchedulesToInsert; } return Page.revenueScheduleView2; }

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
wesnoltewesnolte

Hey

 

You're getting this error becuase you're adding items to list; inserting the list; adding more items to the list; and then trying to insert all the items you've already inserted and the new ones.

 

You shouldn't be performing DML inside a loop, although isn't directly causing your issue. Try this instead:

 

    public PageReference save() {
        List<OpportunityLineItemSchedule> revenueSchedulesToUpdate = new List<OpportunityLineItemSchedule>();
        List<OpportunityLineItemSchedule> revenueSchedulesToInsert = new List<OpportunityLineItemSchedule>();
       
        for(revenueSchedulesDate revenueSchedulesDate:revenueSchedulesDates){
            for(OpportunityLineItemSchedule revenueSchedule:revenueSchedulesDate.getRevenueSchedules()){
                if(revenueSchedule.get('Id') == null)
                    revenueSchedulesToInsert.add(revenueSchedule);
                else
                    revenueSchedulesToUpdate.add(revenueSchedule);
            }
        }
       
        update revenueSchedulesToUpdate;
        insert revenueSchedulesToInsert;       
       
        return Page.revenueScheduleView2;
    }

 

This will help with governor limits(although this still depends on the amoutn of data you work with), and will avoid your other issue.

 

Wes

 

 

uptime_andrewuptime_andrew 

I have an APEX Trigger that runs when a Task is created/updated, so it can update the related Case. 

 

Somehow, the trigger is causing the Case Assignment Rules to re-fire, but I don't know what.  Any thoughts?

 

 

 

trigger caseLastActivityDate on Task (after insert, after update) { Map<String, Task> tMap = new Map<String, Task>(); for (Task t : System.Trigger.new) { String whatId = t.WhatId; System.debug('whatId is ' + whatId); if(whatId <> null && whatId.startsWith('500') == true) { Case c = [select Id from Case where Id = :whatId]; if(c.Id <> null) { c.Last_Activity_Date__c = t.LastModifiedDate; update c; } } } }

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
uptime_andrewuptime_andrew

The solution I had for this was two-fold:

 

First, we added a new field, "Case Taken", which is just a boolean.   Once the case is taken by a user (who is not the default assignee), Case Taken is set to true.

 

Second, we updated the assignment rules with an new entry/step where if Case Taken equals True and the owner is not the default assigner, use the "Do Not Reassign Owner" flag.

anil Kumaranil Kumar 
Hi All,

We have few web service call outs from salesforce community portal to external system. External system has been upgraded to TLS 1.2 protocol. Now they wants us to upgrade to LS 1.2 protocol version. Kidly help me how to upgrade TLS 1.2 version in salesforce?

Thanks,
Anil Kumar
Best Answer chosen by anil Kumar
Khan AnasKhan Anas (Salesforce Developers) 
Hi Anil,

Greetings to you!

It is possible to get this upgrade to TLS 1.2 "indirectly" by upgrading your browser to the latest version. You will automatically be using it if you are using updated browsers. Also, you update your JDK to the latest version.

To check if your browser can handle TLS v1.1 and v1.2, select https://www.ssllabs.com/ssltest/viewMyClient.html to open the SSL/TLS Capabilities of Your Browser web page.

Once the page completes the test, scroll down to the Protocol Features section.
  • If Yes is displayed next to TLS 1.1 and/or TLS 1.2, your browser will continue to work as it is currently does with Talent Suite applications.

However, Salesforce is requiring an upgrade to TLS 1.2 by September, 2019, in order to align with industry best practices for security and data integrity. Around this date, Salesforce will begin disabling the TLS 1.1 encryption protocol. 

A new Critical Update Console (CRUC) setting: "Require TLS 1.2 or higher for HTTPS connections" will be made available in the upcoming weeks. You can check the critical updates from Setup -> Search Critical Updates in Quick Find Box -> Select Critical Updates.

Please refer to the below link which might help you further with the above requirement.

https://help.salesforce.com/articleView?id=000221207&type=1

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
TraceyTracey 

I'm trying to copy a new user as contact by using a trigger but I'm getting the following error

 

MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Contact, original object: User

 

trigger Acceleration_User_Copyto_Contact on User (after insert, after update) {
    
   // Map<String,User> newLead = new Map <String, User>();
    
    system.debug('Acceleration_User_Copyto_Contact Trigger....');
 
    for ( User user : System.Trigger.new)
    {
        if  (user.Email.contains('acceleration'))
        {
            system.debug('Acceleration_User_Copyto_Contact Trigger..2.');
            Integer RecordCount = [select count() from Contact c where c.Email = : user.Email];
            
            system.debug('Acceleration_User_Copyto_Contact Trigger..2a .' + RecordCount);
            
            if (RecordCount == 0)
            {
                String AccountId = '';
                for ( Account a : [Select a.Id From Account a where Name = 'Acceleration']) 
                {
                    system.debug('Acceleration_User_Copyto_Contact Trigger..3.');
                     
                    AccountId = a.Id;
                
                    Contact con = New Contact();
                    con.AccountId = AccountId ;
                    con.Email = user.Email;
                    con.Firstname = User.Firstname;
                    con.Lastname = User.Lastname ;
                    con.User__c = User.Id;
                    insert con;
                }          
            }                   
        }
        
     }
    
    
}

 

Best Answer chosen by Admin (Salesforce Developers) 
wesnoltewesnolte

Hey

 

There you cannot perform DML on what salesforce calls setup objects(User in this case) and non-setup object in the same context. There is a workaround that can be found here although I still had some issues. Let me know if the posted solution works for you, if not mail me and I'll send you mine.

 

Cheers,

Wes 

Eric_SantiagoEric_Santiago 
I'm trying to write a simple trigger that renames a record. I keep getting the error "CallLineItemRename: execution of BeforeInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.CallLineItemRename: line 18, column 9" . What am I missing here?

 

 

 

trigger CallLineItemRename on Call_Line_Item__c (before insert, before update) { // this triger renames the call line item id to be // the specified inventory item name or the product name List<Call_Line_Item__c> callItems = new List<Call_Line_Item__c>(); callItems = Trigger.new; for (Call_Line_Item__c callItem : callItems) { //check if inventory or product was specified if (callItem.Inventory_Item__c <> NULL) { callItem.Name = callItem.Inventory_Item__r.Name; callItem.Name = 'inv item name'; } else if (callItem.Products__c <> NULL) { callItem.Name = callItem.Products__r.Name; } } update callItems; }

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
aalbertaalbert
Remove the update DML statement at the end. By using the "before" trigger to modify the Trigger.new objects, you don't need to explicitly perform an update DML statement. When the trigger ends, it will implicitly update the data as you have modified the values.
vickySFDCvickySFDC 

Hi All,

This two VF tags I am really confusing

Can anyone give examples <apex:actionsupport> and <apex:actionfunction> tags and give some examples?

 

 

Thanks,

 

Vicky

Best Answer chosen by Admin (Salesforce Developers) 
asish1989asish1989

HI

A component that provides support for invoking controller action methods directly from JavaScript code using an AJAX request. An <apex:actionFunction> component must be a child of an<apex:form> component.

 

Used when we need to perform similar action on varioud events. Een though you can use it in place of actionSupport as well where only event is related to only one control.

Example

<!-- Page: -->
	<apex:page controller="exampleCon">
	<apex:form>
		<!-- Define the JavaScript function sayHello-->
		<apex:actionFunction name="sayHello" action="{!sayHello}" rerender="out"
		status="myStatus"/>
	</apex:form>
	
	<apex:outputPanel id="out">
		<apex:outputText value="Hello "/>
		<apex:actionStatus startText="requesting..." id="myStatus">
		<apex:facet name="stop">{!username}</apex:facet>
		</apex:actionStatus>
	</apex:outputPanel>
	
	<!-- Call the sayHello JavaScript function using a script element-->
	<script>window.setTimeout(sayHello,2000)</script>
	<p><apex:outputText value="Clicked? {!state}" id="showstate" /></p>
	<!-- Add the onclick event listener to a panel. When clicked, the panel triggers
	the methodOneInJavascript actionFunction with a param -->
	<apex:outputPanel onclick="methodOneInJavascript('Yes!')" styleClass="btn">
		Click Me
	</apex:outputPanel>
	
	<apex:form>
		<apex:actionFunction action="{!methodOne}" name="methodOneInJavascript"
		rerender="showstate">
			<apex:param name="firstParam" assignTo="{!state}" value="" />
		</apex:actionFunction>
	</apex:form>
</apex:page>

/*** Controller ***/
public class exampleCon {
	String uname;
	public String getUsername() {
		return uname;
	}
	public PageReference sayHello() {
		uname = UserInfo.getName();
		return null;
	}
	public void setState(String n) {
		state = n;
	}
	public String getState() {
		return state;
	}
	public PageReference methodOne() {
		return null;
	}
	private String state = 'no';
}

 

.ActionSupport : A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by theserver when a particular event occurs, such as a button click or mouseover.

 

Used when we want to perform an action on a perticular eventof any control like onchange of any text box or picklist.

 

Example

<apex:page controller="exampleCon">
	<apex:form>
		<apex:outputpanel id="counter">
			<apex:outputText value="Click Me!: {!count}"/>
				<apex:actionSupport event="onclick"
				action="{!incrementCounter}"
			rerender="counter" status="counterStatus"/>
		</apex:outputpanel>
		
		<apex:actionStatus id="counterStatus"
			startText=" (incrementing...)"
			stopText=" (done)"/>
	</apex:form>
</apex:page>


/*** Controller: ***/
public class exampleCon {
	Integer count = 0;
	public PageReference incrementCounter() {
		count++;
		return null;
	}
	public Integer getCount() {
		return count;
	}
}

 If this post answers your questions please mark it as solved and hit kudos button if it helps you

 

Thanks

 

PronowPronow 

Hello there,

 

In my project, on an object I have two fields. One is an auto-update and other is a formula field. Auto-update field contains 'Current Date' value ( 'TODAY()' ). Formula field is number type, calculating difference in days between a custom DATE field and above auto-update DATE field.

 

I am trying to trigger, a workflow rule that will fire when value of formula field would be 30 or 60.

 

Please help me out as the workflow is not getting triggered when the above formula evaluates to true.

 

Thank you in advance.

Best Answer chosen by Admin (Salesforce Developers) 
PronowPronow

Thank you for your response.

 

However, I guess you did not get the actual problem that I faced. The workflow is supposed to fire when the auto-update field i.e. Current date will change. The other field is formula field calculating No. of days between two dates. One is Cutom date field and other is Current date.

 

Even if I try to fire a workflow to update either Current date or No. of days, you need to update that particular record.

 

So, as a conclusion I found a solution to write a Schedular that will fire everyday, and it will calculate no. of days and update it. This will cause all dependent workflows to fire.

 

I implemented this solution in my project, and its working fine and uninterrupted now.

 

Thank you for your knowledge sharing.