Showing posts with label tricks. Show all posts
Showing posts with label tricks. Show all posts

Thursday, February 2, 2012

Detecting the sObject type of Id's from ambiguous fields

When dealing with the OwnerId field, it is important to check if it is a User or a Group sObject you are dealing with before you start using it or you'll get errors. The Task object also has a few ambiguous fields that match up multiple Objects like the WhoId and the WhatId. In triggers and in other logic you will sometimes need to detect what the object is to either exclude or include it in the next bit of code. We dont want to iterate through code and update records if we don't need to, it will bog down the system. 


I have seen some of the ways out there that are used, particularly the one where you check if the first 3 letters of the ID is '500' or '300' but i do not think this is an accurate way of detection. I want one that the system tells me for sure what object it is. Unfortunately its not as dynamic as i would like it to be due to limitations in APEX, but it is still a much better detection than the above. 


I first made a helper class called GlobalHelper_IsSobjectType and populated it with a few methods that look like the following. It takes in the Id and after a check to make sure that an Id was actually passed and is not null, it try's to create an Object of that Type. If it can it will not fall into the Catch and will return true, other wise it will error and return false, but it will not error in a way that will halt your program from finishing(thus why its in a try catch). 




I made one for Account, Contact, Lead, User, and Opportunity since those are the ones I typically have to detect. When it comes to the OwnerId field I can just use the one for User since if it returns false i know its a group. I also found that I needed to Overload the method so it would work with string as well as Id: 




Ideally I was hoping to make the above but make it more dynamic so you pass the object type you wanted to detect as well as the id for the detecting. That way you would only need one method instead of one for each Object, but I have yet to find a way to make it work. Now of course you need to test the code, and I prefer as close to 100% coverage as possible so:






Questions?  
Twitter: @SalesForceGirl  or Facebook


Wednesday, February 1, 2012

APEX Trigger to Prevent Duplicate Object Records

One of the biggest issues in Org's that I have seen is with duplicate records. But what is the best way to prevent this? With an easy trigger of course! 


Let take the Contact object, in my Org, everything is keyed off email, so we shouldn't have more than one contact with the same email address. And we need to not only protect against new Contacts, but we also need to ensure that if a User updates the email on the Contact that it too is not already in use before the update occurs. In order for the User to know that they are trying to Insert or Update incorrectly we will have a field error show next to the email of the contact stating that one already exists.


Lets make(or update) a Contact trigger for before insert and before update. 






We are going to use a Map to store the id and email of each contact that comes into the trigger so we can use that to do a SOQL query later when its time to see if it already exists.  add the 'trigger.isBefore' even though we know this will only occur before, so that this can be easily extended in the future and we wont have to go back and change code.




Now we need to populate the map with the Contact info so we can use it in the SOQL query next. We should also send up an error if the batch of Contacts that is being iterated over in the trigger contains more than one of the same email. 




Now that we have the Map populated, or at least in theory it should be, we will query the DB to see if a Contact already exists with that email, and if so, show an error to the User, other wise do nothing and allow it to be inserted/updated. 






And thats it. You can of course make this much more robust, so it not only compares email but also name and phone number too. 


Questions?  
Twitter: @SalesForceGirl  or Facebook

Wednesday, December 28, 2011

easy double-click to edit related-list VF page

Often enough I am asked to make a custom VisualForce of a related list that is editable in a similar way to salesforce's native double click to edit. I have made them in a variety of ways, including adding images like salesforce's to indicate if a field is editable or locked etc. and some simpler ways like the one I am going to do now.

The Problem:
a sObject under Account(or any other obj) needs show on the Account page layout, but it also needs to be double-click to edit to make it easy for the reps to update key information on the fly without having to click into each sObject. (for this example we will use the Contact obj)


Setup:
First we need to create a controller extension so that it can sit in the page layout of the Account obj, and even though we are showing the contact obj, the extension needs to point to account otherwise it wont show up as an available VisualForce page to add on the layout.
ContactInLineEdit.cls
ContactInLineEdit.page

This is a standard controller extension setup, this allows the class to use the account id referenced in the URL when the page is accessed. Example page URL will be 'apex/ContactInLineEdit?id={!account.id}'

Now we should add the Contact list to the class so we can access it on the page in a apex:repeat, when we add it to the class, we only need to get the list on load of the page, and then again when we update the fields.
ContactInLineEdit.cls

On the page we will need to add the apex:form tag, along with an apex:outputpanel with an id so we can call it later in a rerender attribute on the update call. We will also add the CSS and jQuery files that will help us control the double-click to edit functionality. We then place the jQuery inside the outputpanel so when it rerenders it can reapply the jQuery to the page. I also prefer to use the jQuery.noConflict(); since I often run into issues with salesforce's JS conflicting with what I am trying to implement.
ContactInLineEdit.page

Now we need to add the apex:pagemessages so we can do error handling and we need to add the table for the apex:repeat to sit in. We will also add the apex:outputfiled's that will display in the related list on the page, we need to make sure that any field we reference here is also in the select query on the class.
ContactInLineEdit.page

Lets add in the loading icon for the update and a JS function to control it, and we should also add the edit fields to the table. To help control the conditional hiding and showing of the fields for the edit, we should add some div's with classes to reference in jQuery.
ContactInLineEdit.page
ContactInLineEdit.page

Lets add the double click functionality, first we need to add a class to the edit text in the action column  <span class="editLink">Edit</span> then we need to add a function so that everytime the nonEdit field (outputField) is double-clicked it will hide the outputField and show the inputField. We will also change the Edit text to Cancel and add a class to it so we know that row is in edit mode.

Now lets add the edit row/cancel row edits functionality, this will allow all editable fields in the row to be edited and if cancel is hit, it will undo all edits by retrieving the text from the hidden outputfield otherwise it will continue to show the updated text since we are just hiding and showing. We don't want to clear the fields cause that will potentially clear out the saved info if it gets saved by mistake. So by retrieving the info from the outputfield, we are able to set it back to what it was originally.
ContactInLineEdit.page

We will also need to update our edit action to use the new function, it will now look like this: <span class="editLink" onclick="EditMe(jQuery(this));">Edit</span>
At this point we need to make the update method and add it to the page, this will allow any edits made by the user to be saved, and then the list will rerender with the new information.
ContactInLineEdit.cls

ContactInLineEdit.page

And that it, simple. I didn't add it here, but field validation could be added to ensure its a proper email or phone number etc. In the style i made so that fields that were editable when the mouse hovered over it, the cursor would change to a pointer like it would when the mouse hovers over a link. This way the user knows the field is editable instead of having to add an image that could bog down the page load.

Questions?  
Twitter: @SalesForceGirl  or Facebook

Tuesday, May 31, 2011

What makes Elegant Code?

One of the things i love about programming is that there is always several different ways to accomplish a task. If you gave 10 programmers the same task, each would go about it in there own way, sure the result would be the same but the code will be completely unique.

I find that when i look at other programmers code, its almost like looking at an artist work, not to say that the code is a work of art, just unique and sometimes beautiful. Every programmer has there own way of doing things, tendencies that all make up the big picture of the code. The naming convention used, structure of the methods and even the way they went about accomplishing the task. It all contributes to the look and feel of the code. It also can show the skill of the programmer or artist, or lack there of. 

Code should be simplistic, elegant, beautiful. It should also be structured, and still 'flow' like a picture. So many times i look at code and often think of spaghetti, and cringe at the over complication of something that should only be one or two lines and not ten. And please don't get me wrong, i am always trying to learn new ways to improve my code, trying to find smarter ways to go about a problem, keeping an open mind to new ideas and concepts.

An example of what i mean, below is two lines, both of the same SOQL statement, both get the job done. But one, while not wrong, also isn't quite right.

Contact[] objContact = [select id, name from Contact where email ='someemail@email.com' limit 1];

Contact objContact = [select id, name from Contact where email = :sInEmail limit 1];

In the first SOQL statement, it is creating a list of Contacts even though the query is only returning one. It also has a 'hard-coded' variable which is never a good practice.  In the second, since we are only querying for one obj, it only creates a single object, also it uses a variable instead of string text. 

Now i know what you may be thinking, does that really make a difference in the elegance of the code? Yes. If we left it as the first statement, where it is returning a List of objs instead of a single obj, and all the proceeding methods would then have to accommodate for it, even thought it isn't necessary. Its like adding lines and logic that only complicate and so the code tends to look messy or clustered when it doesn't need to be. Keeping code simplistic is key. As a rule of thumb, I try to keep my methods under 10 lines total, and that includes all the curly brackets.

Here is another example of doing things different ways while still accomplishing the same task:

      public string mystring;

      public string getMystring()
      {
            return mystring;
      }

      public void setMyString(string s)
      {
            this.s = mystring;
      }

vs

          public string sInStringName{get;set;}

I hope I don't need to explain why the second is cleaner, but if you notice i use the variable name of 'sInStringName' instead of 'mystring', i do this for most variable's: 'lst' for list, 'obj' for sObjects, etc. this helps me identify what it is, along with what type. So if i am looking for a string, i know it will start with 's'. I also like to follow the camel hump approach where the first word in the name is lowercase and all words after have the first letter capitalized. When it comes to booleans i am still trying to decide if i like 'b' as in 'bInBoolean' or 'is' since it is a true false statement, which would look like 'isBoolean'. Its important that no matter what naming convention you choose, that you stick with it, for the whole project, if you don't like it, try tweaking it in the next project.

Questions? 

Twitter: @SalesForceGirl  or Facebook

Thursday, March 17, 2011

jQuery table sorter meets salesforce

jQuery is a powerful tool, and so I always use it in my APEX projects to help accomplish what I wouldn't be able to with just apex/html/css. One of the things I almost always include is the Tablesorter, but there are a few issues when trying to make it work with Salesfroce standard page markup tags. 
All the documentation for the tablesorter is on their page: Tablesorter, but some points to remember are that if you are using any apex:output(filed/text) that it wraps a span around the text and the tablesorter needs to know that, also if you use an 'a' tag it behaves differently as well. Also there seems to be an issue with using the default sorter params, ie letting the tablesorter pick them for you.
To show you a good example of the jQuery table sorter in action with salesforce, I will be using the 'User Info List' that I recently just updated with it.

(NOTE: that table sorter requires the class tablesorter  on the table tag in order to work)
Example Table markeup:
<td><apex:outputfield value="{!c.Email}" /></td>
<td>{!c.Name}</td>
<td><span><apex:outputfield value="{!c.Phone}" /></span></td>
<td><a target="_blank" href="/{!c.Id}" title="go to Contact">Contact</a></td>

JS markup:
//this checks the table for data on three levels
      //<td>the data</td> $(node).text();
      //<td><node>the data</node></td> $(node).next().text();
      //<td><node><node>the data</node></node></td> $(node).next().next().text();
//this ensures that the data is found no matter how many nodes it needs to transverse.
var myTextExtraction = function(node) 
{  
      var nodeText = $(node).text();
      if(nodeText == null || nodeText == ''){
            nodeText = $(node).next().text();
      }
      if(nodeText == null || nodeText == ''){
            nodeText = $(node).next().next().text();
      }
      return nodeText;
}
//example markup to use the node traversing and establish the sorter params
$("table").tablesorter({
       textExtraction: myTextExtraction,
       headers: {
           0: {sorter: 'text'},
           1: {sorter: 'text'},
           2: {sorter: 'text'},
           3: {sorter: 'text'},
           4: {sorter: 'shortDate'
       }
   });

Now lets look at the User-Info-List page, you'll notice that instead of using the standard apex:pageblocktable I am using a standard table, BUT I have included the style(classes/structure) of what the apex:pageblocktable would have... meaning that if you right click and view source on an apex:pageblocktable you will see the same as below (style/class wise minus a few things for my own customizations) and so when this page renders, it looks like an apex:pageblocktable. I do it this way due to the lack of flexibility in the standard apex:pageblocktable, and the blocktable seems to clash with the jQuery tablesorter when used naively. 


The Page:
<apex:page controller="UserInfoList" standardStylesheets="false" title="User Info" action="{!SwitchList}">
<apex:stylesheet value="{!URLFOR($Resource.UserList, '/NewTQC.css')}"/>
<apex:stylesheet value="{!URLFOR($Resource.UserList, '/style.css')}"/>
<script type="text/javascript" language="javascript" src="{!URLFOR($Resource.UserList, '/js/jquery1_4.js')}" ></script>
<!-- always include the tablesorter script after the jQuery -->
<script type="text/javascript" language="javascript" src="{!URLFOR($Resource.UserList, '/js/jquery.tablesorter.min.js')}" ></script>
<apex:form >
<div id="pageWrap">
<!--wrap the whole page in an outputpanel so that ajax rerenders, it triggers the jQuery.ready() function-->
<apex:outputPanel id="TicketListWrap" styleClass="Wrap">
      <script language="javascript" type="text/javascript">
            //controls the loading gif
            function Loading(b){
                  if(b){
                        $('.loadingIcon').removeClass('hideIt');
                  }else{
                        $('.loadingIcon').addClass('hideIt');
                  }
            }
            $(document).ready(function(){
                  //important to specify the sorting param otherwise it wont always choose the 'correct' one
                  $("table").tablesorter({
                    headers: {
                        0: {sorter: 'text'},
                        1: {sorter: 'text'},
                        2: {sorter: 'digit'},
                        3: {sorter: 'digit'},
                        4: {sorter: 'text'},
                        5: {sorter: 'text'},
                        6: {sorter: 'text'
                    }
                });
            });   
      </script>
      <div class="clear"></div>
      <br />
      <div id="newTicketHeader" class="floatL">Users in {!sDepartment}</div>
      <div class="floatR">
            <strong>Department:</strong>
            <apex:selectList id="department" size="1" value="{!sDepartment}" >  
                  <apex:selectOptions value="{!lstDepartmentOptions}" />
                  <!-- every time the select list is changed it refreshes the list of users -->
                  <apex:actionSupport event="onchange" onsubmit="Loading(true);" action="{!SwitchList}" rerender="TicketListWrap"id="actionsupportforKnownIssues" oncomplete="Loading(false);" />
            </apex:selectList>
      </div>
      <!-- the loading icon -->
      <div class="loadingIcon hideIt"><apex:image id="loadingImage" value="{!URLFOR($Resource.UserList, 'images/loader_24x26.gif')}"width="24" height="26"/></div>
      <div class="clear"></div>
      <div style="margin-left:5px; font-size:10px;">User count: {!iUserCount}</div>
      <table id="Usertable" class="list tablesorter" cellspacing="1">
      <thead class="rich-table-thead">
            <tr class="headerRow">
                  <th colspan="1" scope="col">Name</th>
                  <th colspan="1" scope="col">Phone</th>
                  <th colspan="1" scope="col" style="width:50px;">Ext</th>
                  <th colspan="1" scope="col">ICQ</th>
                  <th colspan="1" scope="col">Title</th>
                  <th colspan="1" scope="col">Location</th>
                  <th colspan="1" scope="col">Action</th>
            </tr>
      </thead>
      <tbody>
            <apex:repeat value="{!CurrentListofUsers}" var="u" id="UserListRepeater">
            <tr class="dataRow">
                  <td>{!u.name}</td>
                  <td>{!u.phone}</td>
                  <td>{!u.Extension}</td>
                  <td>{!u.ICQ__c}</td>
                  <td>{!u.Title}</td>
                  <td>{!u.Location__c}</td>
                  <td>
                        <div>
                              <!-- only current user can edit their own info -->
                              <apex:outputlink value="/{!u.id}/e?retURL=apex/UserInfoList" rendered="{!IF(u.id == $User.Id, true, false)}" >Edit Info</apex:outputlink>
                        </div>
                              <!-- only manager's/Team lead's/VP's can edit the users Queue info -->
                        <apex:outputpanel rendered="{!IF(CONTAINS($UserRole.Name, 'Manager') || CONTAINS($UserRole.Name, 'VP') || CONTAINS($UserRole.Name, 'Team Lead'), true, false)}">
                              <apex:outputlink value="/apex/QueueMemberEdit?UserId={!u.id}" >Edit Queues</apex:outputlink>
                        </apex:outputpanel>
                        
                  </td>
            </tr>
            </apex:repeat>
      </tbody></table>
      <hr />
</apex:outputPanel>
</div>
</apex:form>
</apex:page>



The classes that power it:
public with sharing class UserInfoList {

      public string sDepartment{get;set;}
      public string sCurrentUserDepartment
      {
            get{return UserInfoListHelper.FindDepartment(UserInfo.getUserId());}
            set;
      }
      public List<User> CurrentListofUsers
      {
            get{return UserInfoListHelper.UserList( UserInfoListHelper.FindDepartment(sCurrentUserDepartment, sDepartment));}
            set;
      }
      public integer iUserCount
      {
            get{return CurrentListofUsers.size();}
            set;
      }
      public List<selectOption> lstDepartmentOptions
      {
            get{return UserInfoListHelper.DepartmentKeys();}
            set{lstDepartmentOptions = value;}
      }
            
      public pageReference SwitchList()
      {
            if(!GlobalHelper.CheckForNotNull(sDepartment))
            {
                  sDepartment = sCurrentUserDepartment;
            }
            return null;
      }
}

public with sharing class UserInfoListHelper {
      /// <summary>
      /// OVERLOADED
    /// FINDS THE USERS DEPARTMENT BASED ON ID PASSED
    /// </summary>
    /// <param name="lstInValueToCheck">USER ID</param>
    /// <returns>USER DEPARTMENT</returns>
      public static string FindDepartment(string sInUserId)
      {
            if(GlobalHelper.CheckForNotNull(sInUserId))
            {
                  try
                  {
                        User u = [select id, Department from User where id=:sInUserId limit 1];
                        return u.Department;
                  }
                  catch(exception e)
                  {
                        system.debug('UserInfoListHelper - FindDepartment - error: '+e);
                  }     
            }
            return null;
      }
      /// <summary>
      /// OVERLOADED
    /// RETURNS USER DEPARTMENT IF SELECTED DEPARMENT IS NULL
    /// </summary>
    /// <param name="sInDepartmentSelection">USER DEPARMENT</param>
    /// <param name="sInUserDepartment">SELECTED DEPARTMENT</param>
    /// <returns>DEPARTMENT</returns>
      public static string FindDepartment(string sInUserDepartment, string sInDepartmentSelection)
      {
            if(GlobalHelper.CheckForNotNull(sInDepartmentSelection))
            {
                  return sInDepartmentSelection;
            }
            return sInUserDepartment;
      }
      /// <summary>
    /// ADDS DEPARTMENT KEY NAMES TO LIST OF SELECT OPTIONS
    /// </summary>
    /// <param name="lstInUser">USER ID</param>
    /// <returns>DEPARTMENT SELECT OPTION LIST</returns>
      public static List<selectOption> AddItemToList(List<User> lstInUser)
      {
            List<SelectOption> lstOptions = new List<SelectOption>();
            if(GlobalHelper.CheckForNotNull(lstInUser))
            {
                  for(User u : lstInUser)
                  {
                        if(!GlobalHelper.ContainsItem(u.Department, lstOptions))
                        {
                              lstOptions.add(new SelectOption(u.Department,u.Department, false));
                        }
                  }
                  return lstOptions;
            }
            return null;
      }
      /// <summary>
    /// FINDS ALL DEPARTMENTS AND ADDS THEM TO LIST OF SELECT OPTIONS
    /// </summary>
    /// <returns>DEPARTMENT SELECT OPTION LIST</returns>
      public static List<selectOption> DepartmentKeys()
      {
            User[] u = [Select Department From User where Department != null and IsActive = True limit 200];
            if(GlobalHelper.CheckForNotNull(u))
            {
                  return UserInfoListHelper.AddItemToList(u);
            }
            return null;
      }
      /// <summary>
    /// GETS LIST OF USERS BASED ON THE DEPARTMENT PASSED
    /// </summary>
    /// <param name="sInDepartment">DEPARTMENT</param>
    /// <returns>USER LIST</returns>
      public static List<User> UserList(string sInDepartment)
      {
            if(GlobalHelper.CheckForNotNull(sInDepartment))
            {
                  try
                  {
                        User[] u = [select Name, Phone, Extension, Title, ICQ__c, Location__c,Department from User where IsActive = True AND Department =:sInDepartment Order By Name ASC limit 200];
                        return u;
                  }
                  catch(exception e)
                  {
                        system.debug('UserInfoListHelper - UserList - error: '+e);
                  }
            }
            return null;
      }
}
Questions? 
Twitter: @SalesForceGirl  or Facebook