Home » Sage CRM Hub » jQuery Showcase
h

Table of Contents

$

Shortcut Your Sage CRM Development with jQuery

$

Submit a Form with jQuery

$

Create Sage CRM Form Blocking with jQuery

$

Modify Out-of-the-box Sage CRM Buttons with jQuery

$

Replace Search Select Advanced Field in Sage CRM Self-Service Portal

$

Replace Date Selector in Sage CRM Self-Service Portal

$

Setup Auto-complete in Sage CRM Text Fields

$

Use the jQuery Tabs Widget in Sage CRM

$

Mask Sage CRM Fields with jQuery

How to Shortcut Your Sage CRM Development with jQuery

Programming for multiple browsers is essential these days as more and more of us begin replacing Internet Explorer with Chrome, Safari and Firefox. It is no longer sufficient to code only for Internet Explorer – even with Sage CRM (SageCRM) development which has traditionally focused exclusively on Internet Explorer.

To ease this transition to cross-browser programming, we would like to make you aware of the excellent JavaScript framework called jQuery. we suggest you go check it out now at http://jquery.com/ as this guide is all about using jQuery inside of Sage CRM.

First, head over to http://jquery.com and download the latest version.

You can get either the minified or full version, it doesn’t matter either way, but it is suggested you use the full version for development and the minified version for production.

After you have downloaded jQuery, you want to place it in any directory under wwwRoot. However, it is easier to reference if it is in the root of wwwRoot which is where we will place it for the examples to follow.

To add the link to jQuery all you need to do is add the content to the eWare page like this:

eWare.AddContent('<script src="' + eWare.URL('jquery-1.6.2.min.js') + '" type="text/javascript">');

Our script is located in the root of wwwRoot so we don’t need to add any subdirectories. Based on where you put JQuery on your file system, you might need to change your relative path.

It is possible to use the CDN-hosted / hot linked version from ajax.googleapis.com but this adds a fragile dependency: the internet. It is recommended to actually download and host the minified version on your Sage CRM server to ensure the users won’t have any issues downloading and running jQuery.

Now that we have jQuery hosted on our Sage CRM server and we know how to link it into a custom ASP page we will cover a simple example of displaying the list of communications for a company in a modal dialog.

First, we need to add a method for the users to view our dialog.

We are going to add the link into the caption for comp_type field on the CompanyLongBox. We will do this from Jscript on the custom page. We also want to show a modal dialog so we will need to reference the jQuery UI plug-in which can be downloaded from http://jqueryui.com.

Below is our custom asp which will account for the two different blocks on the screen and display the communication list in a modal dialog.

<!-- #include file="accpaccrm.js" -->
<% // setup the standard CRM page 
var recMain = CRM.FindRecord("Company", "comp_companyid=25"); 
var container = CRM.GetBlock('container'); 

// get the company block 
var blkCompany = CRM.GetBlock("CompanyBoxLong"); 
blkCompany.Title = 'Company Summary'; 

// update the caption on the type field to contain the link to show the cases 
var comp_name = blkCompany.GetEntry("comp_type"); 
comp_name.Caption = 'Type: View Cases';

// add JQuery link
eWare.AddContent('<script src="' +eWare.URL('jquery-1.6.2.min.js') +'" type="text/javascript"></script>');

// add JQuery-UI link
eWare.AddContent('<script src="' +eWare.URL('jquery-ui-1.8.14.min.js') +'" type="text/javascript"></script>');

// add JQuery-UI CSS Link
CRM.AddContent(' ');

// Add the company block
container.AddBlock(blkCompany);

// Execute the company block into the CRM content
eWare.AddContent(container.Execute(recMain));

// get the communication list
var lstComms = CRM.GetBlock("CommunicationList");
lstComms.ArgObj = "cmli_comm_companyid=25";

// Add the content to the screen, because it is a list with buttons we need to
// update the references to EntryForm and document.forms[0]
// to account for this being the second form on the page
var lstHtml = lstComms.Execute();
lstHtml = lstHtml.replace(/EntryForm/g, 'EntryForm2')
lstHtml = lstHtml.replace(/document.forms[0]/g, 'document.forms[1]');

// add the list and dialog div to the screen
CRM.AddContent('<div id="dialog" style="display: none;">' + lstHtml + '</div>');

// write out the page
Response.Write(eWare.GetPage("Company"));

// check if the page has been submitted and the users wants to see the second page of the list
if (Defined(Request.Form('HIDDENSCROLLMODE'))){
Response.Write("<script>// <![CDATA[ $(document).ready(function () { ShowCases(); }) // ]]></script>");
}
%>

<script>
// <![CDATA[ function ShowCases() { $("#dialog").dialog( { modal: true, title: "Communications", width: 700 } ); } 
// ]]>
</script>

In the next section, we’ll cover submitting a form to an ASP page for processing.

h

Return to Top

How to Submit A Form In Sage CRM Using Ajax And jQuery

In the previous section, we covered how to include and use jQuery in Sage CRM (SageCRM). In this section, we will cover how to submit a form using jQuery and Ajax.

Why would you want to submit a form using Ajax and jQuery?

There are some tasks that technically require a new window or dialog to open but don’t actually require the user to navigate to a new page, enter some details, just to be redirected back to the initial page.

With Ajax & jQuery, you can open a dialog, gather information from the user and post that form to the server for processing while remaining on the same page.

1. First, you must create your custom ASP page. This page can contain any Sage CRM blocks or list. For this example we will keep it simple and  use the CompanyBoxLong block. Here is the code from our custom ASP page:

<!--#include file="accpaccrm.js"-->
<% eWare.AddContent('<script src="' + eWare.URL(" type="text/javascript"></script>');

var compId = Request.QueryString("comp_companyid");

if (String(compId).indexOf(',') >= 0)
compId = String(compId).split(',')[0];

var recMain = eWare.FindRecord("Company", "comp_companyid=" + compId);
var container = eWare.GetBlock("container");
var blkMain = eWare.GetBlock("CompanyBoxLong");

blkMain.Title = "Company Info";
container.AddBlock(blkMain);
eWare.AddContent(container.execute(recMain));
Response.Write(eWare.GetPage());
%>

2. Now that we have a basic custom ASP page, we need to add the code to submit the form using jQuery Ajax.

First, we need to remove the default buttons and add our own custom buttons that will submit the form using jQuery Ajax. Here is our code for adding the custom buttons:

// hide the default button because we are going to use JQuery and Ajax to submit the form
container.DisplayButton(Button_Default) = false;

if (eWare.Mode == Edit){

// add the Ajax submit button
container.AddButton(eWare.Button("Save", "save.gif", "javascript:ajaxsubmit(2);"));
} else {
container.AddButton(eWare.Button("Edit", "edit.gif", "javascript:ajaxsubmit(1);"));
}

3. With the default buttons removed, the only thing left to do is write the function to submit the form and display the results in the browser. Here is our function for submitting the form:

function ajaxsubmit(act) {
// set the em
if ($('input[name=em]').val() != act)
$('input[name=em]').val(act);
// submit the form, you must set the url to post to
$.post('<%=eWare.URL("submitform.asp") + "&amp;amp;comp_companyid=" + compId + "&amp;amp;em=" %>' + act,
$(document.EntryForm).serializeArray(),
function (data) { $(document.body).html(data) });
}

And there you have it, your Sage CRM forms are now being processed using jQuery and Ajax.

In the next section, we will revisit posting forms using jQuery and Ajax to add a form blocker, status messages and handling of HTTP errors.

h

Return to Top

How To Build Form Blocking in Sage CRM using jQuery

In the previous section, we discussed how to submit a form using jQuery and Ajax to Sage CRM (Sage CRM) for processing.

We already have an asp page that is being submitted using jQuery and Ajax which is very convenient for the users, but our work isn’t done yet. We still need to stop the user from clicking other buttons or changing the values in the form while the form is being processed on the server.

To accomplish this we are going to need 3 methods:

  1. A method for preventing the user from changing values of the form being submitted.
  2. A method to indicate to the user what action is being taken.
  3. A method for displaying server side errors to the user if something goes wrong with the Ajax post.

The first two we can combine into a Form Blocker.

A form blocker is a translucent div that will overlay the entire form and provide a status message to the user indicating which action is taking place.

For the third method, we are going to rely on the jQuery Ajax error handler and simply display any error messages in the status message on the form blocker.

We will accomplish this by building onto our existing example from the last section.

1. First create the HTML and CSS required for the form blocker. For this example we will use a semi-transparent white div with a span floating in the center to display our status messages. The code for this is as follows:

eWare.AddContent('<div id="FormBlocker">n');
eWare.AddContent('    <span id="FormBlocker-Message"></span> n');
eWare.AddContent('</div>n');
eWare.AddContent('<script src="jquery.js" type="text/javascript"></script>n');
eWare.AddContent('n');

2. Next step is to create the JavaScript to position and show the form blocker. Due to the limitations of CSS and cross-browser compatibility, we are going to position the form blocker when the page loads and the window is resized.

The code for this is as follows:

eWare.AddContent('<script type="text/javascript">// <![CDATA[ n'); 
eWare.AddContent('    // resize the blocker when the window is resized n'); 
eWare.AddContent('    $(window).resize(function () { n'); 
eWare.AddContent('        $("#FormBlocker").width($(document).width()); n'); 
eWare.AddContent('        $("#FormBlocker").height($(document).height()); n'); 
eWare.AddContent('    }); n'); 
eWare.AddContent('    $("#FormBlocker").width($(document).width()); n'); 
eWare.AddContent('    $("#FormBlocker").height($(document).height()); n'); 
eWare.AddContent('    function DisplayBlocker(msg) { n'); 
eWare.AddContent('        $("#FormBlocker-Message").html(msg); n'); 
eWare.AddContent('        $("#FormBlocker").show(); n'); 
eWare.AddContent('    }'); 
eWare.AddContent('    function HideBlocker() { n'); 
eWare.AddContent('        $("#FormBlocker").hide(); n'); 
eWare.AddContent('    } n'); 
eWare.AddContent(' // ]]></script>n');

This code defines two functions: DisplayBlocker and HideBlocker.

DisplayBlocker accepts one parameter named ‘msg’ which should contain the message to display to the user and the form blocker.

HideBlocker does as its name suggest and hides the form blocker. The rest of the code is for positioning the blocker when the page loads or the window is re-sized.

3. Now we need to modify our existing ajaxsubmit function to accept the status message and handle any errors that are raised on the server side. The updated function will accept a second parameter, msg, which contains the status message.

We will need to add a call to DisplayBlocker at the top of the function and we will also need to add the error handler to the call to $.post.

Here is the complete code for the new ajaxsubmit function:

function ajaxsubmit(act, msg) {
DisplayBlocker(msg);

// set the em
if ($('input[name=em]').val() != act)
$('input[name=em]').val(act);

// submit the form, you must set the url to post to
$.post('<%=eWare.URL("submitform.asp") + "&comp_companyid=" + compId + 
&em=" %>' + act,
$(document.EntryForm).serializeArray(),

function (data) { $(document.body).html(data); })
.error(function (err) { $("#FormBlocker-Message").html(err.responseText + '
<a>Continue') });

4. The only thing left to do now is change our existing calls to ajaxsubmit to provide the status message. The new calls to AddButton should look like this:

if (eWare.Mode == Edit){
container.AddButton(eWare.Button("Save", "save.gif", "javascript:ajaxsubmit(2, 'Saving Changes ...');"));
} else {
container.AddButton(eWare.Button("Edit", "edit.gif", "javascript:ajaxsubmit(1, 'Loading Edit Mode ...');"));
}

And there we have it, in 4 easy steps we have now updated our jQuery Ajax post to include support for server side errors and provide status messages to the user.

h

Return to Top

How To Modify Out Of The Box Sage CRM Buttons With JQuery

When you  need to modify the buttons on an out of the box Sage CRM block, you will quickly discover there is no method to do so, aside from the Default, Delete and Continue buttons.

Let’s take a look at the default Company Summary tab in Sage CRM.

Along with the default Change & Delete buttons you also see ‘Add this record to a group’, ‘Add to Contacts’/’Remove from Contacts’ and ‘Summary Report’.

You may not always want these buttons to show or you may want to change where the buttons take the users. To do this, you are going to have to rely on some custom JavaScript and JQuery.

First, you need to identify the button you want to modify.

In this example, it will be the ‘Summary Report’ button. You will want the button displayed but you would like it to navigate the user to the default Reports page.

Next, you need to look at the URL and see what the ACT is in the query string.

For the Summary Report button it is 523. You can determine this by hovering over the button in your browser and inspecting the tooltip that comes up with the URL for the link.

For the next step, you need to identify the action of the button or URL you want to use instead of the default action.

In this example, it is going to be action 1650 (Reports on the main menu) but this could be any URL or system action that you like.

Now you need to replace and identify the URL/Action you want the button to use instead of its default.

The only thing left to do is write the code to replace the button for you. This raises the question of where you put the code.

You could try to put it in the Custom Content for the CompanyBoxLong, but you will quickly find this is pure HTML and you can’t put any server side code here.

The next spot you might check would be the Create Script for one of the fields on the CompanyBoxLong screen, but this can result in some pretty ugly code. For the second option to work, you would need to append all your JavaScript to a string with the string delimiters escaped and the result is some hard to maintain code.

So what do you do? You use a combination of both.

You can use the Create Script to run your server side code and then write out the required client side values to JavaScript variables that you can use on the client side. Then, write the code that will use those JavaScript variables in the Custom Content for the CompanyBoxLong.

Here is what your code in the Create Script of the Company Name field on the CompanyBoxLong screen will look like:

var script = ‘<script>// <![CDATA[ var newUrl = “’ + eWare.URL(1650) + ‘”; // ]]></script>’;
Caption = “Company Name:” + script;

When the page loads, there will be a variable called newUrl that will contain the new destination for your Summary Report button.

Next, you need to write code that will change the href of the link as well as update the text so the user knows what to expect when they click this button. You are going to use JQuery to find the anchors and replace the href on them.

First, you need to link JQuery into this page.

You can check out the earlier section, Shortcut Your Sage CRM Cross-Browser Development with jQuery, for more information on that topic.

Once JQuery is linked you can’t write your code inside a script tag as you’d expect. This won’t work because the Custom Content is written out before the Caption of the fields in the block so your newUrl variable won’t exist in the DOM yet and there is no guarantee the button has been rendered to the DOM yet either.

With this in mind, you need to attach to the window.load function and run your script inside there.

Here is what the code in the Custom Content will look like. Keep in mind, my JQuery script is located in wwwRoot so you might need to change the src for the script depending on where JQuery is hosted in your environment.

<script src="”/crm-62/jquery.js”"></script>
<script>// <![CDATA[$(window).load(function(){ 
// attach to the window.load function
$(‘a[href*=”Act=1341”]’).each(function() {  

// find all the anchors with the action 523
if ($(this).html().indexOf(“<”) < 0) {

// check if there is only text to update the caption 
$(this).html(‘Reports’); 

// update the text of the button to indicate what the button does 
} 
$(this).attr(‘href’, newUrl); 

// set the new URL for the anchor 
} 
}); 
// ]]>
</script>

There you have it. Now the Report Summary button on the Company Summary screen will redirect the user to the default reports section of Sage CRM.

h

Return to Top

How To Replace Search Select Advanced In A Sage CRM Self-Service Portal

One of the common problems Sage CRM (SageCRM) developers face when building a new Self-Service portal is how to handle Search Select Advance fields.

By default, Sage CRM will allow a Search Select Advanced field to be rendered to the screen in a Self-Service portal but it will not be functional and will produce errors for your users. In this article, we’ll discuss how to get around this.

We are going to set the SSA field to be “read-only” and append a select list to the caption of the field. We will also put in code to set the selected value if one has already been selected as well as write out some JavaScript to hide the “read-only” span when we are in edit mode.

We don’t need to do anything special to get Sage CRM to save our changes because we will still be naming the select list so Sage CRM will kick in and save our changes for us when the form is submitted.

Here is the code except from our sample portal page build on the standard sample Sage CRM Self-Service portal. We have created a sample block (SampleBlock) on the company entity that contains the company name, the created date of the company and new Search Select Advanced field (comp_ssasample) that we created specifically for this example, which is a simple Opportunity look up.

// set the view mode to edit, just for our example
if (eWare.Mode < 1)
eWare.Mode = 1;
// get our sample block
var blkMain = eWare.GetBlock("SampleCompany");

// find a company record
var recMain = eWare.FindRecord("Company", "comp_companyid = 1374");

/* replace the Search Select Advanced with a classic select list */
// only replace the field in Edit mode
if (eWare.Mode == 1) {

// flag indicating if None should be set as selected
foundSelected = false;

// get a reference to the field
var fldSample = blkMain.GetEntry('comp_ssasample');

// set the field as required (optional)
fldSample.Required = true;

// start building the HTML to replace the SSA with a select list
var ssaHtml = '<select id="comp_ssasample" class="EDIT" name="comp_ssasample" size="1">';
</select>

// find the valid records for the select list, you can change the filter as needed
var recVals = eWare.FindRecord("Opportunity", "Oppo_PrimaryCompanyId = 1374");

// order the avaliable options, you can change as needed
recVals.OrderBy = "Oppo_Description";

// loop through the avaliable options and add them to the select
while (!recVals.eof) {
// check if this is the currently selected option
if (recMain.comp_ssasample == recVals.oppo_opportunityid) {

// add the option to the select list
ssaHtml += '' + recVals.oppo_description + '';
foundSelected = true;
} else {
// add the option to the select list
ssaHtml += '' + recVals.oppo_description + '';
}
// move to the next record
recVals.NextRecord();
}

// add the None option to the end of the list
ssaHtml += '--None--';

// close the select tag
ssaHtml += '';

// set the ssa to be read only, this prevents the SSA HTML from being written to the screen
fldSample.ReadOnly = true;

// add the javascript to hide the value div
ssaHtml += "<script>// 
<![CDATA[ setTimeout('document.getElementById("_Datacomp_ssasample").style.display = "none";', 100) 
// ]]></script>";

// set the caption of the ssa to be the CRM caption plus our custom html
fldSample.Caption = eWare.GetTrans("ColNames", "comp_ssasample") + ':
' + ssaHtml;
}

// execute the block and write it to the screen
Response.Write(blkMain.Execute(recMain));

To ensure this sample works correctlyupdate all references to the field names. For example, on line 58 you will need to update the field you are searching for to the actual field name that Sage CRM renders to the screen for your Search Select Advanced.

In the next section, we’ll cover replacing the default date selector in a Sage CRM Self-Service Portal with the jQuery UI DatePicker.

h

Return to Top

How To Replace The Sage CRM Portal Default Date Selector With jQuery

In the last section, we discussed how you can replace a Search Select Advanced field with a Drop-Down on a Sage CRM Self-Service portal. In this section, we will cover replacing the default date selector with the jQuery UI date picker control.

This is not specific to a Self-Service portal; you could easily replace date selection fields in Sage CRM with this technique which we will touch on briefly.

First, you need to link jQuery and jQuery UI into your page which we covered in the previous section, Shortcut Your SageCRM Cross-Browser Development with jQuery.

In addition to jQuery, you also need to link to jQuery UI. You can download jQuery UI from http://jqueryui.com/download.

We recommend getting the Redmond theme as it closely matches the default Sage CRM theme.

Because this is a Self-Service Portal, you should link jQuery and jQuery UI in your header. Include the file so you can access both jQuery and jQuery UI from all pages in your portal. This will make your life easier down the road when you decide to use jQuery in another page on your portal.

Now that you have jQuery and jQuery UI linked into your page you need to wire in the Date Picker to the desired fields on your screen.

In this example you will be setting up the pers_birthday field to use the jQuery UI Date Picker. The most basic implementation of this will look like the following:

<script>// <![CDATA[ 
// use jQuery ready function $(document).ready(function() { 
// setup the date picker $(‘#pers_birthdate’).datepicker(); }); 
// ]]>
</script>

This is the most basic implementation of the Date Picker and you could just leave it at that. Note, the Date Picker has a myriad of options that allow you to customize the control.

For example, you might want to display the Month and Year as drop-downs to allow for faster navigation over multiple months and years. To accomplish this you can pass in an array of parameters to the datepicker call which will look like this:

<script>// <![CDATA[ 
// use jQuery ready function $(document).ready(function() { 
// setup the date picker $(‘#pers_birthdate’).datepicker( { changeMonth: true, changeYear: true } ); }); 
// ]]>
</script>

There are many possible options for the DatePicker. We suggest you head over to http://www.jqueryui.com/demos/datepicker to take a look at all the possible options and play with them to familiarize yourself with the possibilities of the jQuery UI DatePicker.

The codes for implementing this in Sage CRM are very similar but you to want to ensure the dates being entered are adhering to the users preferred date format.

This is accomplished through the dateFormat option. The complete code to set the dateFormat to that of the user is as follows:

// Look up the current users id
var userId = eWare.GetContextInfo('user', 'user_userid');

// Find the current users date format
var myRecord = eWare.FindRecord('usersettings', 
"uset_key like 'NSet_userdateformat%' and uset_userid=" + myRecordId);

// wire the DatePicker
eWare.AddContent("<script>
// <![CDATA[ $(document).ready(function() { “ +  
// use jQuery ready function “              $('#pers_ birthdate').datepicker({ “ + 
// setup the date picker “                       dateFormat: '" + myRecord.uset_value.replace('yyyy', 'yy')  + “’”+  
// set the date format "               }); ” + “}); 
// ]]>
</script>");
h

Return to Top

How to Setup AutoComplete Inside Sage CRM Text Fields with jQuery

Let’s face it: auto-complete is cool.

Users like it and it makes data entry much easier and less error prone if you are presented with proper spelling and suggestions.

jQuery UI has this functionality built right in and with just a little custom coding, you can turn any textbox into an auto-complete in minutes. There are a few simple steps to setting this up you will need to follow.

The first thing you to need to do is link jQuery & jQuery UI to your page, which I have covered before in the section called Shortcut Your Sage CRM Cross-Browser Development with jQuery.

We have mentioned this before but it is worth mentioning again; when you are downloading jQuery UI, the closest match to the Sage CRM theme is Redmond. However, you can download any theme you like.

In this example we are using the default CompanySearchBox and setup the Company Name field to be an auto-complete.

There isn’t anything special you need to do when setting up your page, all the coding will be done in JavaScript. However, there will be some coding needs to be done in the asp page that is going to serve the results for the auto-complete.

Here is the code for our page which displays the CompanySearchBox without the list showing the matching companies.

<!--#include file="accpaccrm.js"-->
<% eWare.AddContent('<script src="' + eWare.URL(" type="text/javascript" language="javascript"></script>');
eWare.AddContent('<script src="' + eWare.URL(" type="text/javascript" language="javascript"></script>');
eWare.AddContent(' ');

var cont = eWare.GetBlock("Container");
cont.DisplayButton(Button_Delete) = false;
cont.DisplayButton(Button_Continue) = false;
cont.DisplayButton(Button_Default) = false;

var blkComp = eWare.GetBlock("CompanySearchBox");
blkComp.Title = "Find Company"
cont.AddBlock(blkComp);

eWare.AddContent(cont.Execute());
Response.Write(eWare.GetPage("find"));
%>

As you can see, there isn’t anything special about this page so far. The magic happens in the JavaScript that you append to the page.

Because you already have jQuery and jQuery UI linked into your page, all you need to do is call the autocomplete function and pass in the desired settings. A complete list of the settings can be found here: http://jqueryui.com/demos/autocomplete/.

In this example, we are only setting the source but you can specify any combination of parameters you like. In our script, we are attaching to the ready function of the document and setting up the auto-complete to ensure the page has rendered the controls to the screen before we try accessing them.

<script type="text/javascript" language="javascript">// <![CDATA[
$(document).ready(function () {
$('#comp_name').autocomplete({
source: '<%=eWare.URL("CompAutoComlete.asp") %>'
});
});
// ]]></script>

That is all the code you need to setup the auto-complete on the page.

Personally, we don’t like the size of the font in the suggestions, so we add this style to override the default jQuery UI style for the auto-complete suggestions.

.ui-menu-item a { font-size: 8pt; }

Now that you have your page setup for the auto-complete, the only thing left to do is setup your asp page to deliver the results in JSON. When you set the source to a URL for the auto-compete it appends the term to the query string, so your asp page for delivering the JSON results should look similar to this.

// clear the response of all text before writing out the JSON
Response.Clear();

// Start the JSON array
Reponse.Write("[");

// get the search term from the url
var strTerm = Request.QueryString("term");

// Ensure there is a search term
if (strTerm)
{
// query the company table
var recComp = eWare.FindRecord("Company", "comp_name like'" + strTerm + "%'");

// loop through all company records
while (!recComp.eof)
{
// write out the suggestion
Response.Write('"' + recComp.comp_name + '"');

// move to the next record
recComp.NextRecord();

// check if we are at the end of the record set, if not append the comma
if (!recComp.eof)
Response.Write(',n');
}
}
// Close the JSON array
Reponse.Write("]");

There you have it!

You now have an auto-complete textbox in Sage CRM. You can use this same type of code for any textbox in CRM.

jQuery UI gives you a bunch of options for the auto-complete so don’t forget to check out the documentation to unleash the full potential of the jQuery UI auto-complete.

h

Return to Top

How To Use The jQuery UI Tabs Widget In Sage CRM

A useful but widely unused widget in jQueryUI is the Tabs widget.

This widget works extremely well when you want to display a lot of information to a user without cluttering up the screen with a bunch of divs that take away from the main focus of the page.

One of the possible work-arounds for this is to use dialogs but even those can be intrusive and cumbersome and still interfere with the page itself requiring the user to take an action and close a dialog before they can start using the page.

Let’s say that one of your requirements is to display all the notes for a company in Sage CRM on a custom page whenever the page is loaded.

To accomplish this, you could write the notes out to the top of the page but this requires the user to scroll down get the contents of the page.

Another option is to use a dialog but once again this requires the user to interact with the page before they can actually see the information they want.

What if all the users don’t need to see the information all the time but would like to have it readily available when they do need?

Here is where the jQueryUI Tabs widget comes into play. This widget allows you to display all the notes at the top of the page in such a way that it doesn’t interfere with the pages functionality itself.

The Tabs widget has a collapsible property that fits the bill perfectly for this scenario. It renders all the HTML to the page but collapses all the tabs until the user selects one. Using this widget, you can have all the notes readily available on the screen while not interfering with the page itself.

In this example, we will show you how to get all the notes and display them in a collapsible Tabs widget that is displayed at the top of the custom page. The Tabs widget has server options and methods that are described in detail in the jQueryUI documentation found here.

First you need to do is declare some variables, set the context and setup your blocks. In this example, we are only displaying the CompanyBoxLong block preceded by all the notes in the Tabs widget.

// get the current company id
var compId = CRM.GetContextInfo("Company", "Comp_CompanyId");

// variable used to construct the HTML and JavaScript for displaying the Tabs widget
var notesHtml = '';
var noteHeaders = '';
var noteContent = '';

// set CRM context to company
CRM.SetContext("Company", compId);

// get the a recordset for the current company
var recComp = CRM.FindRecord("Company", "comp_companyid = " + compId);

// build the detail block
var blk = CRM.getBlock("CompanyBoxLong");
blk.Title = "Company Details";

After you setup your blocks, you will need to find all of the relative notes in the system and build some custom HTML to render to the page. Here is an example of getting all the notes for the current company, looping through all them and building the custom HTML needed.

// Create the tabs
var recNotes = CRM.FindRecord("Notes", "Note_ForeignTableId = 5 AND Note_ForeignId = " + compId);

// check to make sure there are notes
if (!recNotes.eof) {
notesHtml += '<div id="tabs">';

var count = 1;// loop through all the notes
while (!recNotes.eof) {
noteHeaders += '<ul>
 	<li><a href="#tabs-' + count + '">Note #' + count + '</a></li>
</ul>';
noteContent += '<div id="tabs-' + count + '">' + recNotes("note_note") + '</div>';

// move to the next record
recNotes.NextRecord();
// increment the count
count++;
}

// append all the notes and headers to the content
notesHtml += '<ul>' + noteHeaders + '</ul>';
notesHtml += noteContent;
notesHtml += '</div>';
}

Now that you have all the custom HTML built, the only thing left to do is to add jQuery and jQueryUI to your page and add the script to setup the Tabs.

// add jQuery and jQueryUI
CRM.AddContent("<script src="..\jquery.js"></script>");
CRM.AddContent("<script src="..\jquery-ui.js"></script>");
CRM.AddContent("");

// add the notes to the page
CRM.AddContent(notesHtml);
// add the call to tabs, here I am setting the selected tab to -1 to initially 
// have all the tabs collapsed and indicating that the tabs are collapsible
CRM.AddContent("<script>$(function() { $('#tabs').tabs( { selected: -1, collapsible: true } ); } );</script>");

// add the detail block to a container
var cont = CRM.GetBlock("Container");
cont.AddBlock(blk);
CRM.AddContent(cont.Execute(recComp));

// write out the page
Response.Write(CRM.GetPage("Company"));

Simple as that! You now have a custom page that displays the basic company info in Sage CRM along with all the notes in a jQueryUI Tabs widget that is collapsed by default.

h

Return to Top

How to Mask Sage CRM Fields with jQuery

Sometimes you need to format the data inside text boxes in Sage CRM to make data entry simpler for users and entries more consistent in the database.

Below is an example of masking a field in Sage CRM performed using the downloadable Jquery plugin available at digitalbush.com.

The plugin allows a user to more easily enter fixed width input where you would like them to enter the data in a certain format, such as dates, phone numbers, etc.

In this example a custom Date field is masked to input mm/dd/yyyy.

Steps:

  1. Create a text field called comp_testdate
  2. Add the field to CompanyBoxLong
  3. Copy paste the script to the right in Custom Content area and save.
<script src="/crm/jquery/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" 
src="http://digitalbush.com/wp-content/uploads/2013/01/jquery.maskedinput-1.3.1.min_.js">
</script>
<script>
if(window.addEventListener)
{
window.addEventListener("load", doload, false);
}
else if(window.attachEvent)
{
window.attachEvent("onload",doload);
}

function doload()
{
if(document.getElementById("comp_name"))
{
jQuery(function($){   $("#comp_testdate").mask('99/99/9999');});
}
}
</script>

Here are the results in the CompanyBoxLong  ‘Date’ field.

There are many other masking features available within this plug-in, including phone number and social security masks.

Please refer to http://digitalbush.com/projects/masked-input-plugin for full details.

h

Return to Top