function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dhananjay Patil 12Dhananjay Patil 12 

Retrieve the data fro User Object Custom field and Display it to the Task custom Field using Apex Class

Hi,

I have a requirement inwhich There is a field of type Picklist "BU__C" which is present on both User and Task object.Now when a user create a contact record,when he creates a task,value of "BU__C" of User should be stamp to the "BU__C" in Task.
e.g.If Value "BU__c" of user is "ABC" then in task "BU__C" must be stamp with the value as "ABC".

I have to solve this by writing a apex class not a trigger.
Can somebody help me how to do it via apex sharing class?
It would be better if it explains with example
Best Answer chosen by Dhananjay Patil 12
Mahesh DMahesh D
Hi Dhananjay,

Please check the below code:

Here I considered:

(1) Alignment.
(2) Corrected the logic.
(3) Saved it in my DE environment and saved without any errors.
public with sharing class TaskUpdateActivityInfo {    
  
    public static void taskEmailConnection(List<Task> tasksForProcessing) {
        User u = [Select Id, Name, BusinessUnit__c from User where Id =: UserInfo.getUserId()];
        for(Task task : tasksForProcessing) {
            if(String.valueOf(task.Subject).startsWith('Email:')) {
                //task.BusinessUnit__c ='ABC';
                task.BusinessUnit__c =u.BusinessUnit__c;
            }
        }    
    }    
}

Please do let me know if it helps you.

Regards,
Mahesh

All Answers

Mahesh DMahesh D
Hi Dhananjay,

Could please exmplain more about 'only in class but not in trigger'.

Where is your class called from?

If you have any existing code then paste it here so that it will be easy to help you.

Regards,
Mahesh
Dhananjay Patil 12Dhananjay Patil 12
Mahesh I have already created a trigger.in that trigger I am calling a class that I created by providing a method.In the method of a class I have to write a code..

Trigger:​

trigger TaskTrigger on Task (before insert, after insert, after update) {

 if(trigger.isBefore) {

         if(trigger.isInsert) {

                TaskUpdateActivityInfo.taskEmailConnection(trigger.new);
             
                   }
    }

Class:

public with sharing class TaskUpdateActivityInfo {    
  
  public static void taskEmailConnection(List<Task> tasksForProcessing) {
    for(Task task : tasksForProcessing) {

            if(String.valueOf(task.Subject).startsWith('Email:'))

               {
                //task.BusinessUnit__c ='ABC';
                task.BusinessUnit__c =user.BusinessUnit__c;
                }
        }
    
    }
    
}



if u see here In this class I have a requirement when task is created then I have to update  custom field "BUsinessUnit__c" with the value of "BusinessUnit__c" of user.
I did hardcoding before and it is working fine but i have ta assign task.BusinessUnit__c =user.BusinessUnit__c like that 
but is is not giving any value.. I am stuck here..
Please help me to improve this code
 
Mahesh DMahesh D
Hi Dhananjay,

Please check the below code:

Here I considered:

(1) Alignment.
(2) Corrected the logic.
(3) Saved it in my DE environment and saved without any errors.
public with sharing class TaskUpdateActivityInfo {    
  
    public static void taskEmailConnection(List<Task> tasksForProcessing) {
        User u = [Select Id, Name, BusinessUnit__c from User where Id =: UserInfo.getUserId()];
        for(Task task : tasksForProcessing) {
            if(String.valueOf(task.Subject).startsWith('Email:')) {
                //task.BusinessUnit__c ='ABC';
                task.BusinessUnit__c =u.BusinessUnit__c;
            }
        }    
    }    
}

Please do let me know if it helps you.

Regards,
Mahesh
This was selected as the best answer
Dhananjay Patil 12Dhananjay Patil 12
Hi Mahesh,
Thank you so much for the solution..This is working as expected.
Actually I am new to teh apex programming after creating a class I have to create a test for this.
Can u give me some hints reg. how to write a test class.Because I have never written a test class before...
 
Mahesh DMahesh D
Hi Dhananjay,

Please find the test class for your class:
 
@isTest
public class TaskUpdateActivityInfoTest {
    @isTest
    public static void testMethodOne() {
    
        Task tas = new Task();
        tas.Subject = 'Email:';
        insert tas;
    }
}

Please check below post for test classes.
1) https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

Please follow below salesforce Best Practice for Test Classes :

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process.

Regards,
Mahesh
Dhananjay Patil 12Dhananjay Patil 12
Than You So Much Mahesh for this knowledge.Really thankful of your help..
Dhananjay Patil 12Dhananjay Patil 12
Hi Mahesh,
I have modified test class code as follow:
public class TaskUpdateActivityInfoTest {
    @isTest
    public static void testInsertTask() {
        
        Profile p=[Select Id from Profile where Name='Standard User'];
        //Role r=[Select Id from Role];
    user u=new user(LastName='Test' , Alias = 'stdusr', Email='standarduser@test.com',UserName='standarduser123@test.com',CommunityNickname='tst',GlobalId__c='12345678',EmailEncodingKey='UTF-8', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id,TimeZoneSidKey='Europe/Paris',BusinessUnit__c='BDX');
   System.assertEquals(u.BusinessUnit__c,'BDX');
    System.RunAs(u)
    {
    test.startTest();
        Task myTask = new Task();
        myTask.Subject = 'Email:';
        myTask.BusinessUnit__c= u.BusinessUnit__c;
        insert myTask;
        test.stopTest();
    }
    }
}


In Apex Class I am assigning User Business Unit value to task Business Unit Value.If i want to comapre the same in test class how can I comapre it?
where do I add System.assertEquals().
Right now below code is running and code coverage is done to 85%...