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


  • Chatter
    Feed
  • 1031
    Best Answers
  • 1
    Likes Received
  • 32
    Likes Given
  • 3
    Questions
  • 4937
    Replies
Sending an email from a process builder when a condition is true. My business users want to save the email as PDF.

How can I achieve this?

TIA
  • May 15, 2017
  • Like
  • 0
Problem:

I created an Apex trigger that evaluates multiple conditions on the Accounts object (through if statements). If the conditions are met then the trigger creates a task related to the Accounts (that meets the conditions)

Now, since the trigger after update type of trigger, tasks are being created everytime the account is edited or saved. I tried to create a list of tasks that were created today() through a SOQL query so later on I can write an IF statement inside the trigger's loop that would exclude those accounts that were created today() from the loop. 

I keep getting this error message: Entity 'Task' is not supported for semi join inner selects at line 9 column 30

User-added image

Thanks for your help in advance,
Fares.  
Apex Class:
public class RecursionBlocker{
   public static Boolean flag = true;
}
Trigger: I am creating an event record once the record is approved.
Trigger CreatingAnEvent on Approval_Requests__c(After update){
 
     If(RecursionBlocker.Flag = true){

     RecursionBlocker.Flag = false;
     
      Event evt = New Event();
      If(Trigger.isUpdate)
      {
            For(Approval_Requests__c AR: Trigger.New)
            {
                                           
                   If(AR.Approval_Status__c == 'Approved') // Then Create an event record.
                   { 
                       evt.StartDateTime = AR.Start_Date_Time__c;
                       evt.ACA_Location__c = AR.ACA_Location__C;
                       evt.Type = AR.Type__C;
                       evt.Description = AR.Situation__C;
                       evt.Subject = AR.Subject__C;
                       evt.OwnerID =  String.valueOf(AR.OwnerId);  // "Owner" is an assign to
                       evt.Whatid = AR.id;                        // "what" is a relate to
                       evt.DurationInMinutes =   0; 
                       evt.Automatically_Created_Event__c = TRUE;
                       evt.Approved__C = TRUE;
                       evt.Other_Location__C = AR.Other_Location__C;
                       evt.Organization__C = AR.Account__C;
                       evt.whoid = AR.Contact__c;                 // Who is Name field label on an Event and it's looking up to 
                                                                  //     either Lead or Contact. For our purpose of creation, we are looking up 
                                                                  //       to Contact. Id to Id match. 
                     insert Evt;
                                              
                   }
                   else{
                       // Do Nothing
                   }
                   
            }   
   
        }
    }
}
Now, once the record gets approved then an event record gets created -- which is fine!
But when I update the record again, then new event is created which is needed to be stop.
Thak You for the help!


 

Afternoon Team, 

I think i am having one of these days where i cant do the basics in salesforce.

Aim : I would like the class below to only execute if the recordtype developername = "intermittent'". If the recordtype developername = "pending' then do nothing. Currently my class below executes on either Record type. "intermittent" or "pending ".

This is the query i use to Query RT Object for Flow object          
 select id,developername,Name from RecordType where SobjectType='flow__c' and developername='intermittent'  

I have created a trigger which calls an utils class

Trigger:

/********************************************************************
 * UpdateCurrencyInsert 
 *
 * Before Insert trigger on Flow
 ********************************************************************/
trigger UpdateCurrencyInsert on Flow__c (before insert) 
{
  FlowUtils.ValidateCurrencyUpdate(Trigger.new);
}
 

Class:

public class FlowUtils {
 
   public static void ValidateCurrencyUpdate(List<Flow__c> flows ) {


      List<Id> opportunityIds = new List<Id>();
      Map<Id, String> oppIdCurrencyCode = new Map<Id, String>();
      for (Flow__c Flow: flows ) {
          opportunityIds.add(Flow.opportunity__c);
      }
      
      for(Opportunity opp : [Select CurrencyIsoCode from Opportunity where Id in: opportunityIds]) {
        oppIdCurrencyCode.put(opp.Id, opp.CurrencyIsoCode);
      }
      
      for(Flow__c flow : flows) {
        flow.CurrencyIsoCode = oppIdCurrencyCode.get(flow.opportunity__c);
      }   
   }
 }
Looking forward to your help and advise 
Account la_test = new Account(Name='Test');
        insert la_test;
	Contact lcon_test = new Contact(LastName='Test', Accountid=la_Test.id, Email='test@test.com');
        insert lcon_test;
        location__C lloc_test = new Location__C(name = locName, site_wf__c = site);
        insert lloc_test;
        RecordType rec = [SELECT Id,Name FROM RecordType WHERE SobjectType='Case' and name = :record];
        Case lc_test = new Case(Subject='This is a test ', Accountid=la_Test.id, Status='New', RecordTypeId=rec.id, Contactid=lcon_test.id, Location__c= lloc_test.id,  Notify_contact__c = true); 
        //for trigger testing

        insert lc_test;
If I do a lookup query on the location id being passed into case its name value is populated but when I do lc_test.location__r.name it shows as null (location__c being a lookup field) does anyone know what im doing wrong?
Why is the label twice? I have a email__c field and trying to validate using apex on visualforce page. 
  • April 24, 2017
  • Like
  • 0
In security review of check marx I got Reflected Xss issue on the below line 
<script type="text/javascript" language="javascript"> 
            //initActions();                                        
            proceccOptions('{!questionType}');
 </script>
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 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 ?
 
Today I received the following error after editing the endpoint url in my apex class:

System.CalloutException: Web service callout failed: Unable to find Apex package

I got this error once before and burned an entire day attempting every viable solution i found on these forums.  Nothing worked.  The next day i tested the solution and everything immidiately worked as it should.  So my question: Is this a salesforce issue that pops up its annoying head every once in awhile or is there something about apex classes which i am not fully understanding?  And if it is due to my lack of understanding, can someone point me the way to greater enlightenment?
Hello,  

I'm new at writing apex class and test class. I've written a class that's updating a SubMarket field in an account from a Custom Setting. I've created a test class to test if the SubMarket field value on the account matches the value from the SubMarket in the custom setting. I'm only getting 69% code coverage. I'm not sure what I'm missing/need to add to increase my code coverage. Any feedback would be greatly appreciated. 

Apex class: 
public class AccountSubMarketUpdate {
    public static void setSubMarket(List<Account> acctList){
  
        Set<String> billingCountries = new Set<String>(); 
     
        List<Account> finalAccount = new List<Account>();
        for( Account a : acctList){
            if(String.isBlank(a.SubMarket__c)){
               billingCountries.add(a.BillingCountry); 
               finalAccount.add(a);
            }
        }
           Map<String,CountryMarketMatchMap__c> marketName = CountryMarketMatchMap__c.getAll(); 
        Map<String,String> finalsubMarket = new Map<String,String>(); 
        for (CountryMarketMatchMap__c m : marketName.values()){
               finalsubMarket.put(m.Name,m.Sub_Market__c);
                  }
        for(Account a: finalAccount){
            a.SubMarket__c  = finalsubMarket.get(a.BillingCountry); 
           }
        }
}
   
TestClass: 
@isTest
public class AccountSubMarketUpdateTest {
    @testSetup static void setupTests(){
        List<TriggerController__c> tc = new List<TriggerController__c>{
            new TriggerController__c(Name='Account', Disabled__c=false)
        };
            insert tc; 
    }
    
    static testMethod void testSubMarketUpdate(){
        List<Account> newAcctList = new List<Account>();
        
        Account a1 = new Account();
        a1.name = 'AcctSubMarket';
        a1.BillingCountry = 'Albania';
        a1.SubMarket__c = 'ROE';
        
        Account a2 = new Account();
        a2.name = 'AcctNoMatchSubMarket'; 
        a2.BillingCOuntry = 'Albania';
        a2.SubMarket__c = 'ROE'; 
        
        Test.startTest();
        insert(a1); 
        insert(a2); 
        Test.stopTest();
        
   //Test1: Acct SubMarket matches CS SubMarket.   
        CountryMarketMatchMap__c request = new CountryMarketMatchMap__c();
        request.Sub_Market__c ='ROE';
        request.Name ='Albania'; 
   
        Account returnMarket = [SELECT Id,SubMarket__c,BillingCountry FROM Account WHERE Id =:a1.Id LIMIT 1];
        System.assertEquals(request.Name, returnMarket.BillingCountry);
        System.assertEquals(request.Sub_Market__c, returnMarket.SubMarket__c);
        
   //Test2: Acct SubMarket does not match CS SubMarket. 
           CountryMarketMatchMap__c request2 = new CountryMarketMatchMap__c();
        request2.Sub_Market__c = 'Africa';
        request2.Name = 'Albania'; 
        
        Account noMatchMarket = [SELECT Id,SubMarket__c,BillingCountry FROM Account WHERE Id =:a2.Id LIMIT 1];
        System.assertNotEquals(noMatchMarket.SubMarket__c, 'Africa');
    
    }
}
  • May 22, 2017
  • Like
  • 0
Hi,

Executing the 'generateStringArray' method failed. Either the method does not exist, is not static, or does not return the proper number of strings."

My code is as shown below.

public class StringArrayTest {
    
    public static List<String> generateStringArray(Integer n){
        List<String> str = new List<String>(n);
        for(Integer j=0;j<n ;j++){
           str.add('Test '+String.valueOf(j));
          }
        return str ;
    }
}

When I test this on the debug-->open  execute anonymous window,

with the following code, it runs successfully.

List<String> ls = StringArrayTest.generateStringArray(10);
for (Integer m=0;m<10;m++){
    System.debug(ls[m]);
}
 
Hi,

Please help in writing test class for below piece of code. Thanks

public PageReference testFunction(){
        if(testRecord.Shift__c=='Hourly' || testRecord.Shift__c=='Daily'){
            testRecord.Start_Time__c = '8:30 AM';
            testRecord.End_Time__c = '3:30 PM';
        }else if(testRecord.Shift__c=='AM'){
            testRecord.Start_Time__c = '8:30 AM';
            testRecord.End_Time__c = '12:00 PM';
        }
        else if(testRecord.Shift__c=='PM'){
            testRecord.Start_Time__c = '1:00 PM';
            testRecord.End_Time__c = '3:30 PM';
        }
        return null;
    }
Hello awesome developers!

I have a trigger that I created that should fire to rollup the count of Tasks assoctiated with a Lead in our ORG.  The trigger works as it should and the rollups are perfrorming as we want, however on all other objects (standard or custom) when a Task is being created we receive the following error. 

Apex trigger LeadCountOfTasks caused an unexpected exception, contact your administrator: LeadCountOfTasks: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.LeadCountOfTasks: line 11, column 1

I am seeign that the whoId is not being populated on Account Tasks as that is the WhatId and I think that is the issue with the error, but I am new to apex so I am not sure.  As you can see from my following code, I attemted on the line where this error is coming from, to exclude all tasks for objects other than leads, so again I am lost and lookign for some help to fix this one.  

Thank you in advance fo ryour help and I know one of you awesome Devs can help me with this one!

Shawn
 
trigger LeadCountOfTasks on Task (after delete, after insert, after undelete, after update) {
    Task [] tlist;
        if(Trigger.isDelete)
            tlist= Trigger.old;
        else
            tlist = trigger.new;
    set<id> lid = new set< id> ();
    
    If(!tlist.isEmpty()){
    for(Task ts : tlist)
    {   if(string.valueof(ts.WhoId).startswith('00Q') && ts.WhoId!=null && ts.whatId == null)
        lid.add(ts.Whoid);
    } 
    If(lid.size()>0){
    Map <id,Task > tmap = new Map <id, Task>([select id, Whoid from Task where Whoid in:lid]);
    Map <id, Lead> lmap = new Map <id, Lead>([select id,Count_Activity__c from lead where id in:lid ]);
    
        If(lmap.size()>0){
       List<Lead> llist = [SELECT Id, Count_Activity__c FROM Lead WHERE ID IN:lmap.values()]; 
    for(lead l : lmap.values())
    {
        set<id> tids = new set <id>();
        for(Task tt : tmap.values())
        {
           if(tt.WhoId== l.Id)
            tids.add(tt.id);
        }
        if(l.Count_Activity__c!=tids.size())
        l.Count_Activity__c=tids.size();
        
              tlist = [select id, Whoid from task where whoid in:lid ];
        for(lead le :llist)
        {
            for(Task te:tlist)
            {
                if(tlist.size()>0)
                le.Count_Activity__c = tlist.size();
            }
        }
        
        
    }
    If(lmap.size()>0){
    update lmap.values();
    }
    }
    }
    }
}

 

Hi Everyone,
I am trying to find how to go about resolving this error. I am new to Apex.
   Compile Error: Illegal assignment from List<SurveySelection__c> to String at line 23 column 13

Bottom is my code:
By the way, the data type for "SurveySelection__c" is Number(2,0). I am not sure whether that matters. 
-----------------------------------------------------------------------------------------------------------------------------------------------------
public class WrapperDemoController{
    public class TableRow{
        public String sfsid {get;set;}
        public String SurveySelection   {get;set;}
    }
   
    public List<TableRow> RowList {get; set;}

    public WrapperDemoController(){

        RowList = new List<TableRow>();
        TableRow tr;

        for(Student__c con : [SELECT sfsid__c, (select SurveySelection__c from SurveySelections__r) FROM Student__c]){
 
            tr = new TableRow();
            tr.sfsid = con.sfsid__c;
            tr.SurveySelection = con.SurveySelections__r;  // This is line where error occurs
            
            RowList.add(tr);
        }
    }
}


-----------------------------------------------------------------------------------------------------------------------
Thanks in advance!

Hi Developers.
I have written a trigger to update a lookup field in an object i.e. Incident. once field is updated based on that i have implemented a workflow which have email alert action.But i could see that field is being updated but the workflow is triggering even the entry criteria is matching..

Any help would be appriciated.
I am trying to write a trigger that, given a string, will search SFDC for an account using SOSL. 

This is working when you update/insert a few leads but if you go beyond ten or so I'm getting an error: `CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: LeadTrigger: System.LimitException: Too many SOSL queries: 21 []`

The obvious issue is that I have my SOSL query within the FOR loop. That said, I can't seem to figure out how to bulkify this query. I've tried creating a list of matched names and then pass that list into the SOSL query but I can't seem to iterate through that and match the accounts to the appropriate lead.

I need to use SOSL rather than SOQL in this case because SOQL + LIKE isn't working, it's too broad.
public class LeadTriggerHelper {
        
        Public static void UpdateLead(List<Lead> Leads){
            for(Lead ld1 : Leads){
                String accountName;
                accountName = ld1.cleaned_email__c;

                List<List<Account>> matchedAccount = [FIND :accountName IN NAME FIELDS RETURNING Account LIMIT 1];

                if(matchedAccount.size()>0){
                    ld1.Account_Lookup__c = matchedAccount[0][0].Id;
                } else {
                    System.debug('No Account Found');
                }   
            }
        }
    }



    trigger LeadTrigger on Lead (before insert, before update) {
        if(trigger.isBefore){
            if(trigger.isInsert){
                for (Lead lead : Trigger.new){
                    if((lead.email != '' || lead.website!='') && lead.Trigger_Account_Update__c >=0){
                        LeadTriggerHelper.UpdateLead(trigger.new);                                    
                    }
                }
            }
            If(trigger.isUpdate){
                for (Lead lead : Trigger.new){
                    Lead oldLead = Trigger.oldMap.get(lead.Id);
                    if (oldLead.Trigger_Account_Update__c != lead.Trigger_Account_Update__c){
                        System.debug('updating lead');
                        LeadTriggerHelper.UpdateLead(trigger.new);                        
                    }
                }

            }
        }
    }

 
public static userSessionWrapper getLandingPage(){
        userSessionWrapper userSessionWrapperData;
        String Landingpage= '';
        String pageName= '';
        String urlParam= '';
        String profileName = getLoggedInUserProfile();
        system.debug('profileName :: ' + profileName);
        if(profileName == 'System Administrator')
            profileName = 'Idea Chatter';
        List<User_Session__c> lstUserSession = [SELECT Current_Page__c,First_Name__c,Last_Name__c,CIN__c,DOB__c,Gender__c FROM User_Session__c WHERE user__c = :UserInfo.getUserId() LIMIT 1];
        if(lstUserSession.size() > 0){
            List<BackNavigation__c> lstBackNav = BackNavigation__c.getall().values();
           
            system.debug('Current_Page__c :: ' + lstUserSession[0].Current_Page__c);
            for(BackNavigation__c backNav : lstBackNav ){
                 if(profileName == backNav.Profile__c  && backNav.Current_Page__c == lstUserSession[0].Current_Page__c){
                    Landingpage = backNav.Landing_page__c;
                    pageName = backNav.pageName__c;
                     if(backNav.hasURLParam__c){
                         system.debug('fname: : ' + lstUserSession[0].First_Name__c);
                         if(lstUserSession[0].First_Name__c != '' && lstUserSession[0].First_Name__c != null)
                            urlParam = 'fn='+lstUserSession[0].First_Name__c;
                         if(lstUserSession[0].Last_Name__c != '' && lstUserSession[0].Last_Name__c != null){
                            if(urlParam !='') urlParam += '&ln='+lstUserSession[0].Last_Name__c;
                            else urlParam = 'ln='+lstUserSession[0].Last_Name__c;
                         }
                         if(lstUserSession[0].CIN__c != '' && lstUserSession[0].CIN__c != null){
                            if(urlParam !='') urlParam += '&cin='+lstUserSession[0].CIN__c;
                            else urlParam = 'cin='+lstUserSession[0].CIN__c;
                         }  
                         if(lstUserSession[0].Gender__c != '' && lstUserSession[0].Gender__c != null){
                            if(urlParam !='') urlParam += '&gn='+lstUserSession[0].Gender__c;
                            else urlParam = 'gn='+lstUserSession[0].Gender__c;
                         }
                         if(lstUserSession[0].DOB__c != '' && lstUserSession[0].DOB__c != null){
                            if(urlParam !='') urlParam += '&dob='+lstUserSession[0].DOB__c;
                            else urlParam = 'dob='+lstUserSession[0].DOB__c;
                         }
                     }
                 }
            }
            system.debug('Landingpage :: ' + Landingpage);
            userSessionWrapperData = new userSessionWrapper(Landingpage , pageName , urlParam);
        }
        system.debug('userSessionWrapperData >>>' + userSessionWrapperData);
        return userSessionWrapperData;
    }
    
I am unable to write test class for above method please help me out
Hello,
I'm very new to APEX and I'm trying to test a trigger that calls a Class. 
Apex Class:
public class NewAccount {

@Future(callout=true)
public static void PassNewAccoundIDToQuest(string AccID) {

    try {
    String url = 'https://integration.csmlive.com/service.asmx/AddAccount';
    
    String DataToSend = '{';
    DataToSend = DataToSend + '"SFKey": "' + AccID + '"';
    DataToSend = DataToSend + '}';

    Http h = new Http();
    HttpRequest req = new HttpRequest();
        req.setTimeout(2000);
        
    req.setEndpoint(url);
    req.setMethod('POST');
    req.setHeader('Content-Type', 'application/json');
   
    req.setBody(DataToSend);
    
    h.send(req);
    
        } catch(System.CalloutException e) {
    //Exception handling goes here.... retry the call, whatever
}
    
    //HttpResponse res = 
}
    
}
Apex Trigger:
trigger TriggerAccount on Account (after insert) {
        for(Account a: Trigger.new){
        NewAccount.PassNewAccoundIDToQuest(a.Id);
         }

The test on Class is covered but I'm struggling to get the trigger covered. Any help, please? Thanks
 
Hello I will really appreciate your help, i have this trigger, the coverage is 100% , but i get an error, System.LimitException: Too many SOQL queries: 101, Line 12 "List<Proveedores__c > media = [select id,name, Tipo_de_Proveedor__c,Fecha_de_Vencimiento_de_Contrato__c ,Proveedores__c, cuenta__c from Proveedores__c where cuenta__c in : conIds];" i don't know what else i can do. Thank you!


trigger ResumenProveedores on Account (before insert, before update) {



List<Id> conIds = new List<Id>();
String Proveedores='';

for(Account c : Trigger.new){
conIds.add(c.Id);
}

  List<Proveedores__c > media = [select id,name, Tipo_de_Proveedor__c,Fecha_de_Vencimiento_de_Contrato__c ,Proveedores__c, cuenta__c from Proveedores__c where cuenta__c in : conIds];

 for(Account c : trigger.new){
//      conIds.add(c.Id);
    
        
        for(Proveedores__c pro: media){
            Proveedores=Proveedores+': '+pro.tipo_de_proveedor__c+': '+pro.Proveedores__c+': '+pro.Fecha_de_Vencimiento_de_Contrato__c +'/' ;
            }
            c.Proveedores_Resumen__c= Proveedores;
     } 
}
Hi, I have created the below VF page and controller, but i am getting "Content cannot be displayed: List has no rows for assignment to SObject".
please advice on how to fix this.


<apex:page Controller="MyController" Tabstyle="Account">
<apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton action="{!Save}" value="Save"/>
            </apex:pageBlockButtons>
            <apex:pageBlockTable value="{!account.contacts}" var="contact">>
           
                            <apex:column headerValue="First Name"><apex:inputField value="{!contact.firstname}"/></apex:column>
                <apex:column headerValue="Last Name"><apex:inputField value="{!contact.lastname}"/></apex:column>
                <apex:column headerValue="Phone Number"><apex:inputField value="{!contact.phone}"/></apex:column>
                <apex:column headerValue="E-mail"><apex:inputField value="{!contact.email}"/></apex:column>
                <apex:column headerValue="Title"><apex:inputField value="{!contact.title}"/></apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>

    </apex:form>

</apex:page>


Controller:
public class MyController {

    private final Account account;

    public MyController() {
        account = [SELECT Id, Name, Site FROM Account 
                   WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    }

    public Account getAccount() {
        return account;
    }

    public PageReference save() {
        update account;
        return null;
    }
}

              
In my Dev Environment, I have a notification in the top right corner that says 74 Days Remaining.  Is my environment going to be locked when the 74 days are up?

N Days Remaining
Sending an email from a process builder when a condition is true. My business users want to save the email as PDF.

How can I achieve this?

TIA
  • May 15, 2017
  • Like
  • 0
The following outbound change set upload failed due to a system error:

Error Number: 819142524-35365 (245827274)

I am unable to deploy dashboards - who can I contact to resolve this issue?
We'd like to connect SSO using ActiveX, not using SAML. Is it possible or not?
Hello,

Can anyone suggest me how to inactive a trigger which is in managed package,i cannot look at the code and dont have any access to change the code,i googled it,after some reserach got to know i can do it with custom settings,but no blog has complete information,can any one help me out to resolve this issue,without using any code.

Thanks!
 
I was working on the Customize Your Login Process with My Domain module and I accidentally changed my domain of my Hands-On Org. Is it possible to change it back to what it was? I get an error message now when I try to launch my hands-on org. L

My former Hands On Org. URL is as follows: curious-badger-397879-dev-ed.my.salesforce.com

The domain I changed it to is: mylightsaber.dom-dev-ed.my.salesforce.com
 
NOT (ISPICKVAL( Transfer_ID__r.Transfer_Type__c , 'Store to WHS') AND (Shipping_Quantity__c > Serial_No__r.Quantity_available__c ))

I am getting ) missing in thie validation rule, Can someone 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?