• sfadm sfadm
  • NEWBIE
  • 185 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 34
    Questions
  • 14
    Replies
I have two related custom objects. I'll name them:
"Custom_Object1__c"
and 
"Custom_Object2__c".

In the "Custom_Object2__c" I have a lookup field to "Custom_Object1__c". In "Custom_Object1__c" I have a related list with "Custom_Object2__c".
In "Custom_Object2__c" I also have a checkbox field. When changing the state of the checkbox I need in the "Custom_Object2__c" trigger to get all checked "Custom_Object2__c" records of "Custom_Object1__c".

I've implemented a code in the trigger and I'm trying to get all checked "Custom_Object2__c" records via the following query:[SELECT checkbox__c, Custom_Object2_Status__c, Id FROM Custom_Object1__c where id =:Custom_Object1_ID__c]

The issue I have is that the query returns old data which is before the update of the record.

For instance I have four out of 4 checked Custom_Object2__c records but in the trigger the query returns 3 instead of 4 checked.

How can I get the actual data?
I have a process builder with several flows. I also have a validation rule. Both the validation rule and the process builder are applicable for one and the same custom object. It is possible the custom object to pass though one of the flows and such flow can change the custom object in a way that the conditions in the validation rule to return true. In that case the flow cannot pass and the following error message is received:
The record couldn’t be saved because it failed to trigger a flow. A flow trigger failed to execute the flow with version ID 3015E0000008BxE. Flow error messages: An unhandled fault has occurred in this flow
An unhandled fault has occurred while processing the flow. Please contact your system administrator for more information. Contact your administrator for help.

What I would like to know in this situation is how to display only the message from the validation rule and to avoid the above error?
When uploading a file via the Visualforce `apex:inputFile` standard component, if the file size exceeds the 3Mb limit I would like to display a message to the user that the file is greater than 3Mb and cannot be uploaded into the system.
Please advise how this can be achieved on VisualForce level?
I'm using the following code to Parse CSV file in Apex:
public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) {
    List<List<String>> allFields = new List<List<String>>();

    // replace instances where a double quote begins a field containing a comma
    // in this case you get a double quote followed by a doubled double quote
    // do this for beginning and end of a field
    contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
    // now replace all remaining double quotes - we do this so that we can reconstruct
    // fields with commas inside assuming they begin and end with a double quote
    contents = contents.replaceAll('""','DBLQT');
    // we are not attempting to handle fields with a newline inside of them
    // so, split on newline to get the spreadsheet rows
    List<String> lines = new List<String>();
    try {
        lines = contents.split('\n');
    } catch (System.ListException e) {
        System.debug('Limits exceeded?' + e.getMessage());
    }
    Integer num = 0;
    for(String line : lines) {
        // check for blank CSV lines (only commas)
        if (line.replaceAll(',','').trim().length() == 0) break;

        List<String> fields = line.split(',');  
        List<String> cleanFields = new List<String>();
        String compositeField;
        Boolean makeCompositeField = false;
        for(String field : fields) {
            if (field.startsWith('"') && field.endsWith('"')) {
                cleanFields.add(field.replaceAll('DBLQT','"'));
            } else if (field.startsWith('"')) {
                makeCompositeField = true;
                compositeField = field;
            } else if (field.endsWith('"')) {
                compositeField += ',' + field;
                cleanFields.add(compositeField.replaceAll('DBLQT','"'));
                makeCompositeField = false;
            } else if (makeCompositeField) {
                compositeField +=  ',' + field;
            } else {
                cleanFields.add(field.replaceAll('DBLQT','"'));
            }
        }

        allFields.add(cleanFields);
    }
    if (skipHeaders) allFields.remove(0);
    return allFields;       
}
The code was taken from the following article:https://developer.salesforce.com/page/Code_Samples#Parse_a_CSV_with_APEX
After I invoke the method the return result is giving me incorrect new line on incorrect place.
Here is the result I received in the debug log: 
User-added image
I was looking at the code but not able to figured out why there is a new line before the closing bracket?
Please advise.
I'm trying to retrieve the record type Name of the Lead object in the following piece of code:
Lead objLead;
//constructor
        public LeadToMerchantController(ApexPages.StandardController controller) {    
                objLead = (Lead)controller.getRecord();
            }
        ...
            String leadType = objLead.RecordType.Name;
                    System.debug('leadType ' + leadType);

but instead I receive 'Null' as a value of 'leadType'.
Please advise how to retrieve the name of the Lead record type?
I have implemented the following piece of code in my controller class:
Integer csvFileSize = csvFileBody.size();
        if(csvFileSize >= Constants.MAX_FILE_SIZE) {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, 'The CSV file exceeded the maximum file size limit.' );
            ApexPages.addMessage(myMsg);
            return;
        }
to validate the blob size.

 I set maximum size to:
Integer MAX_FILE_SIZE = 3 * 1024 * 1024;

I've started to implement the following test method:

public static testmethod void testBlob() {
                Test.startTest();
                String fileBody = myBlob.toString();
                Integer csvFileSize = myBlob.size();                
                Test.stopTest();
}

Please advise how to be able to test the blob size as well as to cover the validation in my controller class?
In the following piece of code:
List<String> necessaryColumns = new List<String> {'columnA', 'columnB', 'columnC', 'columnD', 'columnE', 'columnF','columnG'};    
Set<String> columnsInFile = new Set<String>(necessaryColumns);
            System.debug('columnsInFile' + columnsInFile);
            // Get all column names from the CSV file
            List<String> columnNames = csvRecords.get(0);
            for(String columnName :columnNames) {
                System.debug('columnName: ' + columnName);
                if(!columnsInFile.contains(columnName)) {
                    System.debug('clmnName: ' + columnName);
                    ApexPages.Message myMessage = new ApexPages.Message(ApexPages.Severity.FATAL, 'The uploaded file is invalid');
                    ApexPages.addMessage(myMessage);
                    return;      
                }
            }
The issue I have is that the names of the columns in the set are in strict order.
|DEBUG|columnsInFile{columnA, columnB, columnC, columnD, columnE, columnF, columnG}
and if the order of the columns in the CSV file is changed for instance:
columnG, columnF, columnD, columnC, columnA, columnB
The algorithm is entering the if block and is showing the message, which is totally wrong.
What I'm trying to achieve is to show the message only if one of the columns in the CSV file is missing.
If there are 20 columns in the CSV file but for instance columnA is missing in the file only then the ApexPages.Message has to be displayed for the users.
Please advise how this can be achieved with apex?


 
As described in the following article:
​https://developer.salesforce.com/forums/?id=906F0000000BPXxIAO
I make the suggested validation to finind out if the uploaded file is ".csv" or not. Therefore I'm using the suggested try/catch in my controller class 
blob docBlob = doc.body;
string blobString;
try
{
blobString = docBlob.toString();
}
catch(Exception e)
    {
        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please upload a valid CSV document');
        ApexPages.addMessage(myMsg); 
        return ;   
    }

The try/catch is working for specific file formats such as:
".pdf" , ".xlsx", ".docx".

But when I try to upload files with the following file formats:
".log", ".eml", ".cls"
they become successfully uploaded in Salesforce, creating hundreds of records in Salesforce which is totaly wrong and inadmissable.

Please advise how to adjust the try/catch block in order to allow only ".csv" file formats to be uploaded?
 

I have a blob object which is a CSV file and I need a method to return all lines from that file in the following data structure:
List<List<String>>
where each element of that data structure
(List<String>)
is a separate line in the file.

Please advise how this can be achieved and implemented?
Please advise how to move dynamic HTML code from my controller class into VF page.

My VF page implementation:
<apex:page standardController="task" extensions="SomeController">
 <apex:stylesheet value="{!$Resource.Task}"/>
  <apex:form >
   <apex:pageBlock >
       <apex:pageMessages escape="false"/> 
   </apex:pageBlock>
 </apex:form>
I have the following HTML code implemented in controller class:
public SomeController(ApexPages.StandardController controller) {
        objTask = (Task)controller.getRecord();
        String resultAll = buildTemplate(objTask);
        ApexPages.Message infoPage = new 
        ApexPages.Message(ApexPages.Severity.INFO, resultAll);
        ApexPages.addMessage(infoPage);
    }

public String buildTemplate(Task task) {

        ...

        String pageHTMLContent = '<HTML><HEAD></HEAD><BODY><TABLE class="task_history_class">';
        pageHTMLContent += '<TR><TH>Value1</TH><TH>Value2</TH><TH>Value3</TH><TH>Value4</TH>';
        for(Task_Activity_History__c taskActivityHistory :listTaskActivityHistory) {
            String oldValue = taskActivityHistory.Old_Value__c;
            if(oldValue == null || oldValue.equals('')) {
                oldValue = '&nbsp;';
            }
            String newValue = taskActivityHistory.New_Value__c;
            if(newValue == null || newValue.equals('')) {
                oldValue = '&nbsp;';
            }
            String userName = '&nbsp;';
            Id userId = taskActivityHistory.LastModifiedById;
            if(userId != null) {
                User user = usersMap.get(userId);
                if (user != null) {
                    userName = user.Name;
                }
            }

            DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
            if(lastModifiedByDate == null) {
                oldValue = '&nbsp;';
            }
            pageHTMLContent += '<TR>';
            pageHTMLContent += '<TD>' + oldValue + '</TD><TD>' + newValue + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
            pageHTMLContent += '</TR>';
        }
        pageHTMLContent += '</TABLE></BODY></HTML>';
        return pageHTMLContent;
    }
With this row
ApexPages.addMessage(infoPage);
I add dynamically generated HTML code in my VF page.

Please advise how to move the entire HTML code including the dynamically generated HTML from my controller class into my VF page?


 
When I try to deploy on my production environment I receive the following error message:
Apex CPU time limit exceeded and An unexpected error has occurred. Your development organization has been notified.
The last method in stacktrace where the error happens is my custom method.

I presume that the error is due to the fact that some of the other methods is taking considerable amount of time to be executed.

Please advise how to realize which is the method that is trowing such error and is consuming the entire cpu time.

Please advise how to avoid such error because I really need to find a solution as every time I try to deploy on production I receive such error message:

Apex CPU time limit exceeded and An unexpected error has occurred. Your development organization has been notified.
 
I have a controller class with the following method implementation:
public String buildTemplate(Task task) {

    Id taskId = task.Id;

    List<Task_History__c> listTaskHistory = [SELECT Field1, Id, Field2, Username__c, LastModifiedDate FROM Task_History__c WHERE Task_ID__c = :taskId];
    String pageHTMLContent = '<HTML><HEAD><STYLE>{! $Resource.Stylesheet }</STYLE></HEAD><BODY><TABLE class="css_class">';
    pageHTMLContent += '<TR><TH>Comment1</TH><TH>Comment2/TH><TH>Last Modified By</TH><TH>Last Modified Date</TH>';

    for(Task_History__c taskHistory :listTaskHistory) {
        String oldValue = taskHistory.Old_Value__c;
        String newValue = taskActivityHistory.New_Value__c;
        String userName = taskActivityHistory.Username__c;
        DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
        pageHTMLContent += '<TR>';
        pageHTMLContent += '<TD>' + oldValue + '</TD><TD>' + newValue + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
        pageHTMLContent += '</TR>';
    }

    pageHTMLContent += '</TABLE></BODY></HTML>';

    return pageHTMLContent;
}
I'd like to know how to include the contents of a static resource file in controller class?
In the Static Resource I have a file called "Stylesheet" with content:
table.css_class , .css_class th, .css_class td { border: 1px solid black; padding: 10px; } table.css_class th { text-align: center; }
Please advise how to include the contents of a static resource file in controller class?

 
Hello,

I have the following error message:
Error: Illegal assignment from Schema.SObjectField to Id
when I try to update lookup field in apex.

Here is the method implementation:
public void addTaskCommentHistory(Task task) {
    if(task == Null) {
            return;
    }

    String newValue = task.Description;

    if(newValue != Null && !newValue.equals('')) {
        String taskId = task.Id;
        String fieldName = 'Comments';
        String oldValue = '';

        Task_History__c taskHistory = new Task_History__c();
        taskHistory.Task_ID__c = taskId;
        taskHistory.Field_Name__c = fieldName;
        taskHistory.Old_Value__c = oldValue;
        taskHistory.New_Value__c = newValue;


        String lastModifiedBy = task.LastModifiedById; 
        String userName = '';
        // the query will return no more than one row because the data is extracted by user id
        List<User> listOfUsers = [SELECT Name FROM User where Id = :lastModifiedBy];
        if(listOfUsers.size() > 0){
            User user = listOfUsers.get(0);
            userName = user.Name;
        }

        taskHistory.User__c = user.Name;

        insert taskHistory;
    }    
}

When I try to add
user.Name
to
taskHistory.User__c
in
taskHistory.User__c = user.Name;
I get the "Error: Illegal assignment from Schema.SObjectField to Id" message.

Please advise how to update the User__c lookup field without the error message?


 
I have the following method 
public String buildTemplate(Task task) {
       
        Id taskId = task.Id;
        List<Task_History__c> listTaskHistory = [SELECT Field1, Id, Field2, Username__c, LastModifiedDate FROM Task_History__c WHERE Task_ID__c = :taskId];
        String pageHTMLContent = '<HTML><HEAD><STYLE>table.css_class , .css_class th, .css_class td { border: 1px solid black; padding: 10px; } table.css_class th { text-align: center; } </STYLE></HEAD><BODY><TABLE class="css_class">';
        pageHTMLContent += '<TR><TH>Comment1</TH><TH>Comment2/TH><TH>Last Modified By</TH><TH>Last Modified Date</TH>';
        System.debug('pageHTMLContent ' + pageHTMLContent);
        for(Task_History__c taskHistory :listTaskHistory) {
            String oldValue = taskHistory.Old_Value__c;
            String newValue = taskActivityHistory.New_Value__c;
            String userName = taskActivityHistory.Username__c;
            DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
            pageHTMLContent += '<TR>';
            // '<a href="' + mainURL + '">' + LeadId + '</a>';
            // '<a href="realURL">accountId</a>'
            //String mainAccURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + accountId;
            pageHTMLContent += '<TD>' + oldValue + '</TD><TD>' + newValue + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
            pageHTMLContent += '</TR>';
        }
        pageHTMLContent += '</TABLE></BODY></HTML>';
        return pageHTMLContent;
    }

in my controller class.

Please advise how to move the css "String pageHTMLContent = '<HTML><HEAD><STYLE>table.css_class , .css_class th, .css_class td { border: 1px solid black; padding: 10px; } table.css_class th { text-align: center; } </STYLE></HEAD><BODY><TABLE class="css_class">';" part into a Visual Force page or external file?

I'll strognly appreciate if you can provide an example.

Thank you

I'm using the after update trigger to update the "BillingCity" field in the Account object and make the field in proper case.
 
trigger on Account (after update) {

            String billingCity = Account.billingCity;

            toTitleCase(billingCity);
}

And the code in the invoked toTitleCase(billingCity) method:
 
//converts a given string to Title Case where the
//first letter of every word is capitalised and the rest are small
public String toTitleCase(String billingCity) {
   System.debug('billingCity ' + billingCity);
   String titlePhrase = '';
   //a set of words that should always be in lower case when in Title Case
   Set<String> forceLower = new Set<String>{'of', 'the', 'for', 'and', 'a', 'to', 'at' ,'an', 'but', 'if', 'or', 'nor'};

   if(billingCity != null && billingCity.length() > 0){
      String[] splitPhrase = billingCity.trim().split(' ');

      for(integer i = 0; i < splitPhrase.size(); i++){
          if(!forceLower.contains(splitPhrase[i].toLowerCase()) || i == 0 || i == (splitPhrase.size()-1) ) {
             titlePhrase += (splitPhrase[i].substring(0,1).toUpperCase())+(splitPhrase[i].substring(1).toLowerCase())+' ';

          } else {
               titlePhrase += splitPhrase[i].toLowerCase()+' ';

               }
          }
       }

       return titlePhrase.trim();
}
In the debug log I can see that the "BillinCity" field is updated with the proper case:
 
17:00:57:945 USER_DEBUG [40]|DEBUG|billingCity San Marino
but on a record level the field remains with upper case: "SAN MARINO"

Please advise an appropriate solution.

 
I'm getting this error while running this VF Page
 
Error: SObject row was retrieved via SOQL without querying the requested field: Task.LastModifiedById

An unexpected error has occurred. Your development organization has been notified.

VF Page:

<apex:page standardController="task" extensions="TaskHistoryController">
  <apex:form >
   <apex:pageBlock >
       <apex:pageMessages escape="false"/> 
    </apex:pageBlock>
  </apex:form>   
</apex:page>

Controller:
public with sharing class TaskHistoryController {



Task objTask;
String objTaskId;

public TaskHistoryController(ApexPages.StandardController controller) {
    objTask = (Task)controller.getRecord();
    Id taskId = objTask.Id;
    List<Task_Activity_History__c> listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId]; 
    Task_Activity_History__c taskHistory1 = listTaskActivityHistory.get(0);
    Task_Activity_History__c taskHistory2 = listTaskActivityHistory.get(1);
    String newValue1 = taskHistory1.New_Value__c;
    String newValue2 = taskHistory2.New_Value__c;
    String resultAll = buildTemplate(objTask);
    ApexPages.Message infoPage = new ApexPages.Message(ApexPages.Severity.INFO, resultAll);
    ApexPages.addMessage(infoPage);
}

public String buildTemplate(Task task) {
    Id lastModifiedBy = task.LastModifiedById;
    String userName = '';
    List<User> listOfUsers = [SELECT Id, IsActive, LastModifiedById, Name FROM User where Id = :lastModifiedBy];
    for(User user :listOfUsers) {
        userName = user.Name;
    }
    Id taskId = task.Id;
    List<Task_Activity_History__c> listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId];
    String pageHTMLContent = '<HTML><HEAD><STYLE>table.user_class, .user_class th, .user_class td { border: 1px solid black; padding: 10px; } table.user_class th { text-align: center; } </STYLE></HEAD><BODY><TABLE class="user_class">';
    pageHTMLContent += '<TR><TH>Comment Old Value</TH><TH>Comment New Value</TH><TH>Last Modified By</TH><TH>Last Modified Date</TH>';
    for(Task_Activity_History__c taskActivityHistory :listTaskActivityHistory) {
        String newValue1 = taskActivityHistory.Old_Value__c;
        String newValue2 = taskActivityHistory.New_Value__c;
        String lastModifiedById = taskActivityHistory.LastModifiedById;
        DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
        pageHTMLContent += '<TR>';
        pageHTMLContent += '<TD>' + newValue1 + '</TD><TD>' + newValue2 + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
        pageHTMLContent += '</TR>';
        System.debug('pageHTMLContent7 ' + pageHTMLContent);
    }
    pageHTMLContent += '</TABLE></BODY></HTML>';

    return pageHTMLContent;
}
Please advise an appropriate solution.
Hello,

I'd like to know is there a formula or some other feasible way in Salesforce to set Camel case?

I have data entered into the fields of all upper or all lower case. I need "SALESFORCE FORMULA" , to be dispalyed like "Salesforce Formula".

Please advise how this can be achieved in Salesforce?
I need a validation in the Biliing Post Code code field to prevent users from typing and entering City and Coutry into the Post Code field the way it is displayed in the followng image
User-added image
Please advise how such validation can be achieved?
I have an Application object an in the Application object I have list with custom CC App records.

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

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

When I try to save the value

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

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

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

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

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

Please advise how this can be achieved?
I keep getting the following error message:
FATAL_ERROR System.NullPointerException: Class.System.BusinessHours.diff:
Here is the stacktrace:
16:12:53.0 (303362690)|FATAL_ERROR|System.NullPointerException: Start date cannot be null
Class.System.BusinessHours.diff: line 23, column 1
Class.CCApprovalHandler.calculateWorkingHours: line 36, column 1
Class.CCApprovalHandler.processRiskRecords: line 188, column 1
Class.CCApprovalHandler.calculateAverageResponceTime: line 289, column 1
Class.CCApprovalHandler.beforeUpdate: line 341, column 1
Class.TriggerFactory.execute: line 93, column 1
Class.TriggerFactory.createHandler: line 27, column 1
Trigger.CCApprovalTrigger: line 2, column 1
16:12:53.0 (303383089)|FATAL_ERROR|System.NullPointerException: Start date cannot be null
and part of the source code where the exception happens:
 
private Double calculateWorkingHours(Datetime createdDate, Datetime completedDate) {
        List<BusinessHours> bhList = [SELECT id FROM BusinessHours WHERE IsDefault=true AND Name='Test Business Hours'];
        if(bhList.size() == 0) {
            return -1;
        }

        String bhId = bhList.get(0).id;
        System.debug('bhId ' + bhId);

        //is line 36 where the exception happens
        Long businessMillis = BusinessHours.diff(bhId, createdDate, completedDate);

        System.debug('businessMillis ' + businessMillis);
        Boolean areMillisZero = false;
        if(businessMillis == 0) {
            areMillisZero = true;
        }

        Integer bMinutes = (Integer)(businessMillis/1000)/60;
        Integer bHours = bMinutes/60;
        Integer bReminder = Math.mod(bMinutes, 60);
        Double hoursToAdd = 0;
        if(bReminder == 0) {
             hoursToAdd = 0;
        } else if(bReminder <= 30) {
             hoursToAdd = 0.5;
        } else {
             hoursToAdd = 1;
        }

        Double realBHours = bHours + hoursToAdd;
        if(realBHours == 0 && !areMillisZero) {
            realBHours = 0.5;
        }

        return realBHours;
    }
The line 36 is indicated in the comment above the row where the exception happens.

I'm also executing this method in beforeUpdate trigger.

Please advise how to avoid such exception?


 
In the following piece of code:
List<String> necessaryColumns = new List<String> {'columnA', 'columnB', 'columnC', 'columnD', 'columnE', 'columnF','columnG'};    
Set<String> columnsInFile = new Set<String>(necessaryColumns);
            System.debug('columnsInFile' + columnsInFile);
            // Get all column names from the CSV file
            List<String> columnNames = csvRecords.get(0);
            for(String columnName :columnNames) {
                System.debug('columnName: ' + columnName);
                if(!columnsInFile.contains(columnName)) {
                    System.debug('clmnName: ' + columnName);
                    ApexPages.Message myMessage = new ApexPages.Message(ApexPages.Severity.FATAL, 'The uploaded file is invalid');
                    ApexPages.addMessage(myMessage);
                    return;      
                }
            }
The issue I have is that the names of the columns in the set are in strict order.
|DEBUG|columnsInFile{columnA, columnB, columnC, columnD, columnE, columnF, columnG}
and if the order of the columns in the CSV file is changed for instance:
columnG, columnF, columnD, columnC, columnA, columnB
The algorithm is entering the if block and is showing the message, which is totally wrong.
What I'm trying to achieve is to show the message only if one of the columns in the CSV file is missing.
If there are 20 columns in the CSV file but for instance columnA is missing in the file only then the ApexPages.Message has to be displayed for the users.
Please advise how this can be achieved with apex?


 

I have a blob object which is a CSV file and I need a method to return all lines from that file in the following data structure:
List<List<String>>
where each element of that data structure
(List<String>)
is a separate line in the file.

Please advise how this can be achieved and implemented?
I'm getting this error while running this VF Page
 
Error: SObject row was retrieved via SOQL without querying the requested field: Task.LastModifiedById

An unexpected error has occurred. Your development organization has been notified.

VF Page:

<apex:page standardController="task" extensions="TaskHistoryController">
  <apex:form >
   <apex:pageBlock >
       <apex:pageMessages escape="false"/> 
    </apex:pageBlock>
  </apex:form>   
</apex:page>

Controller:
public with sharing class TaskHistoryController {



Task objTask;
String objTaskId;

public TaskHistoryController(ApexPages.StandardController controller) {
    objTask = (Task)controller.getRecord();
    Id taskId = objTask.Id;
    List<Task_Activity_History__c> listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId]; 
    Task_Activity_History__c taskHistory1 = listTaskActivityHistory.get(0);
    Task_Activity_History__c taskHistory2 = listTaskActivityHistory.get(1);
    String newValue1 = taskHistory1.New_Value__c;
    String newValue2 = taskHistory2.New_Value__c;
    String resultAll = buildTemplate(objTask);
    ApexPages.Message infoPage = new ApexPages.Message(ApexPages.Severity.INFO, resultAll);
    ApexPages.addMessage(infoPage);
}

public String buildTemplate(Task task) {
    Id lastModifiedBy = task.LastModifiedById;
    String userName = '';
    List<User> listOfUsers = [SELECT Id, IsActive, LastModifiedById, Name FROM User where Id = :lastModifiedBy];
    for(User user :listOfUsers) {
        userName = user.Name;
    }
    Id taskId = task.Id;
    List<Task_Activity_History__c> listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId];
    String pageHTMLContent = '<HTML><HEAD><STYLE>table.user_class, .user_class th, .user_class td { border: 1px solid black; padding: 10px; } table.user_class th { text-align: center; } </STYLE></HEAD><BODY><TABLE class="user_class">';
    pageHTMLContent += '<TR><TH>Comment Old Value</TH><TH>Comment New Value</TH><TH>Last Modified By</TH><TH>Last Modified Date</TH>';
    for(Task_Activity_History__c taskActivityHistory :listTaskActivityHistory) {
        String newValue1 = taskActivityHistory.Old_Value__c;
        String newValue2 = taskActivityHistory.New_Value__c;
        String lastModifiedById = taskActivityHistory.LastModifiedById;
        DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
        pageHTMLContent += '<TR>';
        pageHTMLContent += '<TD>' + newValue1 + '</TD><TD>' + newValue2 + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
        pageHTMLContent += '</TR>';
        System.debug('pageHTMLContent7 ' + pageHTMLContent);
    }
    pageHTMLContent += '</TABLE></BODY></HTML>';

    return pageHTMLContent;
}
Please advise an appropriate solution.
In my code
trigger ContactRole on Application__c (before update) {

// Get the time between the last aTeam and bTeam
                DateTime lastUWCreated = lastCCUW.Created_Date__c;
                System.debug('lastUWCreated ' + lastUWCreated);
                DateTime lastAmTeamCreated = lastCCRiskAndChecked.Created_Date__c;
                System.debug('lastAmTeamCreated ' + lastAmTeamCreated);
                
                Double workingHours = calculateWorkingHours(lastUWCreated, lastAmTeamCreated);
                System.debug('workingHours ' + workingHours);
                Id ccAppId = lastAmTeamCreated.Id;
                
                List<Application__c> ccAppList = [SELECT CalculatedWorkingHours__c from Application__c where id = :ccAppId];
                Application__c appRecord = ccAppList.get(0);
                appRecord.CalculatedWorkingHours__c = workingHours;
                System.debug('appRecord.CalculatedWorkingHours__c ' + appRecord.CalculatedWorkingHours__c);
}

I'm using the before update trigger in order to populate the calculated working hours into a custom field called "CalculatedWorkingHours__c".

I can see in the debug log that the  "CalculatedWorkingHours__c" field is updated
 
USER_DEBUG [184]|DEBUG|workingHours 17.5

USER_DEBUG [194]|DEBUG|ccAppRecord.CalculatedWorkingHours__c 17.5
but on a record level the field remains blank

Please advise what can be the issue and why the field is not populated in the record?
Hello,

I have setup a new SalesForce environment and I have to transfer my Apex classes on it.

In order to deploy my code I use a test class with test methods.

A validation process is started when I try to deploy the changes.

This validation invokes all existing test methods and the environment throws the following exception:
System.LimitException: Apex CPU time limit exceeded

Oddly enough on the old environment there is no such exceptions

I'm sending you a method of my source code where the Apex CPU time limit exceeded is most likely to happen:
 
private List<LeadConversionContainer> checkByWebsite(Lead leadObj) {
        List<LeadConversionContainer> accountWebsites = new 
        List<LeadConversionContainer>();
        String website = leadObj.Website;
        String leadId = leadObj.Id;
        List<Account> accWebsiteList = [SELECT Website, Url__c, Status__c FROM 
        Account];
        if(website != null && !website.equals('') && accWebsiteList != null) {
            List<String> leadWebsites = extractWebsites(website);
            for (String leadUrl : leadWebsites) {
                String normWebsite = normalizeWebsite(leadUrl);
                String leadWebsite = normWebsite.trim();
                for(Account acc : accWebsiteList) {
                    String accountWebsite = acc.Url__c;
                    String accountId = acc.Id;
                    List<String> extractedAccountWebsite = 
                    extractWebsites(accountWebsite);
                    for(String accWebsite :extractedAccountWebsite) {
                        String accountSite = normalizeWebsite(accWebsite);
                        if(accountSite != null) {
                            List<String> leadSplitWebsitesList = leadWebsite.split('[,;\\s]');
                            for(String leadSplitUrls :leadSplitWebsitesList) {
                                if(accountSite.equals(leadSplitUrls)) {
                                    boolean isAccountStatusActive = isAccountActive(acc);
                                    boolean isMerchantApplication = 
                                    isMerchantApplicationsAttached(acc);
                                    if(isAccountStatusActive || isMerchantApplication) {
                                        String reasonToStopConversion = 'Lead Website coincide with 
                                        Account Website';
                                        LeadConversionContainer leadConvert = new 
                                        LeadConversionContainer(acc.Id, '', reasonToStopConversion);
                                        accountWebsites.add(leadConvert);
                                    }
                                }    
                            }
                        }
                    }
                }    
            }
        }
        return accountWebsites;
    }

Please advise how to solve the issue with my deploy and avoid such System.LimitException: Apex CPU time limit exceeded exception?
I have an apex source code where I have plenty of if/else conditions which depend on the business hours Mon - Fri 9h - 18h settings in Salesforce.
I'm creating a test method to validate my code but because of the business hours settings the apex code enters only in few if conditions.
And I cannot reach the necessary percentage to validate my code.

Is it possible in the test method to change the business hours so that I can validate my code on 100% or is there a way to validate my code despite the fact that it is depending on the business hours?
Hello,

When the priority in a task is changed I calculate dynamically the calendar hours.

The calculated calendar hours are set and updated in a custom field called "timeframe".

After the value in the "timeframe" field is changed I want to send an e-mail alert based on the number of hours set in the "timeframe" field.

Example: If task priority is set to "High", the calendar hours in the "timeframe" filed will be 23 hours.

I want to know how to send an e-mail alert after 23 hours?

Could you please advise how to do that in Salesforce?
I need to get the current time but to be in type DateTime.

I use:
DateTime now = System.now();
but it returns wrong time.

I execute the code in 2017-08-04 00:38:46 AM

but it returns
00:38:46:023 USER_DEBUG [138]|DEBUG|now 2017-08-03 21:38:46
How can I get my correct current local time 2017-08-04 00:38:46?

I had even tried with:
DateTime now = DateTime.parse(System.Now().format());
but I still get wrong time.
01:10:09:021 USER_DEBUG [139]|DEBUG|now 2017-08-03 22:10:00
How can I get the correct current local time?



 
I have an object of type Time startWorkingTime and object of type DateTime nextBusinessDay. I want to create new object of type DateTime based on startWorkingTime and nextBusinessDay.
Here is my code:
DateTime startWorkingTime = DateTime.newInstance(nextBusinessDay.year(), nextBusinessDay.month(), nextBusinessDay.day(), currentStartHours.hour(), currentStartHours.minute(), currentStartHours.second());
After startworkingtime the time is set one hour earlier
For example:
23:59:24:025 USER_DEBUG [188]|DEBUG|currentStartHours 09:00:00.000Z
23:59:24:025 USER_DEBUG [189]|DEBUG|currentStartHours.hour() 9
23:59:24:025 USER_DEBUG [197]|DEBUG|startWorkingTime 2017-08-04 08:00:00
Could you please explain why the hour in startWorkingTime is 08:00:00 and advise how to fix it?


 

I need to calculate the out of office hours in apex.

The hours are:
6 pm – 9 am Mon – Fri
and
6 pm on Fri till 9 am on Mon

I've already configured the Business Hours:

Monday09:00to18:00
Tuesday09:00to18:00
Wednesday09:00to18:00
Thursday09:00to18:00
Friday09:00to18:00
Saturday24 Hours
Sunday24 Hours

and activate it in Salesforce.

Please advise how it can be achieved in apex?

Hello,

I have a custom vf page which is controlling the conversion process from Lead to Account. What I'd like to achieve is that once I convert the system to automatically redirect to the opportunity page. Could you please advise how this can be achieved?
Hello,

I'd like to know how to display a dialog or pop up window in Salesforce.

I'm using a convert button with associated custom visualforce page. I use custom visualfoce page to invoke appex controller class.

Depending on the given parameters the appex class the end result of the class is to return a message. The message is displayed in a visualforce page(see the attached screenshot).Custom Visualforce page

What I would like to know is how to dispaly a message in a dialog or a pop-up window instead of entire visualforce page.

Here is what I would like to achive:
Once the convert button is pressed(see the attached screenshot)Standard Convert Page
I would like to know how to dispaly the message in a dialog or a pop-up window.

Could you please advise how this can be achieved?

 
I have an existing workflow and some part of the workflow involves approval process for opportunities. During the approval process Opportunity object is locked. The unlock takes place at the end of the approval process. The lock for Opportunity object can not be removed in administrative way. What I strive to achieve is during the approval process the Opportunity object to be unlocked. There are two apex methods to lock and unlock in the Approval class but I'm not aware where to use those methods and which apex method and apex class exactly is invoked when the approval process is submitted. Please advise which apex method is invoked when the approval process is submitted.