Monday, January 30, 2012

Case History Related List

Component VF Code:


<apex:component controller="CaseHistoriesComponentController">
    <!-- Attribute Definition -->
    <apex:attribute name="CaseId" description="Salesforce Id of the Case whose Case History needs to be rendered" type="Id" required="true" assignTo="{!caseId}" />
    
    <!-- Case History Related List -->
    <apex:pageBlock title="Case History">
        <apex:pageBlockTable value="{!histories}" var="History" >
            <apex:column headerValue="Date"  value="{!History.thedate}"/>
            <apex:column headerValue="User"> <apex:outputLink value="/{!History.userId}"> {!History.who} </apex:outputLink></apex:column>
            <apex:column headerValue="Action"><apex:outputText escape="false" value="{!History.action}"/></apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:component>


Controller Code:



public class CaseHistoriesComponentController {
    
    public Id caseId {get; set;}
    public cHistories[] histories; 
    
    // Variables
    public Static final Map<String, Schema.SObjectField> CaseFieldmap = Schema.SObjectType.Case.fields.getMap();
    public Static final List<Schema.PicklistEntry> fieldPicklistValues = CaseHistory.Field.getDescribe().getPicklistValues();
    
    public List<cHistories> getHistories()
    {
        list<cHistories> histories = new list<cHistories>();
        String prevDate = '';
        for(CaseHistory cHistory : [Select CreatedDate, CreatedBy.Name, CreatedBy.Id, Field, NewValue, OldValue from CaseHistory where CaseId = :caseId order by CreatedDate desc])
        {
            if((cHistory.newValue == null && cHistory.oldValue == null) 
                    || (cHistory.newValue != null && !(string.valueOf(cHistory.newValue).startsWith('005') || string.valueOf(cHistory.newValue).startsWith('00G')))
                    || (cHistory.oldValue != null && !(string.valueOf(cHistory.oldValue).startsWith('005') || string.valueOf(cHistory.oldValue).startsWith('00G'))))
            {
                cHistories tempHistory = new cHistories();
                // Set the Date and who performed the action
                if(String.valueOf(cHistory.CreatedDate) != prevDate)
                {
                    tempHistory.theDate = String.valueOf(cHistory.CreatedDate);
                    tempHistory.who = cHistory.CreatedBy.Name;
                    tempHistory.userId = cHistory.CreatedBy.Id;
                }
                else
                {
                    tempHistory.theDate = '';
                    tempHistory.who = '';
                    tempHistory.userId = cHistory.CreatedBy.Id;
                }
                prevDate = String.valueOf(cHistory.CreatedDate);
                
                // Get the field label
                String fieldLabel = CaseHistoriesComponentController.returnFieldLabel(String.valueOf(cHistory.Field));
                
                // Set the Action value
                if (String.valueOf(cHistory.Field) == 'created') {    // on Creation
                    tempHistory.action = 'Created.';
                }
                else if(cHistory.OldValue != null && cHistory.NewValue == null){ // when deleting a value from a field
                    // Format the Date and if there's an error, catch it and re
                    try {
                        tempHistory.action = 'Deleted ' + Date.valueOf(cHistory.OldValue).format() + ' in <b>' + fieldLabel + '</b>.';
                    } catch (Exception e){
                        tempHistory.action = 'Deleted ' + String.valueOf(cHistory.OldValue) + ' in <b>' + fieldLabel + '</b>.';
                    }
                }
                else{  // all other scenarios
                    String fromText = '';
                    if (cHistory.OldValue != null) {
                        try {
                            fromText = ' from ' + Date.valueOf(cHistory.OldValue).format();
                        } catch (Exception e) {
                            fromText = ' from ' + String.valueOf(cHistory.OldValue);
                        }
                    }
                    
                    String toText = '';
                    if (cHistory.OldValue != null) {
                        try {
                            toText = Date.valueOf(cHistory.NewValue).format();
                        } catch (Exception e) {
                            toText = String.valueOf(cHistory.NewValue);
                        }
                    }
                    if(toText != '')
                        tempHistory.action = 'Changed <b>' + fieldLabel + '</b>' + fromText + ' to <b>' + toText + '</b>.';
                    else
                        tempHistory.action = 'Changed <b>' + fieldLabel;
                }
                
                // Add to the list
                histories.add(tempHistory);
            }
        }
        
        return histories;
    }   
    
    // Function to return Field Label of a Case field given a Field API name
    public Static String returnFieldLabel(String fieldName)
    {
        if(CaseHistoriesComponentController.CaseFieldmap.containsKey(fieldName))
            return CaseHistoriesComponentController.CaseFieldmap.get(fieldName).getDescribe().getLabel();
        else
        {
            for(Schema.PicklistEntry pickList : fieldPicklistValues)
            {
                if(pickList.getValue() == fieldName)
                {
                    if(pickList.getLabel() != null)
                        return pickList.getLabel();
                    else
                        return pickList.getValue();
                }
            }
        }
        return '';
    }
    // Inner Class to store the detail of the case histories    
    public class cHistories {


        public String theDate {get; set;}
        public String who {get; set;}
        public Id userId {get; set;} 
        public String action {get; set;}
    }
}

Case Comment Related List

Component VF Code:


<apex:component controller="CaseCommentsComponentController" allowDML="true">
    <!-- Attribute Definition -->
    <apex:attribute name="CaseId" description="Salesforce Id of the Case whose Case Comments needs to be rendered" type="Id" required="true" assignTo="{!caseId}" />
    
    <!-- Component Body -->
    <apex:componentBody >
        <apex:form >
            <apex:pageBlock title="Case Comments" >
                <apex:pageBlockButtons location="top">
                    <apex:commandButton action="{!NewComment}" value="New"/>
                </apex:pageBlockButtons>
                <apex:pageBlockTable value="{!Comments}" var="comment"> 
                    <apex:column headerValue="Action"> 
                        <apex:outputLink value="/{!comment.cComment.Id}/e?parent_id={!caseId}&retURL=/{!caseId}">Edit</apex:outputLink>&nbsp;&nbsp;
                        <apex:commandLink action="{!deleteComment}" value="Del">
                            <apex:param name="CommentId_d" value="{!comment.cComment.Id}"/>
                        </apex:commandLink>&nbsp;&nbsp; 
                        <apex:commandLink action="{!makePublicPrivate}" value="{!comment.PublicPrivateAction}">
                            <apex:param name="CommentId_p" value="{!comment.cComment.Id}" />
                        </apex:commandLink>
                    </apex:column>
                    <apex:column headerValue="Public" value="{!comment.cComment.IsPublished}" />
                    <apex:column headerValue="Comments">
                        <apex:outputText escape="false" value="{!comment.commentText}"/>
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlock>   
        </apex:form>    
    </apex:componentBody>
</apex:component>


Controller Code:


public with sharing class CaseCommentsComponentController {
    
    public Id caseId {get; set;}
    public cComments[] comments{
        get{
            List<cComments> comments = new List<cComments>();
            for(CaseComment comment : [Select LastModifiedDate, LastModifiedBy.Id, LastModifiedBy.Name, IsPublished, CreatedDate, CreatedBy.Id, CreatedBy.Name, CommentBody From CaseComment c where ParentId = :caseId order by c.LastModifiedDate desc])
            {
                cComments tempcComment = new cComments();
                tempcComment.cComment = comment;
                
                // Build String to display.
                tempcComment.commentText = '<b>Created By: <a href=\'/' + comment.CreatedBy.Id + '\'>' + comment.CreatedBy.Name + '</a> (' + comment.CreatedDate.format() + ') | ';
                tempcComment.commentText += 'Last Modified By: <a href=\'/' + comment.LastModifiedBy.Id + '\'>' +  comment.LastModifiedBy.Name + '</a> (' + comment.LastModifiedDate.format() + ')</b><br>';
                tempcComment.commentText += comment.CommentBody;
                
                if(comment.IsPublished)
                    tempcComment.PublicPrivateAction = 'Make Private';
                else
                    tempcComment.PublicPrivateAction = 'Make Public';
                //Add to list
                comments.add(tempcComment); 
            }
            return comments;
        }
        
        set;
    }
        
    public PageReference NewComment()
    {
        PageReference pr = new PageReference('/apex/new_comment?id='+caseId);
        pr.setRedirect(true);
        return pr;
    }
    
    public PageReference deleteComment()
    {
        Id commentId = ApexPages.currentPage().getParameters().get('CommentId_d');
        
        for(cComments Comment : comments)
        {
            if(Comment.cComment.Id == commentId)
            {   
                delete Comment.cComment;                
                break;
            }
        }
        
        PageReference pg = new PageReference('/' + caseId);
        pg.setRedirect(true);
        return pg;
    }   
    
    public PageReference makePublicPrivate()
    {
        Id commentId = ApexPages.currentPage().getParameters().get('CommentId_p');
        for(cComments Comment : comments)
        {
            if(Comment.cComment.Id == commentId)
            {   
                Comment.cComment.IsPublished = !Comment.cComment.IsPublished;
                if(Comment.cComment.IsPublished)
                    Comment.PublicPrivateAction = 'Make Private';
                else
                    Comment.PublicPrivateAction = 'Make Public';
                    
                update Comment.cComment;                
                break;
            }
        }
        PageReference pg = new PageReference('/' + caseId);
        pg.setRedirect(true);
        return pg;
    }
    
    public class cComments {
    
        public CaseComment cComment {get; set;}
        public String commentText {get; set;}
        public String PublicPrivateAction {get; set;}
    }
}