• Amit Chaudhary 8
  • ALL STAR
  • 34076 Points
  • Member since 2014
  • Salesforce CRM Consultant


  • Chatter
    Feed
  • 1023
    Best Answers
  • 1
    Likes Received
  • 30
    Likes Given
  • 3
    Questions
  • 4842
    Replies
So, I'm new to Apex and Visualforce, and I have a unique problem that I am sure is indicative of the fact that I am a rookie at this envrionment. The code executes correctly when using 'Visualforce' but not with my Apex Test Class. Since I've only been working with Apex and Visualforce for two weeks now, I'm sure its because there is something that I am not clear about. Please find below my Visualforce code, my Controller code and my Test class. I'm only having a problem with testing the Delete code in the Apex class. I can't seem to get the correct 'ID' to pass through so that the row is subsiquently deleted from Salesforce. The 'Null' portion of the Delete in the Controller tests with the Test class, but the deletion of the row inserted does not. Any help would be greatly appreciated. Thanks!

VISUALFORCE CODE 
<apex:page standardController="Request__c" extensions="TrController" >
    <!-- The following code will fix a problem with the calendar autospawning when the time entries are displayed. -->
    <script>
        function setFocusOnLoad(){ Coment.focus(); }
    </script>
   
    <!--Because we will be defining 'Input' fields, we must wrap our code in a 'Form' block. -->
    <apex:form id="Time_Entry_Form">
        <apex:pageBlock title="CDCR - Salesforce Time Reporting for Requests" id="Time_Entry_List">
           
            <!-- The following pageBlockButtons segment defines the two buttons that appear at the top of the Time entry form. -->
            <apex:pageBlockButtons id="Button_area">
                <!-- The following Button is defined in a more complicated fashion so that a parameter can be passed. -->
                <apex:commandLink >
                    <a href="javascript: CurrRequest('{!Request__c.Id}');" class="btn">New</a>               
                </apex:commandLink>
               
                <apex:commandLink >
                    <a href="javascript: SaveEntry();" class="btn">Save</a>               
                </apex:commandLink>

            </apex:pageBlockButtons>
           
             <!-- The following pageBlockTable segment defines the time entry rows that will be displayed. -->
            <apex:pageBlockTable value="{!TimeEntries}" var="entry" id="Entry_Table_List">
                <apex:column width="45" headerValue="Action">
                    <a href="javascript:if (window.confirm('Are you sure?')) DeleteEntry('{!entry.Id}');" style="font-weight:bold">Del</a>               
                </apex:column>   
                <apex:column width="70" headerValue="Activity">
                    <apex:inputField value="{!entry.Activity__c}"/>
                </apex:column>   
                <apex:column width="70" headerValue="Date Worked">
                    <apex:inputField value="{!entry.Date_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Hours">
                    <apex:inputField value="{!entry.Hours_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Worked">
                    <apex:inputField value="{!entry.Minutes_Worked__c}"/>
                </apex:column>   
                <apex:column headerValue="Work Description">
                    <apex:inputField style="width:100%" value="{!entry.Work_Description__c}" id="comment"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <!-- This action block is executed based on the 'Delete' button being clicked on. -->
        <apex:actionFunction action="{!del}" name="DeleteEntry" reRender="Time_Entry_List">
            <apex:param name="deleteEntryID" value="" assignTo="{!SelectedEntryID}"/>
        </apex:actionFunction>
       
         <!-- This action block is executed based on the 'New' button being clicked on. -->
        <apex:actionFunction action="{!add}" name="CurrRequest" reRender="Time_Entry_List">
            <apex:param name="addEntryID" value="" assignTo="{!ReqID}"/>
        </apex:actionFunction>

         <!-- This action block is executed based on the 'Save' button being clicked on. -->
        <apex:actionFunction action="{!save}" name="SaveEntry" reRender="Time_Entry_List"/>
       
     </apex:form>
    <!-- The following script code is used in order to fix the problem with the calendar autospawning. -->
    <script>
        var Coment=document.getElementById('{!$Component.theForm.block.sec.item.comment}');
    </script>   
</apex:page>

APEX CONTROLLER CLASS

public with sharing class TrController
{
    //This is the list for handling the group of time entries related to the parent object.
    public List<Time_Entry__c> TimeEntries {get;set;}
    //Used to get a hold of the entry record that is selected for deletion.
    public string SelectedEntryID {get;set;}
    //Used to get the parent request object ID from the Visual force page to the controller.
    public string ReqID {get;set;}
    public TrController(ApexPages.StandardController controller)
    {
        //Obtain the parent object Id from the the visualforce form.
        ReqId = Apexpages.currentPage().getparameters().get('Id');
        //SelectedEntryId = Apexpages.currentPage().getparameters().get('deleteEntryId');
        //Call the loaddata method to laod the time entries related to the parent object.
        LoadData();
     }
    public void LoadData()
    {
        //Obtain the first 15 bytes of the Parent Object ID to use for record selection.
        string RequestID = ReqId.substring(0, 15);
        //Load the related time entry records from the database.
        TimeEntries = [select id, Activity__c, Date_Worked__c, Hours_Worked__c, Minutes_Worked__c, Work_Description__c from Time_Entry__c WHERE Related_Object__c=:RequestID order by ID DESC];

    }
    public void save()
    {
        //Update the Salesforce database with the data entred.
        update TimeEntries;
    }
    public void add()
    {  
       //Obtain the first 15 bytes of the Parent Object ID to use for record identification.
        string RequestID = ReqId.substring(0, 15);
        //Build the default values to the new time entry record.
        Time_Entry__c entry = new Time_Entry__c(Activity__c='Research', Date_Worked__c=System.today(), Hours_Worked__c=' 0', Minutes_Worked__c='00', Related_Object__c=RequestID);
        //Insert the new default time entry row into the Salesforce database.
        Insert entry;
        //Call the method to reload the Visualforce list.
        LoadData();
    }
    public void del()
    {
     ExecuteDelete(SelectedEntryId);
    }
    public void ExecuteDelete(string selectedEntry)
    {
        //if we are missing the reference, then do nothing except return.
        if (selectedEntry == null)
        {
            return;
        }
        
        //If the record is within the collection, then delete it.
        Time_Entry__c tobeDeleted = null;
        for(Time_Entry__c a : TimeEntries)
        {
            string EntID = a.Id;
            string SelId = EntId.substring(0, 15);
        if (EntID == selectedEntry)
            {
                tobeDeleted = a;
                break;
            }
        }   
        //If account record found then delete it.
        if (tobeDeleted != null)
            {
                Delete toBeDeleted;
            }
        //Refresh the list
        LoadData();

    }

}

APEX TEST CLASS

@isTest
public class TrControllerTest
{
 static testMethod void testMethod1()
 {
  
    //Instantiate a new instance of the Custom Request Object.
        Request__c ReqObj = new Request__c();
    //Populate the name of the new request object.
        ReqObj.Name = 'Test request';
    //Populate 'What is being requested.
        ReqObj.What_is_being_requested__c = 'Entry to test apex code.';
    //Insert the new request object into Salesforce.
  insert ReqObj;             
  
 //Instantiate a new instance of the Time_Entry object.
  Time_Entry__c te = new Time_Entry__c();
    //Populate the required fields of the Time Entry object.
  te.Name ='Test';            
        te.Date_Worked__c = System.today();
        te.Hours_Worked__c = '01';
        te.Minutes_Worked__c = '15';
        te.Work_Description__c = 'This is a test entry';
        te.Activity__c = 'Research';
    //Insert the new Time_Entry object into Salesforce.
  insert te;              
  
    //Indicate the starting of the test process.
        Test.StartTest();
 
    //Post the Request ID of the Request object created.
            Apexpages.currentPage().getparameters().put('id', String.valueOf(ReqObj.Id));
    //Instantiate a new instance of the Request object standard controller.
       ApexPages.StandardController sc = new ApexPages.StandardController(ReqObj);
    //Instantiate a new instance of the Time Entry Controller that is related to the Standard controller.
        TrController testAccPlan = new TrController(sc);
   
    //Test the code within the 'save' method.
            testAccPlan.save(); 
    //Test the code within the 'add' method.
         testAccPlan.add();           
         //System.AssertEquals(NewEntryId, ReqObj.Id);
            
 //Obtain the object Id's for the row inserted in the database initially.    
         List<Time_Entry__c> deleteEntry = [select id from Time_Entry__c WHERE Work_Description__c = 'This is a test entry'];

 //Loop through the objects returned from the 'Select' statement and pass the Object Id's to the 'ExecuteDelete' class.    
        for(Time_Entry__c a : deleteEntry)
            {
                testAccPlan.ExecuteDelete(a.Id);
                //Leave the loop after one itteration.
                break;
            }
    
    //Execute the ExecuteDelete class with a 'Null' variable so that the additionally related code is tested.
        testAccPlan.ExecuteDelete(null);
  
    //Indicate the end of the test code.
        Test.StopTest();
 }
}
Hello,

I have a workflow Rule with a field update attached with it.

The workflow entry criteria for workflow is as below:
AND( 
AND($Profile.Name <> 'Profile 1',$Profile.Name <> 'Profile 2',$Profile.Name <> 'Profile 3',$Profile.Name <> 'Profile 4',$Profile.Name <> 'Profile 5'), 
NOT(ISBLANK(customField__1)), 
Or( 
ISCHANGED( customField__1 ), 
ISNEW() ) 
)
I want to execute the workflow if it doesnot belong to certain profile
Profile 1 to Profile 5

the fielld update is not working as i want because of entry criteria.

Am i going wrong anywhere ?


 
So I have a Visualforce page that I have created that is related to a standard controller and also an extension to an 'Apex' controller. I've taken the 'Trailhead' training on testing an Apex class, but I can't seem to successfully apply what I learned in the Trailhead tutorial to my project and get there to not be syntax errors in my test code. I have only working on my first Visualforce/Apex project for a week now, so I'd sure welcome any suggestions anyone might have. The primary Methods that I am calling from the Visualforce Page are 'Save', 'Add' and 'Delete', so any help in any of those methods that I could then apply to the others would be greatly appreciated.

VISUALFORCE CODE:
<apex:page standardController="Request__c" extensions="TrController" >
    <!-- The following code will fix a problem with the calendar autospawning when the time entries are displayed. -->
    <script>
        function setFocusOnLoad(){ Coment.focus(); }
    </script>
   
    <!--Because we will be defining 'Input' fields, we must wrap our code in a 'Form' block. -->
    <apex:form id="Time_Entry_Form">
        <apex:pageBlock title="CDCR - Salesforce Time Reporting for Requests" id="Time_Entry_List">
           
            <!-- The following pageBlockButtons segment defines the two buttons that appear at the top of the Time entry form. -->
            <apex:pageBlockButtons id="Button_area">
                <!-- The following Button is defined in a more complicated fashion so that a parameter can be passed. -->
                <apex:commandLink >
                    <a href="javascript: CurrRequest('{!Request__c.Id}');" class="btn">New</a>               
                </apex:commandLink>
               
                <apex:commandLink >
                    <a href="javascript: SaveEntry();" class="btn">Save</a>               
                </apex:commandLink>

            </apex:pageBlockButtons>
           
             <!-- The following pageBlockTable segment defines the time entry rows that will be displayed. -->
            <apex:pageBlockTable value="{!TimeEntries}" var="entry" id="Entry_Table_List">
                <apex:column width="45" headerValue="Action">
                    <a href="javascript:if (window.confirm('Are you sure?')) DeleteEntry('{!entry.Id}');" style="font-weight:bold">Del</a>               
                </apex:column>   
                <apex:column width="70" headerValue="Activity">
                    <apex:inputField value="{!entry.Activity__c}"/>
                </apex:column>   
                <apex:column width="70" headerValue="Date Worked">
                    <apex:inputField value="{!entry.Date_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Hours">
                    <apex:inputField value="{!entry.Hours_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Worked">
                    <apex:inputField value="{!entry.Minutes_Worked__c}"/>
                </apex:column>   
                <apex:column headerValue="Work Description">
                    <apex:inputField style="width:100%" value="{!entry.Work_Description__c}" id="comment"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <!-- This action block is executed based on the 'Delete' button being clicked on. -->
        <apex:actionFunction action="{!del}" name="DeleteEntry" reRender="Time_Entry_List">
            <apex:param name="EntryID" value="" assignTo="{!SelectedEntryID}"/>
        </apex:actionFunction>
       
         <!-- This action block is executed based on the 'New' button being clicked on. -->
        <apex:actionFunction action="{!add}" name="CurrRequest" reRender="Time_Entry_List">
            <apex:param name="EntryID" value="" assignTo="{!ReqID}"/>
        </apex:actionFunction>

         <!-- This action block is executed based on the 'Save' button being clicked on. -->
        <apex:actionFunction action="{!save}" name="SaveEntry" reRender="Time_Entry_List"/>
       
     </apex:form>
    <!-- The following script code is used in order to fix the problem with the calendar autospawning. -->
    <script>
        var Coment=document.getElementById('{!$Component.theForm.block.sec.item.comment}');
    </script>   
</apex:page>

CONTROLLER APEX CODE

public with sharing class TrController
{
    //This is the list for handling the group of time entries related to the parent object.
    public List<Time_Entry__c> TimeEntries {get;set;}
    //Used to get a hold of the entry record that is selected for deletion.
    public string SelectedEntryID {get;set;}
    //Used to get the parent request object ID from the Visual force page to the controller.
    public string ReqID {get;set;}
    public TrController(ApexPages.StandardController controller)
    {
        //Obtain the parent object Id from the the visualforce form.
        ReqId = Apexpages.currentPage().getparameters().get('Id');
        //Call the loaddata method to laod the time entries related to the parent object.
        LoadData();
     }
    public void LoadData()
    {
        //Obtain the first 15 bytes of the Parent Object ID to use for record selection.
        string RequestID = ReqId.substring(0, 15);
        //Load the related time entry records from the database.
        TimeEntries = [select id, Activity__c, Date_Worked__c, Hours_Worked__c, Minutes_Worked__c, Work_Description__c from Time_Entry__c WHERE Related_Object__c=:RequestID order by ID DESC];

    }
    public void save()
    {
        //Update the Salesforce database with the data entred.
        update TimeEntries;
    }
    public void add()
    {  
       //Obtain the first 15 bytes of the Parent Object ID to use for record identification.
        string RequestID = ReqId.substring(0, 15);
        //Build the default values to the new time entry record.
        Time_Entry__c entry = new Time_Entry__c(Activity__c='Research', Date_Worked__c=System.today(), Hours_Worked__c=' 0', Minutes_Worked__c='00', Related_Object__c=RequestID);
        //Insert the new default time entry row into the Salesforce database.
        Insert entry;
        //Call the method to reload the Visualforce list.
        LoadData();
    }
    public void del()
    {   
        //if we are missing the reference, then do nothing except return.
        if (SelectedEntryId == null)
        {
            return;
        }
        
        //If the record is within the collection, then delete it.
        Time_Entry__c tobeDeleted = null;
        for(Time_Entry__c a : TimeEntries)
        if (a.Id == SelectedEntryId)
            {
                tobeDeleted = a;
                break;
            }
        //If account record found then delete it.
        if (tobeDeleted != null)
            {
                Delete toBeDeleted;
            }
        //Refresh the list
        LoadData();

    }

}

Thank you in advance for your time.

Eric Anderson 
Hi,

I tried test the example of the below link, and the gauge is not displaying on the page.
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_charting_appearance_gauge_charts.htm

Can someone share an example of a gauge chart with apex code?

Thanks
Rafael
Hello, 
I don't know how to write test code for list method! Hear, i am giving you my original apex class,

APEX Class:

public class Accountant_Profil {
    
    public List<User> getUser(){
        
      return [Select FirstName, LastName, Username, Email, UserRole.Name, Profile.Name, SmallPhotoUrl From User WHERE FirstName = 'Dharam'];
        
    }

    public List<PermissionSetAssignment> getPermissionSetAssignment(){
        
        return [ SELECT PermissionSet.Description, PermissionSet.Name FROM PermissionSetAssignment  WHERE Assignee.Name = 'Dharam Makvana' ];
    
    }
    
    public List<ObjectPermissions> getObjectPermissions(){

        List<ObjectPermissions> Acc =  [SELECT SObjectType, PermissionsRead, PermissionsCreate, PermissionsDelete, PermissionsEdit, PermissionsModifyAllRecords, PermissionsViewAllRecords, Parent.Name FROM ObjectPermissions WHERE (ParentId IN (SELECT PermissionSetId FROM PermissionSetAssignment WHERE Assignee.Name = 'Dharam Makvana'))];
         return Acc;
    }

}

Please Help Me.
Thanks
trigger DuplicateService on Site__c (before insert) {
    for(Site__c  B : Trigger.New) {
        try {
            Integer i = [SELECT count() FROM Site WHERE Account__c = :B.Account__c AND RecordTypeId = :B.RecordTypeId];

            if (i > 0) {
            String RT = [SELECT Name FROM RecordType WHERE Id = :B.RecordTypeId].Name;
            String TS = [SELECT Name FROM Site__c WHERE Account__c = :B.Account__c AND RecordTypeId = :B.RecordTypeId].Name;
               B.addError('Already existing ' + RT + ': <<<' + TS + '>>>, !!');
            }
        }
        catch (DmlException e) {
            System.debug('Trigger DuplicateService: ' + e.getMessage());
        }
    }
}

 
Hi,
I'm trying to see why my test code is failing for when I try to create a custom object off our Opportunities. Running this will only give me 4%. Any help would be greatly appreciated!

Here's the class:
public with sharing class triggerLogic_Opportunity { 

        public static void createProject(List<Opportunity> newOpportunities){
        Set<ID> opportunityIDs = new Set<ID>();
            
        // Check for qualifying opportunities.
        for(Opportunity o : newOpportunities){
            if(o.StageName == 'Closed Won' && o.Type == 'New Business' && o.Setup_Opportunity_Created__c == false){
                opportunityIDs.add(o.id);
                           
            }
        }
        try{
            if(opportunityIDs.size() > 0){
            List<Opportunity> createProjectsFor = opportunityQuery(opportunityIDs);
            List<Milestone1_Project__c> projectsCreated = new List<Milestone1_Project__c>();
            List<Milestone1_Milestone__c> mainMilestones = new List<Milestone1_Milestone__c>();
            Group pUserForOwnerID = [SELECT Id FROM GROUP WHERE Name = 'Sales Operations Queue' AND TYPE = 'QUEUE'];
            
            
           
            //supportLogic_Dates sld = new supportLogic_Dates();
            
            for(Opportunity o : createProjectsFor){
                // Create projects
               
                o.Setup_Opportunity_Created__c = true;
                Milestone1_Project__c project = new Milestone1_Project__c();
                project.Name = o.Name + ' New Account Setup';
                //project.Status__c = 'Agreement Signed';
                //project.Project_Type__c = 'New Account Setup';
                project.Opportunity__c = o.Id;
                project.Kickoff__c = Date.today();
                project.Date_Time_Opened__c = system.now();
                project.Deadline__c = supportLogic_Dates.addBusinessDays(Date.today(), 5);
                project.OwnerId = pUserForOwnerID.Id;
                projectsCreated.add(project);
            }                   
                    
                
            insert(projectsCreated);
            update(createProjectsFor);  
            // Add Main Milestones to each project.
            for(Milestone1_Project__c p : projectsCreated){
                // Create Setup Milestone
                Milestone1_Milestone__c mainMilestone1 = new Milestone1_Milestone__c();
                mainMilestone1.Name = 'Implementation Call';
                mainMilestone1.Project__c = p.id;
                mainMilestone1.Date_Time_Opened__c = system.now();
                mainMilestone1.Kickoff__c = Date.today();
                mainMilestone1.Stage__c = 'Stage 1';
                mainMilestone1.Deadline__c = supportLogic_Dates.addBusinessDays(Date.today(), 4);
                mainMilestones.add(mainMilestone1);
 
                Milestone1_Milestone__c mainMilestone2 = new Milestone1_Milestone__c();
                mainMilestone2.Name = 'Packages';
                mainMilestone2.Project__c = p.id;
                mainMilestone2.Date_Time_Opened__c = system.now();
                mainMilestone2.Kickoff__c = Date.today();
                mainMilestone2.Stage__c = 'Stage 2';
                mainMilestone2.Deadline__c = supportLogic_Dates.addBusinessDays(Date.today(), 4);
                mainMilestones.add(mainMilestone2);
                
                Milestone1_Milestone__c mainMilestone3 = new Milestone1_Milestone__c();
                mainMilestone3.Name = 'Users';
                mainMilestone3.Project__c = p.id;
                mainMilestone3.Date_Time_Opened__c = system.now();
                mainMilestone3.Kickoff__c = Date.today();
                mainMilestone3.Stage__c = 'Stage 3';
                mainMilestone3.Deadline__c = supportLogic_Dates.addBusinessDays(Date.today(), 4);
                mainMilestones.add(mainMilestone3);
                
  
            }   
            
            insert(mainMilestones);
            
        }
        }Catch(Exception ex){
            new Opportunity().addError('Issue in creating associated project.');
            new Milestone1_Project__c().addError('Issue in creating associated project.');
        }
        
        
            
    }
    
    public static List<Opportunity> opportunityQuery(Set<ID> queryThese){
        String pqString = supportLogic_SOQL.getAllObjectFields('Opportunity', 'ID IN :queryThese');
        List<Opportunity> theseCases = (List<Opportunity>)database.query(pqString);
        return(theseCases);
    } 
}

And here's the test code:
 
@isTest
private class test_triggerLogic_Opportunity { 
   static testmethod void testCreateProject(){
        // Create a new opportunity
        Opportunity testOpportunity = new Opportunity();
        Opportunity testOpportunityClone = new Opportunity();
        final ID opportunitiesStandardRTID =  supportLogic_RT.getRTId('Standard', 'Opportunity');
        System.debug('STANDARD RECORD TYPE ID: >>>> + opportunitiesStandardRTID');
        
        testOpportunity.Name = 'Project Test Opportunity';
        testOpportunity.RecordTypeID = opportunitiesStandardRTID;
        testOpportunity.type = 'New Business';
        testOpportunity.StageName = 'Qualification';
        testOpportunity.LeadSource = 'Web';
        testOpportunity.CloseDate = date.parse('09/25/1990');
        testOpportunity.Probability = 10;
        testOpportunity.NextStep = 'Nothing';
        insert(testOpportunity);
        
        // This is to throw an exception for 100% code coverage.
        testOpportunityClone.Name = 'Duplicate Test Opportunity';
        testOpportunityClone.RecordTypeID = opportunitiesStandardRTID;
        testOpportunityClone.type = 'New Business';
        testOpportunityClone.StageName = 'Qualification';
        testOpportunityClone.LeadSource = 'Web';
        testOpportunityClone.CloseDate = date.parse('09/25/1990');
        testOpportunityClone.Probability = 10;
        testOpportunityClone.NextStep = 'Nothing';
        insert(testOpportunityClone);
           
        } 
}

 
trigger DuplicateService on Site__c (before insert) {
    for(Site B : Trigger.New) {
        try {
            Integer i = [SELECT count() FROM Site WHERE Account__c = :B.Account__c AND RecordTypeId = :B.RecordTypeId];

            if (i > 0) {
            String RT = [SELECT Name FROM RecordType WHERE Id = :B.RecordTypeId].Name;
            String TS = [SELECT Name FROM Site__c WHERE Account__c = :B.Account__c AND RecordTypeId = :B.RecordTypeId].Name;
               B.addError('Already existing ' + RT + ': <<<' + TS + '>>>, !!');
            }
        }
        catch (DmlException e) {
            System.debug('Trigger DuplicateService: ' + e.getMessage());
        }
    }
}

 
Hi All!

We have a trigger to prevent users from deleting events in salesforce:

Trigger PreventDelete on Event (before delete)

{Profile adminId = [SELECT Id from Profile where Name='System Administrator' LIMIT 1];if(System.Trigger.IsDelete && UserInfo.getProfileId() != adminId.Id)
      {
    for(Event tsk : Trigger.old)
    {
      tsk.addError('Meetings can not be deleted.  Please mark as Cancelled or reschedule to a different day/time.');
    }
 }
 }

But I cannot deploy it because it has 0% code coverage.  I am guessing I need a test class but do not know how to do that.  Can anyone help?  Thanks!
I have a class that fixes sandbox user emails and a test class that inserts users than calls the method to fix the emails. This code works if I just run it but  cant get it to work on the test data. Anything Im missing? It fails on the assert.
 
//Fix emails of the admin users on the sandboxs automatically
public class FixSandboxUsers {
    @future
    public static void FixUsers(){
        //make sure its a sandbox enviroment
        if([SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox){
            //get the system admin profile
            Profile p = [Select id, name from Profile where name='System Administrator' limit 1];
            //check users with that profile
            List<User> use = [Select id, name, email, Profileid from user where profileid = :p.id];
            //update each users email
            for(User u : use){
                u.email = u.Email.replace('=','@').replace('@example.com','');
                //debug print out the email
               // System.debug(u.Email);
            }
            //update the users
            update use;
        }
    }
}
@isTest
public class FixSandboxUsers_Test {
    @isTest
    public static void FixUsers_Test(){
        Profile profileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];
        List<User> userList = new List<User>();
        for(integer i = 0; i < 10; i++){
            userList.add(new User(LastName = 'LIVESTON' + i,
                                FirstName='JASON' + i,
                                Alias = 'jliv' + i,
                                Email = 'TESTADDRESS' + i + '=asdf.com@example.com',
                                Username = 'TESTADDRESS' + i + '@asdf.com',
                                ProfileId = profileId.id,
                                TimeZoneSidKey = 'GMT',
                                LanguageLocaleKey = 'en_US',
                                EmailEncodingKey = 'UTF-8',
                                LocaleSidKey = 'en_US'
                               ));
        }
        insert userList;
        Test.startTest();
        FixSandboxUsers.FixUsers();
        Test.stopTest();
        For(User u : userList){
            System.debug(u.Email);
            System.assert(!u.email.contains('='));
            System.assert(!u.email.contains('@example.com'));
           
        }
       
    }
}


 
Not able to figure out what's wrong with this trigger.  
 
trigger DuplicateEmail on Contact (before insert, before update) {

map<string, contact> conmap =  new map<string, contact> ();

   for(contact con : trigger.new)
   
      {
        if(con.email!=null){
        
        conmap.put(con.email, con);
        
        }
      
     }
     
     
 map<string, contact> emailmap = new map<string, contact> ([select email, id from contact where email IN: conmap.keyset() limit 1]);    
 

 
      for(contact c : trigger.new)
      
      {
      
      
      
     if(emailmap.get(c.email) !=null)
      
      {
        c.email.adderror('this is duplicate email');
      }
    
   
   }
     
     
     
}

 
I am writing my first trigger. Basically when a new sales opportunity with a company is created, I want the trigger to compare the product2Id of this opportunity with the product2Id from the assets of this company to check if I have saled this product to this company before. If so, I want to set the type of this opportunity to  "Existing_business".
This is my code:
User-added image
I am curious how should I start writing the test for trigger? Thanks in advance!
I am trying to do a summary a a custom time object we have for Cases. I have embded the VFP on a cases page layout. When people enter time, it groups together the person entering the time, and the amount they have billed. But I keep getting the 'List has more than 1 row for assignment to SObject' error. I am not sure why, this query will 99% percent of the time have more than 1 record (or more than 1 person entering records) because of how our cases work. Why cant I display more than 1 record? Other Programs we have made will return multipe records and then we loop through them on the VFP to display. Not sure why there is a limit on this program though. 

Code:
 
public class TimeSummaryController {
    public string caseid {get;set;}
     private final Case cc;
    public AggregateResult timeq {get;set;}
    public TimeSummaryController(ApexPages.StandardController stdController){
        this.cc = (Case)stdController.getRecord();
        
    }
    
    public AggregateResult getTimes(){
        try {
       	 timeq = [SELECT Engineer_Name__r.Name enr,SUM(Total_Billed__c)total_billed FROM Time__c WHERE Case__c = :cc.Id GROUP BY Engineer_Name__r.Name ORDER BY SUM(Total_Billed__c) DESC];
        }catch(Exception e){
            System.debug(e);
        	ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'No Time To Display'));
    		return null;        
        }
        return timeq;
    }
}
 
<apex:page standardController="Case" extensions="TimeSummaryController" showHeader="false">
    <apex:pageMessages ></apex:pageMessages>
    <apex:pageBlock>
   <apex:pageBlockTable value="{!Times}" var="tt" id="rr">
		
        <apex:column value="{!tt['enr']}"/>
       <apex:column value="{!tt['total_billed']}"/>

    </apex:pageBlockTable>
        </apex:pageBlock>
</apex:page>

 
I am trying to have a site that has a visualforce page allowing someone to upload an attachment with the new record that they are creating. I have the attachment passing at 95% code coverage but it doesn't seem to actually be uploading the attachment with the new record.

VF: 
<apex:pageBlockButtons >
    <apex:commandButton action="{!save}" value="Submit"/>
       <apex:commandButton action="{!cancel}" value="Cancel"/>
    </apex:pageBlockButtons>
    <apex:pageBlockSection title="Upload the Attachment" collapsible="false" dir="LTR" columns="1">
        <div id="upload" class="upload">                                   
            <apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>                            
        </div>
</apex:pageBlockSection>

Apex Class: 
public class dataSheetAttachment
{
    public Data_Feasibility_Request__c objdfr{get;set;}
    public Attachment myAttachment{get;set;}
    public string fileName{get;set;}
    public Blob fileBody{get;set;}

    public dataSheetAttachment(Apexpages.standardcontroller controller)
    {
        objdfr = (Data_Feasibility_Request__c)controller.getRecord();
        myAttachment = new Attachment();
    }
    public pagereference save()
    {
        if(myAttachment.Name == null)
        {
            insert objdfr;
        }
        if(myAttachment.Name != null)
        {
            insert objdfr;
            System.debug('@@@@@fileBody'+fileBody);    
            myAttachment = new Attachment();
            Integer i=0;
            myAttachment .clear();
            myAttachment.Body = fileBody;
            myAttachment.Name = fileName ;
            myAttachment.ParentId = objdfr.id;            
            insert myAttachment;   
        }             
       pagereference pr = Page.Thank_You;                          
       pr.setRedirect(true);
       return pr;
    }
}
Test Class: 
 
@isTest
private class Test_dataSheetAttachment {

public static testMethod void validatedataSheetAttachment() {        
    Data_Feasibility_Request__c myDFR = new Data_Feasibility_Request__c();
    dataSheetAttachment pageController = new dataSheetAttachment(new ApexPages.StandardController(myDFR));
  
    pageController.myAttachment.Name = 'foo';
    pageController.fileBody=Blob.valueOf('Body Test');
    pageController.fileName = 'Test';
    pageController.save();
  
    }

}



Wondering if someone might be able to help me figure out what I might be doing incorrect? 
I am getting below exception
Execution of BeforeInsert caused by: System.SObjectException: DML statement cannot operate on trigger.new or trigger.old: Class
I create a class which insert task for account object while creating task for a Lead object, below i hardcoded the account whatId. I created trigger for Task and call CreateTaskInAccount.createTask() from trigger, but its not happening like so.
Please share your feedback.

public class CreateTaskInAccount
{
 public void createTask(List<Task> TaskFromTrigger)
  {
  
    Account targetWhatId= [SELECT a.Id FROM Account a where a.Name='NishantAccount'];
    
    List<Task> tskList= new List<Task>();
    
    for(Task varTask: TaskFromTrigger)
    {
      Task tsk= new Task();
      
      tsk=varTask;
      tsk.WhatId=targetWhatId.Id;
            
                  
      tskList.Add(tsk);
    }
  
    Database.Insert(tskList);
  }
}
------------------------------------
trigger CreateTaskInAccount on Task (before insert, before update) {

  List<Task> lTask = new List<Task>();
  
    
  CreateTaskInAccount objAccount=new CreateTaskInAccount();
  objAccount.createTask(Trigger.new);
}

Tanks in advance
I'm very, very new to working with visual force and need to write a testclass for my controller below.  Could someone help get me started?  Many thanks in advance.

Best,
Collen
 
public class addMileageExpense {
public Expense_Report__c reports;
 public Mileage_expense__c del;
 public List<Mileage_expense__c> addexpenseList {get;set;}
 public List<Mileage_expense__c> delexpenseList {get;set;}
 public List<Mileage_expense__c> expenseList {get;set;}
 public Integer totalCount {get;set;}
 public Integer rowIndex {get;set;}
 public List<Mileage_expense__c> delexpense {get; set;} 
 public addMileageExpense(ApexPages.StandardController controller) {
 
 reports = (Expense_Report__c)controller.getRecord();
 expenseList = [Select id, Name, Expense_Report__c, Miles__c, Total_Miles__c,   
                Date__c, Prgm_1_Miles__c, Prgm_2_Miles__c, Prgm_3_Miles__c, Prgm_4_Miles__c, 
                Prgm_5_Miles__c, Prgm_6_Miles__c from Mileage_expense__c where Expense_Report__c =: reports.ID];
 totalCount = expenseList.size();
 
 delexpenseList = new List<Mileage_expense__c>();
 delexpense = new List<Mileage_expense__c>();
 }
 
 public void addRow(){
 addexpenseList = new List<Mileage_expense__c>();
 expenseList.add(new Mileage_expense__c(Expense_Report__c = reports.Id));
 }
 
 public PageReference ave(){
 
 upsert expenseList;
 delete delexpenseList;
 return (new ApexPages.StandardController(reports)).view();
 } 
 
 public void deleteRow(){
 
 rowIndex = Integer.valueOf(ApexPages.currentPage().getParameters().get('rowIndex'));
 System.debug('row to be deleted ' + rowIndex );
 System.debug('row to be deleted '+ expenseList[rowIndex]);

     del = expenseList.remove(rowIndex);
     If(del.Id <> null) {delexpenseList.add(del);}
         
 
     }
 }
 
 
Hello Everyone,

Greetings!!

I want know how SOQL subquery can be written in  REST explorer on workBench, for example, I have to fetch accounts and related contacts with the following SOQL query:

-> SELECT Id,Name,(SELECT Id,Name FROM Contacts) FROM Account

How this query could be written IB REST Explorer?

Please respond. Thanks in advance.

Regards
Aakanksha Singh
I want to check login user profile name without using $user.profileid in the formula field. I do not want to hardcode profile id as it differs from sandbox to production.
Hi,

Is it possible to access Field Service Lightning (Managed Package) - Service appointment object from SOQL?
I've tried [SELECT Id, Name FROM FSL__Service_Appointment];
[SELECT Id, Name FROM FSL__ServiceAppointment];
[SELECT Id, Name FROM FSL__Service_Appointment__c];
and plethora of other ways, but i always get: 

"sObject type 'FSL__ServiceAppointment__c' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names."
Line no 14 I am getting this error. "Type cannot be constructed: String" Please help me on this.
  1.    public String type_Z {get;set;} 
  2.     public List<String> authcookies {get;set;} 
  3.  
  4.     public JsonStringsss(JSONParser parser) {
  5.         while (parser.nextToken() != JSONToken.END_OBJECT) {
  6.             if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
  7.                 String text = parser.getText();
  8.                 if (parser.nextToken() != JSONToken.VALUE_NULL) {
  9.                     if (text == 'type') {
  10.                         type_Z = parser.getText();
  11.                     } else if (text == 'auth-cookies') {
  12.                         authcookies = new List<String>();
  13.                         while (parser.nextToken() != JSONToken.END_ARRAY) {
  14.                             authcookies.add(new String(parser));
  15.                         }
  16.                     } else {
  17.                         System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
  18.                         consumeObject(parser);
  19.                     }
  20.                 }
  21.             }
  22.         }
  23.     }
I got to know that , Salesforce has recently introduced the Platform Developer 1 certification (DEV450) to replace the Developer (DEV401) certification. All practitioners, with the DEV401 certification, must complete the DEV450 exam during 2016 to retain a Salesforce developer certification.

Is this true as i dnt not got any email from salesforce / webassessvor that if you will not give the DEV450 exam then your DEV401 certifcate will expire ?
 
When i am posting code "" is not printing. And Some code is removing automatically. 

Any idea . It look like some issue ?
External Lookup Relationship could now be setup between external objects and Salesforce object.
External Object - They are same as custom objects but used to map to data located outside Salesforce.
External object take data from External source and External source obviously has its own DB. 
To create external object : From Setup, click Develop | External Objects.
To create external Data source : Develop | External data source
 
I got to know that , Salesforce has recently introduced the Platform Developer 1 certification (DEV450) to replace the Developer (DEV401) certification. All practitioners, with the DEV401 certification, must complete the DEV450 exam during 2016 to retain a Salesforce developer certification.

Is this true as i dnt not got any email from salesforce / webassessvor that if you will not give the DEV450 exam then your DEV401 certifcate will expire ?
 
Hi All,

I'm trying to show an error message near the email field on visualforce page. Can I use ouputtext and innerhtml to display message?
Here is my code:

<apex:page id="thepage" controller="mySurvey">pt>
    <script type="text/javascript">
        var examNote = document.getElementsByClassName('examNote')[0].value;
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
        var validEmail = re.test(examNote);
             if(validEmail == false) {
             alert("email not valid"); //checking if the code is reaching here by an alert message
             //code to show the error message on vf page instead of alert
            
     </script>
    <apex:form id="audit">
        <apex:pageblock id="pb1" >
          <apex:pageblockSection id="pbs1" columns="1">
            <p><apex:inputText value="{!account}" label="Account"/></p>
            <apex:inputText id="Survey" value="{!txtSurvey}" label="SurveyName"/>
            <apex:inputText id="examNote" value="{!examNote}" Label="Exam Note" styleClass="examNote"/>
            <apex:outputText value="{0}">
                <apex:param value="result"/>
            </apex:outputText>
              <apex:commandButton action="{!save}" onclick="return validate();" value="save"/>
          </apex:pageblockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>
  • April 21, 2017
  • Like
  • 0
User-added image



 
trigger updateact on Account(before update) {
 List<ID> accs=new List<ID>();
    Map<Id,Account> oldMap=Trigger.oldMap;
    Map<Id,Account> newMap=Trigger.NewMap;
   for(Id aid:oldMap.keySet())
   {
        if(oldMap.get(aid).AccountNumber!=newMap.get(aid).AccountNumberr)
        {
     accs.AccountNumber.addError(' Please contact Master Data to make this change.');
       }
    }
 
}

 
Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Update failed. First exception on row 0 with id 0012800000vRs6sAAC; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Account Number is not numeric.: [AccountNumber]
  1. trigger EventTriggers on Event (after insert, after update) {
  2.     EventHandler.AddCampaginMember(trigger.new);
  3. }
Error Received:
"Challenge Not yet complete... here's what's wrong: 
The process did not set the correct Type value on submitting for approval"



Process Automation
Hey, 

I have a simple trigger that puts basic emailMessage data on the related parent case after the parent case is inserted. See the relevant trigger snippet below:
if (Trigger.isAfter)
	{
    List<case> cases=new List<Case>();
	List<EmailMessage> email=[select ToAddress, FromAddress, CcAddress, FromName from EmailMessage where ParentId IN : trigger.newMap.keyset() and Incoming = true and Parent.Number_of_Messages_Received__c = 0];
	map<Id,EmailMessage> mapCaseId_Email = new map<Id,EmailMessage>();
	for(EmailMessage objEmail : email){
		mapCaseId_Email.put(objEmail.ParentId, objEmail); 
		}	
	if(!mapCaseId_Email.isEmpty()){
		for(Case c:Trigger.new){
			if(mapCaseId_Email.containsKey(c.Id)){}
				c.Email_To_Address__c=email[0].ToAddress;
				c.From_Address__c=email[0].FromAddress;
				c.Email_CC_Address__c=email[0].CcAddress;
				c.Email_From_Name__c=email[0].FromName;
				cases.add(c);
			}
		if(cases.size()>0){
			update cases;
			}
		}
	}

The trigger is great, but I can't get good code coverage because I need to insert the case with a related emailMessage record and I have no idea how to make that happen. Here's what I have now:
@isTest
private class caseTriggerAllTestIsAfter {
    static testMethod void isAfterCaseTest(){
        case newCase = new case ();
        	newCase.Email_CC_Address__c = '';
        	newCase.Email_From_Name__c = '';
        	newCase.Email_To_Address__c = '';
        	newCase.From_Address__c = '';
        emailMessage newEmail = new emailMessage();
           	newEmail.FromAddress = 'Email@No.com';
    		newEmail.ToAddress = 'Feedback@no.com';
    		newEmail.CcAddress = 'ccAddress@verify.com';
    		newEmail.FromName = 'Someones Name';
    		newEmail.Incoming = True;
    		newEmail.ParentId = newCase.id;
	insert newCase;
    insert newEmail;
	System.assertEquals ('Email@No.com', newCase.From_Address__c);
   	System.assertEquals ('Feedback@no.com', newCase.Email_To_Address__c);
   	System.assertEquals ('ccAddress@verify.com', newCase.Email_CC_Address__c);
   	System.assertEquals ('Someones Name', newCase.Email_From_Name__c);
    }
}

I know that if I create the case first, i can populate the emailMessage.ParentId as the newCase.id, but at that point, the trigger will have already fired because the case has already been inserted. Does anyone know how to create the child emailMessage first, and then associate it to the case at insert? Any help will be greatly appreciated! 

Thanks, Mike.


 
So, I'm new to Apex and Visualforce, and I have a unique problem that I am sure is indicative of the fact that I am a rookie at this envrionment. The code executes correctly when using 'Visualforce' but not with my Apex Test Class. Since I've only been working with Apex and Visualforce for two weeks now, I'm sure its because there is something that I am not clear about. Please find below my Visualforce code, my Controller code and my Test class. I'm only having a problem with testing the Delete code in the Apex class. I can't seem to get the correct 'ID' to pass through so that the row is subsiquently deleted from Salesforce. The 'Null' portion of the Delete in the Controller tests with the Test class, but the deletion of the row inserted does not. Any help would be greatly appreciated. Thanks!

VISUALFORCE CODE 
<apex:page standardController="Request__c" extensions="TrController" >
    <!-- The following code will fix a problem with the calendar autospawning when the time entries are displayed. -->
    <script>
        function setFocusOnLoad(){ Coment.focus(); }
    </script>
   
    <!--Because we will be defining 'Input' fields, we must wrap our code in a 'Form' block. -->
    <apex:form id="Time_Entry_Form">
        <apex:pageBlock title="CDCR - Salesforce Time Reporting for Requests" id="Time_Entry_List">
           
            <!-- The following pageBlockButtons segment defines the two buttons that appear at the top of the Time entry form. -->
            <apex:pageBlockButtons id="Button_area">
                <!-- The following Button is defined in a more complicated fashion so that a parameter can be passed. -->
                <apex:commandLink >
                    <a href="javascript: CurrRequest('{!Request__c.Id}');" class="btn">New</a>               
                </apex:commandLink>
               
                <apex:commandLink >
                    <a href="javascript: SaveEntry();" class="btn">Save</a>               
                </apex:commandLink>

            </apex:pageBlockButtons>
           
             <!-- The following pageBlockTable segment defines the time entry rows that will be displayed. -->
            <apex:pageBlockTable value="{!TimeEntries}" var="entry" id="Entry_Table_List">
                <apex:column width="45" headerValue="Action">
                    <a href="javascript:if (window.confirm('Are you sure?')) DeleteEntry('{!entry.Id}');" style="font-weight:bold">Del</a>               
                </apex:column>   
                <apex:column width="70" headerValue="Activity">
                    <apex:inputField value="{!entry.Activity__c}"/>
                </apex:column>   
                <apex:column width="70" headerValue="Date Worked">
                    <apex:inputField value="{!entry.Date_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Hours">
                    <apex:inputField value="{!entry.Hours_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Worked">
                    <apex:inputField value="{!entry.Minutes_Worked__c}"/>
                </apex:column>   
                <apex:column headerValue="Work Description">
                    <apex:inputField style="width:100%" value="{!entry.Work_Description__c}" id="comment"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <!-- This action block is executed based on the 'Delete' button being clicked on. -->
        <apex:actionFunction action="{!del}" name="DeleteEntry" reRender="Time_Entry_List">
            <apex:param name="deleteEntryID" value="" assignTo="{!SelectedEntryID}"/>
        </apex:actionFunction>
       
         <!-- This action block is executed based on the 'New' button being clicked on. -->
        <apex:actionFunction action="{!add}" name="CurrRequest" reRender="Time_Entry_List">
            <apex:param name="addEntryID" value="" assignTo="{!ReqID}"/>
        </apex:actionFunction>

         <!-- This action block is executed based on the 'Save' button being clicked on. -->
        <apex:actionFunction action="{!save}" name="SaveEntry" reRender="Time_Entry_List"/>
       
     </apex:form>
    <!-- The following script code is used in order to fix the problem with the calendar autospawning. -->
    <script>
        var Coment=document.getElementById('{!$Component.theForm.block.sec.item.comment}');
    </script>   
</apex:page>

APEX CONTROLLER CLASS

public with sharing class TrController
{
    //This is the list for handling the group of time entries related to the parent object.
    public List<Time_Entry__c> TimeEntries {get;set;}
    //Used to get a hold of the entry record that is selected for deletion.
    public string SelectedEntryID {get;set;}
    //Used to get the parent request object ID from the Visual force page to the controller.
    public string ReqID {get;set;}
    public TrController(ApexPages.StandardController controller)
    {
        //Obtain the parent object Id from the the visualforce form.
        ReqId = Apexpages.currentPage().getparameters().get('Id');
        //SelectedEntryId = Apexpages.currentPage().getparameters().get('deleteEntryId');
        //Call the loaddata method to laod the time entries related to the parent object.
        LoadData();
     }
    public void LoadData()
    {
        //Obtain the first 15 bytes of the Parent Object ID to use for record selection.
        string RequestID = ReqId.substring(0, 15);
        //Load the related time entry records from the database.
        TimeEntries = [select id, Activity__c, Date_Worked__c, Hours_Worked__c, Minutes_Worked__c, Work_Description__c from Time_Entry__c WHERE Related_Object__c=:RequestID order by ID DESC];

    }
    public void save()
    {
        //Update the Salesforce database with the data entred.
        update TimeEntries;
    }
    public void add()
    {  
       //Obtain the first 15 bytes of the Parent Object ID to use for record identification.
        string RequestID = ReqId.substring(0, 15);
        //Build the default values to the new time entry record.
        Time_Entry__c entry = new Time_Entry__c(Activity__c='Research', Date_Worked__c=System.today(), Hours_Worked__c=' 0', Minutes_Worked__c='00', Related_Object__c=RequestID);
        //Insert the new default time entry row into the Salesforce database.
        Insert entry;
        //Call the method to reload the Visualforce list.
        LoadData();
    }
    public void del()
    {
     ExecuteDelete(SelectedEntryId);
    }
    public void ExecuteDelete(string selectedEntry)
    {
        //if we are missing the reference, then do nothing except return.
        if (selectedEntry == null)
        {
            return;
        }
        
        //If the record is within the collection, then delete it.
        Time_Entry__c tobeDeleted = null;
        for(Time_Entry__c a : TimeEntries)
        {
            string EntID = a.Id;
            string SelId = EntId.substring(0, 15);
        if (EntID == selectedEntry)
            {
                tobeDeleted = a;
                break;
            }
        }   
        //If account record found then delete it.
        if (tobeDeleted != null)
            {
                Delete toBeDeleted;
            }
        //Refresh the list
        LoadData();

    }

}

APEX TEST CLASS

@isTest
public class TrControllerTest
{
 static testMethod void testMethod1()
 {
  
    //Instantiate a new instance of the Custom Request Object.
        Request__c ReqObj = new Request__c();
    //Populate the name of the new request object.
        ReqObj.Name = 'Test request';
    //Populate 'What is being requested.
        ReqObj.What_is_being_requested__c = 'Entry to test apex code.';
    //Insert the new request object into Salesforce.
  insert ReqObj;             
  
 //Instantiate a new instance of the Time_Entry object.
  Time_Entry__c te = new Time_Entry__c();
    //Populate the required fields of the Time Entry object.
  te.Name ='Test';            
        te.Date_Worked__c = System.today();
        te.Hours_Worked__c = '01';
        te.Minutes_Worked__c = '15';
        te.Work_Description__c = 'This is a test entry';
        te.Activity__c = 'Research';
    //Insert the new Time_Entry object into Salesforce.
  insert te;              
  
    //Indicate the starting of the test process.
        Test.StartTest();
 
    //Post the Request ID of the Request object created.
            Apexpages.currentPage().getparameters().put('id', String.valueOf(ReqObj.Id));
    //Instantiate a new instance of the Request object standard controller.
       ApexPages.StandardController sc = new ApexPages.StandardController(ReqObj);
    //Instantiate a new instance of the Time Entry Controller that is related to the Standard controller.
        TrController testAccPlan = new TrController(sc);
   
    //Test the code within the 'save' method.
            testAccPlan.save(); 
    //Test the code within the 'add' method.
         testAccPlan.add();           
         //System.AssertEquals(NewEntryId, ReqObj.Id);
            
 //Obtain the object Id's for the row inserted in the database initially.    
         List<Time_Entry__c> deleteEntry = [select id from Time_Entry__c WHERE Work_Description__c = 'This is a test entry'];

 //Loop through the objects returned from the 'Select' statement and pass the Object Id's to the 'ExecuteDelete' class.    
        for(Time_Entry__c a : deleteEntry)
            {
                testAccPlan.ExecuteDelete(a.Id);
                //Leave the loop after one itteration.
                break;
            }
    
    //Execute the ExecuteDelete class with a 'Null' variable so that the additionally related code is tested.
        testAccPlan.ExecuteDelete(null);
  
    //Indicate the end of the test code.
        Test.StopTest();
 }
}
Hi friends,
I am getting only 41% code coverage for this class. Plz help me to get the coverage for this class.

My Test Class
******************
@isTest
public with sharing class NavikRecommendationsControllerHelperTest {
    public static testmethod void ControllerHelperTest() {
        
        
        Account acc = new Account(Name= 'Test', Industry= 'Pharma', Account_Lead_Score__c= 90, Last_Action__c= 'call', Existing_Conversation__c= 1, New_Conversations__c = 1, Account_YTDSales__c = 10);
        insert acc;
        
        Opportunity opp = new Opportunity(Name= 'Testopp' /*, Contact__c= 'jain' */, CloseDate= System.today(), StageName = 'Closed', Sales_Rep_1__c= 'Kunal Jain', Geography__c = 'ME', Vertical__c = 'CPG', Horizontal__c ='NCT', Opportunity_Lead_Score__c= 90, Contact_YTD_Sales__c = 100, Conversation_Type__c = 'Phone', Product_Recommendation__c= 'test', Next_Best_Action__c = 'email', Account_Manager_1__c = 'Jim', Status__c ='lost', Reason_for_Closure__c= 'done');
        insert opp;
        //Account= 'Test',
        
        Recommendation__c rec = new Recommendation__c (Name= 'Test', Est_Value__c= 5000, Opportunity_Score__c = 90, Product_Service__c= 'PC');
        insert rec;
        
        Recommendation_Rationale__c rcr = new Recommendation_Rationale__c (Name= 'Offer', Rationale1__c = 'Offer1', Rationale2__c= 'offer2', Rationale3__c= 'Offer3', Rationale4__c = 'offer4', Rationale5__c= 'offer5', Rationale6__c= 'offer6', Recommendation__c = rec.Id);
        insert rcr;
        
          Cheatsheet__c cts = new Cheatsheet__c (Name= 'cheatsheet', Recommendation__c = rec.Id);
        insert cts;
        
        /*
        List<SalesAIRecommendations.Data> lst = new List<SalesAIRecommendations.Data>();

        SalesAIRecommendations.Data data = new SalesAIRecommendations.Data();
            data.accountNumber = '7846483469';
            data.AccountId = acc.Id;
            data.dataId = 9456;
            data.accountName = 'Test';
            data.leadScore = 90;
            data.productServiceRecommendation = 'NA';
            data.feedback = 'testing';
            data.thisWeek = 1;
            data.lastWeek = 2;
            data.primarySKU = 'NA';
            data.skuLabel = 'NA';
            data.location = 'Gurgaon';
            data.industryType = 'IT';
            data.customerSince = System.today();
            data.contactName = 'NA';
            data.oppId = acc.Id;
            //insert data;
        lst.add(data);
        */
        
        /* SalesAIRecommendations.Recommendations temp = new SalesAIRecommendations.Recommendations();
                    temp.productServiceRecommendation = 'PC';
                    temp.opportunityScore = 90;
                    temp.estimatedValue = 5000;
                    data.recommendations.add(temp); */
        
        
        
        test.startTest();
        string str = NavikRecommendationsControllerHelper.pCallout();
        string str1 = NavikRecommendationsControllerHelper.deCallout();
        string str2 = NavikRecommendationsControllerHelper.inCallout();
         string str3 = NavikRecommendationsControllerHelper.callout('98748', 'Raj', 'test');
        string str4 = NavikRecommendationsControllerHelper.specificSalesRecommendation('test');
        string str5 = NavikRecommendationsControllerHelper.specificOpportunities('73872832');
        //string str6 = NavikRecommendationsControllerHelper.sendEmail(new List<SendToInbox.response>{new SendToInbox.response()});
        //string str7 = NavikRecommendationsControllerHelper.invalid(new List<integer>{123435}, new List<String>{'123435'});
         //string str8 = NavikRecommendationsControllerHelper.setInvalidCallout(new List<integer>{123435});
        test.stopTest();
        
        
    
    }
    
}
  • April 19, 2017
  • Like
  • 0
Hello,

I have a workflow Rule with a field update attached with it.

The workflow entry criteria for workflow is as below:
AND( 
AND($Profile.Name <> 'Profile 1',$Profile.Name <> 'Profile 2',$Profile.Name <> 'Profile 3',$Profile.Name <> 'Profile 4',$Profile.Name <> 'Profile 5'), 
NOT(ISBLANK(customField__1)), 
Or( 
ISCHANGED( customField__1 ), 
ISNEW() ) 
)
I want to execute the workflow if it doesnot belong to certain profile
Profile 1 to Profile 5

the fielld update is not working as i want because of entry criteria.

Am i going wrong anywhere ?


 
Hello everybody i created a milestone who starts couting once a Work Order is created, but i want that it to stop counting once the Status of the Work Order changes to Start Execution
Can any one help me with that?
Thank you
User-added image
I have a test class that is 68% covered.  I have 2 lines throughout that I cannot get covered.  Can anyone help me get them covered?
Its the 2 lines after the else statement.  
 
if (oldCase.Substatus__c == 'Open with Cat Support') {
                                // Log into the "Open with Cat Support" bucket
                                if(c.Accumulated_Duration_Open_with_Cat_Supp__c != Null) {
                                  c.Accumulated_Duration_Open_with_Cat_Supp__c += elapsedHours;
                                }
                                else {
                                    c.Accumulated_Duration_Open_with_Cat_Supp__c = 0.0;
                                    c.Accumulated_Duration_Open_with_Cat_Supp__c += elapsedHours;
                                }
                            }

 
  • April 17, 2017
  • Like
  • 0
So I have a Visualforce page that I have created that is related to a standard controller and also an extension to an 'Apex' controller. I've taken the 'Trailhead' training on testing an Apex class, but I can't seem to successfully apply what I learned in the Trailhead tutorial to my project and get there to not be syntax errors in my test code. I have only working on my first Visualforce/Apex project for a week now, so I'd sure welcome any suggestions anyone might have. The primary Methods that I am calling from the Visualforce Page are 'Save', 'Add' and 'Delete', so any help in any of those methods that I could then apply to the others would be greatly appreciated.

VISUALFORCE CODE:
<apex:page standardController="Request__c" extensions="TrController" >
    <!-- The following code will fix a problem with the calendar autospawning when the time entries are displayed. -->
    <script>
        function setFocusOnLoad(){ Coment.focus(); }
    </script>
   
    <!--Because we will be defining 'Input' fields, we must wrap our code in a 'Form' block. -->
    <apex:form id="Time_Entry_Form">
        <apex:pageBlock title="CDCR - Salesforce Time Reporting for Requests" id="Time_Entry_List">
           
            <!-- The following pageBlockButtons segment defines the two buttons that appear at the top of the Time entry form. -->
            <apex:pageBlockButtons id="Button_area">
                <!-- The following Button is defined in a more complicated fashion so that a parameter can be passed. -->
                <apex:commandLink >
                    <a href="javascript: CurrRequest('{!Request__c.Id}');" class="btn">New</a>               
                </apex:commandLink>
               
                <apex:commandLink >
                    <a href="javascript: SaveEntry();" class="btn">Save</a>               
                </apex:commandLink>

            </apex:pageBlockButtons>
           
             <!-- The following pageBlockTable segment defines the time entry rows that will be displayed. -->
            <apex:pageBlockTable value="{!TimeEntries}" var="entry" id="Entry_Table_List">
                <apex:column width="45" headerValue="Action">
                    <a href="javascript:if (window.confirm('Are you sure?')) DeleteEntry('{!entry.Id}');" style="font-weight:bold">Del</a>               
                </apex:column>   
                <apex:column width="70" headerValue="Activity">
                    <apex:inputField value="{!entry.Activity__c}"/>
                </apex:column>   
                <apex:column width="70" headerValue="Date Worked">
                    <apex:inputField value="{!entry.Date_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Hours">
                    <apex:inputField value="{!entry.Hours_Worked__c}"/>
                </apex:column>   
                <apex:column width="20" headerValue="Worked">
                    <apex:inputField value="{!entry.Minutes_Worked__c}"/>
                </apex:column>   
                <apex:column headerValue="Work Description">
                    <apex:inputField style="width:100%" value="{!entry.Work_Description__c}" id="comment"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <!-- This action block is executed based on the 'Delete' button being clicked on. -->
        <apex:actionFunction action="{!del}" name="DeleteEntry" reRender="Time_Entry_List">
            <apex:param name="EntryID" value="" assignTo="{!SelectedEntryID}"/>
        </apex:actionFunction>
       
         <!-- This action block is executed based on the 'New' button being clicked on. -->
        <apex:actionFunction action="{!add}" name="CurrRequest" reRender="Time_Entry_List">
            <apex:param name="EntryID" value="" assignTo="{!ReqID}"/>
        </apex:actionFunction>

         <!-- This action block is executed based on the 'Save' button being clicked on. -->
        <apex:actionFunction action="{!save}" name="SaveEntry" reRender="Time_Entry_List"/>
       
     </apex:form>
    <!-- The following script code is used in order to fix the problem with the calendar autospawning. -->
    <script>
        var Coment=document.getElementById('{!$Component.theForm.block.sec.item.comment}');
    </script>   
</apex:page>

CONTROLLER APEX CODE

public with sharing class TrController
{
    //This is the list for handling the group of time entries related to the parent object.
    public List<Time_Entry__c> TimeEntries {get;set;}
    //Used to get a hold of the entry record that is selected for deletion.
    public string SelectedEntryID {get;set;}
    //Used to get the parent request object ID from the Visual force page to the controller.
    public string ReqID {get;set;}
    public TrController(ApexPages.StandardController controller)
    {
        //Obtain the parent object Id from the the visualforce form.
        ReqId = Apexpages.currentPage().getparameters().get('Id');
        //Call the loaddata method to laod the time entries related to the parent object.
        LoadData();
     }
    public void LoadData()
    {
        //Obtain the first 15 bytes of the Parent Object ID to use for record selection.
        string RequestID = ReqId.substring(0, 15);
        //Load the related time entry records from the database.
        TimeEntries = [select id, Activity__c, Date_Worked__c, Hours_Worked__c, Minutes_Worked__c, Work_Description__c from Time_Entry__c WHERE Related_Object__c=:RequestID order by ID DESC];

    }
    public void save()
    {
        //Update the Salesforce database with the data entred.
        update TimeEntries;
    }
    public void add()
    {  
       //Obtain the first 15 bytes of the Parent Object ID to use for record identification.
        string RequestID = ReqId.substring(0, 15);
        //Build the default values to the new time entry record.
        Time_Entry__c entry = new Time_Entry__c(Activity__c='Research', Date_Worked__c=System.today(), Hours_Worked__c=' 0', Minutes_Worked__c='00', Related_Object__c=RequestID);
        //Insert the new default time entry row into the Salesforce database.
        Insert entry;
        //Call the method to reload the Visualforce list.
        LoadData();
    }
    public void del()
    {   
        //if we are missing the reference, then do nothing except return.
        if (SelectedEntryId == null)
        {
            return;
        }
        
        //If the record is within the collection, then delete it.
        Time_Entry__c tobeDeleted = null;
        for(Time_Entry__c a : TimeEntries)
        if (a.Id == SelectedEntryId)
            {
                tobeDeleted = a;
                break;
            }
        //If account record found then delete it.
        if (tobeDeleted != null)
            {
                Delete toBeDeleted;
            }
        //Refresh the list
        LoadData();

    }

}

Thank you in advance for your time.

Eric Anderson 
I want to get all fields information which includes parent records details as well.
let suppose query is like, select * from contact.
Here contact is child object of Account, So i need account all feilds as well.

Is This Possiable?
Note: I wil have only recordID, based on i need all above info.
Any alternative soution other than Apex code?
Guys, please help me on this.
  • April 17, 2017
  • Like
  • 0
Hi all,
I stucked in writing test class for trigger please help me am newbie

MyTrigger:
trigger onCustomerUpdate on Account (after update) {
	try
	{
		// Get all Lead Sharing records
		SPG_Approval_request__c[] SPGRecords = [Select Id, Customer_Name__c from SPG_Approval_request__c where Customer_Name__c in :trigger.newMap.keySet()];
		
		Set<Id> SPGIds = new Set<Id>();
		for(SPG_Approval_request__c SPG : SPGRecords)
			SPGIds.add(SPG.Id);
		/*	
		// Get the existing sharing rules for the lead sharings and delete them
		for(SPG_Approval_request__Share[] SPGRecordShares : [Select Id from SPG_Approval_request__Share where parentId in :SPGIds and RowCause = 'Derived_From_Customer__c'])
			delete SPGRecordShares;
		*/
		System.debug('DML Rows Processed : ' + Limits.getDMLRows());
		// Insert the new sharing rules 
		inheritSharingForSPG.inheritSharingFromCustomer(SPGIds);		
	}
	catch(Exception e)
	{
		trigger.new[0].addError('Following Exception Occurred: ' + e.getMessage() + '\n. Please contact the system administrator with the error message.');
	}	
}

MyTestClass for above Trigger:
@isTest
public class onCustomerUpdateTest {
    static testMethod void TestMethodonCustomerUpdate(){
        Account a=new account();
        a.name='Test Account';
        insert a;
        SPG_Approval_request__c  s=new SPG_Approval_request__c();
        s.Customer_Name__c=a.Id;
        s.Document_Name__c='DB';
        insert s;
        a.name='change';
        update a;

         }
}

 
Hello All,

I am on the Data Security:Control Access to Fields chapter of Trailhead.  Even though, I have done the steps as listed by the challenge
1)Create an Account Profile
2)Change the Object Settings for Account and Contacts Object
3)Changed the Field Setting for Rating field in the Account Object
4)Created a Rating permission set and changed the access for Rating field of the Account object.

I keep getting this error "The 'Account' profile was not found".  I am stuck on this since 1 day.  Is anyone else facing the same problem? How did you solve it? Thank you.

Priya
Hi all,
Can anyone help me in writting test class for this.

public class Ugcontroller {

    public String getBirthdateDOW() {
        return null;
    }


    public PageReference FindBirthdateDOW() {
        return null;
    }


 public String selectedyear{get;set;}
 public Date dat{get;set;}
 public ID ugId{get;set;}
 

  public UnderGradute__c ugform{
    get {
      if (ugform== null)
       ugform = new UnderGradute__c();
       
      return ugform;
    }
    set;
  }
  
  
  
    public PageReference Ugpage4() {
        return page.UG_page4;
    }
    
    
    public PageReference ugpage3() {
        return page.UG_page3;
    }
    
    
    public PageReference ugpage2() {
        return page.UG_page2;
    }


    public PageReference ugpage1() {
        return page.UG_Page1;
    }



    
     public Ugcontroller () {
    
      
  }
  
  
    public class Sampledate {
            
            public Sampledate() {
        
            }
       }
    
public List<SelectOption> getyearOptions() {
        List<SelectOption> countryOptions = new List<SelectOption>();
        countryOptions.add(new SelectOption('','-None-'));
        
        for(integer i=2016;i<=2022;i++)
        {
        string s = string.valueof(i);
        countryOptions.add(new SelectOption(s,s));
        }
        
        return countryOptions;
    } 

    public PageReference cancel() {
        return null;
    }

    public PageReference save() {
    system.debug(this.ugform);
    
           try {
      ugform.Year_Enrollment__c = String.valueOf(selectedyear);
      ugform.Date_of_Birth_ug__c = Date.valueof(dat);
      upsert ugform;
     
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error creating new Undergraduate.'));
      return null;
    }
     Pagereference ref = new Pagereference('/apex/UG_congrats?id=' +ugform.id);

              ref.setRedirect(true);
            
         // if successfully inserted new lform, then displays the thank you page.
           return ref;
        
    }
            public PageReference getpdfpage() {
  this.ugId = ApexPages.currentPage().getParameters().get('id');
  Pagereference ref = new Pagereference('/apex/UG_PDF_Page?id=' +this.ugId);

              ref.setRedirect(true);
            
         // if successfully inserted new lform, then displays the thank you page.
           return ref;      
    }
    
    public with sharing class ExamplePageController {

    public ExamplePageController(Ugcontroller controller) {

    }

  public UnderGradute__c ugform{get; set;}
  public String StringDate {get; set;}
  public String StringDateDOW {get; set;}
  public String BirthdateDOW {get; set;}
  
  // create a temporary contact 
  public ExamplePageController() {
   
    ugform = new UnderGradute__c();
  }
  
  // find the day of the week for Birthdate.  Date.valueOf can be used with Date fields
  public PageReference FindBirthdateDOW() {
    try {
      BirthdateDOW = DateTime.newInstance( Date.valueOf(ugform.Date_of_Birth_ug__c), Time.newInstance(0, 0, 0, 0) ).format('EEEE');
    } catch (exception e) {
      BirthdateDOW = '';
    } 
    return null;
  }
  
}

}
public class AddPrimaryContact implements Queueable {
Private Contact conl = new Contact();
Private String sty;
Public List<Contact> coninsert = new List<Contact>();

public AddPrimaryContact(Contact conlist, String str)
{
    this.conl = conlist;
    this.sty= str;
}


public void execute(QueueableContext context)
{
    for(List<Account> acclist: [Select id,name from Account where BillingState =:sty]);
    {
        for(Account accops:acclist)// Error in this statement
        {
            conl.lastname = 'testLast';
            conl.accountid = accops.id;
             coninsert.add(conl);
        }
    }

    if(coninsert.size()>0)
    {
        insert coninsert;
    }
}}


I am trying Queueable Apex challenge in trial head. In the code I am getting an error in the for loop. Correct me if I am wrong in the below code.
Error: Variable does not exist: acclist

 

Thanks for help!

System.QueryException: List has more than 1 row for assignment to SObject
Class.AccountSearchUI.<init>: line 13, column 1

My VF Page

<apex:page standardController="Account" extensions="AccountSearchUI">
<head>
<title>Account Search UI</title>
<style type="text/css"> </style>
</head>

<body>
<table width="99%" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
    <tr>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
    <tr>
        <td bgcolor="#FFFFFF"></td>
        <td bgcolor="#FFFFFF"></td>
        <td bgcolor="#FFFFFF"></td>
      </tr>
    <tr>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
        <td height="5" bgcolor="#FFFFFF">&nbsp;</td>
    </tr>
    <tr>
    <td bgcolor="#FFFFFF" valign="top">
        <table width="100%" border="0" align="center" cellpadding="1" cellspacing="0" class="tablemain">
            <tr><td height="1"></td></tr>
            <tr><td height="50" class="headingmain">&nbsp;Account Search UI</td></tr>
            <tr>
                <td align="center">
                  <table width="100%" border="0" cellspacing="0" cellpadding="1" class="tablemain">
                    <tr>
                      <td width="10%" height="23" class="headingsub1">Group Org Acc</td>
                      <td width="10%" height="23" class="headingsub1">Vertical</td>
                      <td width="10%" height="23" class="headingsub1">Account Name</td>
                      <td width="10%" height="23" class="headingsub1">Type</td>
                      <td width="10%" height="23" class="headingsub1">Owner Last Name</td>
                      <td width="10%" height="23" class="headingsub1">Client Rank</td>
                      <td width="10%" height="23" class="headingsub1">Account Plan</td>
                      <td width="10%" height="23" class="headingsub1">Last Modified</td>
                      <td width="10%" height="23" class="headingsub1">View Latest PDF</td>
                      <td width="10%" height="23" class="headingsub1">PDF Upload Date</td>
                    </tr>
                    <apex:repeat value="{!accPList}" var="cp">
                    <tr>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Group_Org__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Vertical__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Name}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Type}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Client_Rank__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Group_Org__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Vertical__c}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Name}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Type}"/></td>
                        <td height="23" class="headingsub1"><apex:outputField value="{!cp.Client_Rank__c}"/></td>
                    </tr>
                    </apex:repeat>
          </table>
        </td>
        
      </tr>
    </table></td>
    <td bgcolor="#FFFFFF" valign="top"></td>
    <td bgcolor="#FFFFFF" valign="top"></td>
  </tr>
  
  <tr>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;</td>
    <td bgcolor="#FFFFFF">&nbsp;</td>
  </tr>

</table>

</body>

</apex:page>

APEX Class
public with sharing class AccountSearchUI{    

    public ApexPages.StandardController stdController {get; set;}
    public Account acc {get; set;}
    public Account accPList {get; set;}
    
    public String accountName ='';
    public AccountSearchUI(ApexPages.StandardController stdController){
    this.stdController = stdController;

 accPList = [select Group_Org__c, Vertical__c, Name, Type, Client_Rank__c from Account where Top_25_Client__c = true and Client_Rank__c < 26 order by Client_Rank__c ASC limit 5];
    }
}
Can anyone help with the issue.
 
This is my code
=============
global class BatchApex implements Database.Batchable<sobject>{
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('select id from Opportunity');
        
    }
    global void execute(Database.BatchableContext bc,List<Opportunity>scope){
        for(Opportunity o:scope){
            o.Name='sandhya';
        }
    update scope;
}
    global void finish(Database.BatchableContext bc){
            
   Messaging.SingleEmailMessage[] mail=new Messaging.SingleEmailMessage();
        String[] toAddresses=new String[] {'forcesfdcloud@gmail.com'};
            mail.setToAddresses(toAddresses);
        mail.setSubject('sending mail ');
        mail.setPlainTextBody('process completed success fully');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
      
    }
    }
I want to update my opportunities. After updating the opportunities i want to send a mail to the above mentioned address, but it shows error like" Illegal assignment from Messaging.SingleEmailMessage to List<Messaging.SingleEmailMessage>" can any one tell me how to solve this issue.
trigger CheckValidationonCaseClose on Case (after update) {     
for(Case e:Trigger.New){          
Case d=Trigger.oldMap.get(e.Id);         
if(d.Signature_Required__c==true && d.Customer_Signature_Status__c!='Completed' && e.IsClosed==true)
{  
e.adderror('Cannot Close Case');
}

its urgent
}  
Hi,

I have a rquirement to format a time which is given in HH:MM format (24-hour clock) into the user's locale. I assumed that there would be a fromat() method as the DateTime class does, but it does not exist.

Any ideas how I can do this?

Thanks
I have a Salesforce App which passed security review for the first time in the last year. This App also includes integration with external web application, due to this I also submitted a BURP scan report of the external web application. I am not sure about how Salesforce conducts periodic security review and have some queries.

As you may know, Salesforce provides periodic, point-in-time review at an interval determined by salesforce.com (typically anywhere between 6 months to 2 years).

• As per Salesforce documentation for already passed Apps, around the expiry date, Salesforce contacts partners to arrange another review. Can you guide me on how much time Salesforce gives us to prepare for Security Review?

• BURP scan and fixing the issues reported by it can take time. If I could not submit a clean BURP scan report within the time frame provided by Salesforce, Does Salesforce remove package from AppExchange?

• Salesforce charges for Security Review process for paid Apps, as one-time upfront fee, and a small subsequent annual fee. Can you guide me on how much subsequent annual fee Salesforce charges to partners? Salesforce also charges annual listing fee of $150 USD. Is that correct?

Kindly help me with this. Thanks in advance.
Hi All,

I want to disable the global search for particular users,i have disabled the chatter in chatte section,please give me suggestion how to disable the global search.
see the below screen shot where i have disabled
User-added image

see the below screen shot for what i want to disable 

User-added image

Thanks,
Surya
I'm stuck on only one unit for this module; the controlling access to fields unit:

"Two team members need to view and update Accounts, but only one should be able to see and edit the Rating field. Create one profile and one permission set with field level security to solve for this use case.The profile must be named 'Basic Account User' and result in an API name of 'Basic_Account_User'. It should use the 'Salesforce' user license type.
The permission set must be named ‘Account Rating’ and result in an API name of 'Account_Rating'."

"Challenge Not yet complete... here's what's wrong:
The 'Basic Account User' profile did not have the appropriate object and field-level security for the Account object "
  • February 02, 2016
  • Like
  • 1
Hi Jacob,

I have already completed 5 badges, but still no email for obtaining the Cloak of Adventure sweatshirt. Does it take username or email address for sending emails, as my email address and user name are different.

User-added image
Hi,

I want to send an email alert to task owner if they have any open task which due date is already passed.
I want to send it 1 day after due date and 1 week after due date.
Please suggest how I can achieve it because through workflow it is not achievable.

Regards
Emily
 view state and need a steps how can we reduce view state without help of transient
Hi,

I have executed "Run all test" to get code coverage of all apex classes. Is there way to get all apex classes code coverage with percentage copy to excel sheet. I am able to see all classes with percentage in Developer console. But not able to copy all those. Please provide some suggestion.
We are using Apex Data Loader 19.0 and cliq_process.  Using Apex Data Loader & Cliq_process, we are exporting the data into salesforce custom object. The process was working fine past 2 years and till last week. Last few days we are getting the below error.


2015-08-17 06:12:31,218 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:104) - Logging in to: https://www.salesforce.com/services/Soap/u/19.0
2015-08-17 06:12:31,233 INFO  [ExportRevenue] client.PartnerClient login (PartnerClient.java:989) - Beginning Partner Salesforce login ....
2015-08-17 06:12:31,249 INFO  [ExportRevenue] client.PartnerClient login (PartnerClient.java:998) - Salesforce login to https://www.salesforce.com/services/Soap/u/19.0/services/Soap/u/19.0 as user forceuser@<company>.com
2015-08-17 06:12:31,655 INFO  [ExportRevenue] dao.DataAccessObjectFactory getDaoInstance (DataAccessObjectFactory.java:51) - Instantiating data access object: C:\Program Files\salesforce.com\Apex Data Loader 19.0\cliq_process\ExportRevenue\write\ExportRevenue.csv of type: csvWrite
2015-08-17 06:12:31,655 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:109) - Checking the data access object connection
2015-08-17 06:12:31,655 INFO  [ExportRevenue] process.ProcessRunner run (ProcessRunner.java:114) - Setting field types
2015-08-17 06:12:31,766 ERROR [ExportRevenue] client.PartnerClient describeSObject (PartnerClient.java:1249) - Error while calling web service operation: describeSObject, error was: Failed to send request to https://ncst.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:113)
    at com.sforce.soap.partner.PartnerConnection.describeSObject(PartnerConnection.java:48)
    at com.salesforce.dataloader.client.PartnerClient.describeSObject(PartnerClient.java:1240)
    at com.salesforce.dataloader.client.PartnerClient.setFieldTypes(PartnerClient.java:1196)
    at com.salesforce.dataloader.controller.Controller.setFieldTypes(Controller.java:127)
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:115)
    at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:229)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:847)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
    at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:97)
    at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:82)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    ... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
    at sun.security.validator.Validator.validate(Validator.java:203)
    at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
    at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:840)
    ... 19 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:236)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:194)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:216)
    ... 24 more
2015-08-17 06:12:31,766 FATAL [main] process.ProcessRunner topLevelError (ProcessRunner.java:214) - Unable to run process ExportRevenue
java.lang.RuntimeException: com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:139)
    at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:229)
Caused by: com.sforce.ws.ConnectionException: Failed to send request to https://<company>.my.salesforce.com/services/Soap/u/19.0/00D400000009okc
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:113)
    at com.sforce.soap.partner.PartnerConnection.describeSObject(PartnerConnection.java:48)
    at com.salesforce.dataloader.client.PartnerClient.describeSObject(PartnerClient.java:1240)
    at com.salesforce.dataloader.client.PartnerClient.setFieldTypes(PartnerClient.java:1196)
    at com.salesforce.dataloader.controller.Controller.setFieldTypes(Controller.java:127)
    at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:115)
    ... 1 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:847)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:815)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1025)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1038)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:836)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
    at com.sforce.ws.transport.JdkHttpTransport.connectLocal(JdkHttpTransport.java:97)
    at com.sforce.ws.transport.JdkHttpTransport.connect(JdkHttpTransport.java:82)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    ... 6 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:221)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:145)
Exact replication steps:
1. Create a connected app
2. Add the callback URL to that connected app as the URL of a VF page. For Eg - 'https://c.eu2.visual.force.com/apex/mypage'.
3. Connect to another salesforce org of the same instance.Énter the login details ie username and password
4. Allow permission to the connected app create on your source org to access info about target org by clicking on Állow Button'
5. Instead of redirecting back to source org it redirects me to the target org and tries to open up the page mentioned in the callback url.
6. This issue is coming when my source and target org are on same instance. It works fine when source and target instances are different.
Hello,
I have some queries on release versioning and listing subsequent versions on AppExchange:
  1. Can I release and maintain 2 versions on AppExchange? In other words, if there a v1.0 that is listed on AppExchange, and we release a new version v1.1 that has passed Security Review and ready to be listed on AppExchange, does it automatically replace the v1.0 that was listed earlier? 
  2. Do the existing customer orgs get any notification of a new released version? If yes, does it automatically contain the install link? If not, what is the most preferred practice?
  3. If I deprecate an earlier version, do the customer orgs using this version get a notification to upgrade? Are they forced to upgrade?
  4. If a patch is created for a particular released version, do I have to manually inform all customer orgs using it? Or do they get automatic notifications of the same and can choose to apply the patch as needed?
Thanks in advance!
Hi,

I want to develop an "Open CTI Adapter", where can I find the documentation(API/Library) for the same?

Regards,
Rohan
Hi ,
  
 I'm trying to parse Account records to JSON string. But I'm getting unnecessary data like attributes(type,url) that is not required in String.

Can any one pls help me in how to parse the string to required format.
List<Account> accnts=[Select Name,Phone From Account];
String s=JSON.serialize(accnts);
The resulting output is in below fromat..
{
  "attributes" : {
    "type" : "Account",
    "url" : "/services/data/v34.0/sobjects/Account/00128000002trGGAAY"
  },
  "Name" : "GenePoint",
  "Phone" : "(650) 867-3450",
  "Id" : "00128000002trGGAAY"
}


My requirement is to generate resulting String as below JSON string format.
 
{
  "Name" : "GenePoint",
  "Phone" : "(650) 867-3450",
  "Id" : "00128000002trGGAAY"
}

So that I can minimize the data to to be sent the the client system.

Any help is really appreciated. Thanks in advance.

Regards,
Naveen.
I need to download Contacts Near By component for the trailhead - field sales app project but I am not able to find it on appexchange. Any idea where can I get it from?
I am wrting sql query for getting count,avg,sum,min,max aggregate functions at apex class. but i am getting this error.  please help.
 
Error: Compile Error: Illegal assignment from List<AggregateResult> to Integer at line 12 column 1  


public class soqlfunc
{
public integer count12{set;get;}
public integer avg{set;get;}
public integer sum{set;get;}
public integer max{set;get;}
public integer min{set;get;}

public soqlfunc()
{
count12=[select count() from transaction__c ];
avg=[select avg(amount__c) from transaction__c];
sum=[select sum(amount__c) from transaction__c   ];
max=[select max(amount__c) from transaction__c   ];
min=[select min(amount__c) from transaction__c   ];
}
}

 
Receiving following error on chatter approvals for Cas object
Challenge not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Process failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, missing required field: [nextApproverIds]: [nextApproverIds]
I do not have a clue as to missing information. This was a very confusing exercise for me. Newbie I am