Pages

Showing posts sorted by relevance for query logic hook. Sort by date Show all posts
Showing posts sorted by relevance for query logic hook. Sort by date Show all posts

Thursday, April 14, 2011

Logic Hooks: OnDemand Installations

Source: photosteve101/Flickr
Say that you developed a cool logic hook and are ready to put it into use on your production instance of SugarCRM. However, you are faced with the challenge of the production instance being hosted on the SugarCRM OnDemand platform. 

For those of you that are new to the world of logic hooks, the OnDemand environment presents a unique challenge in that in order for one to make use of logic hooks in general, one has place the logic hook files in specific sub-folders within the folder containing your SugarCRM installation. You would not have access to said folders for OnDemand installations. Thus, our challenge.

So how do we solve this problem?

Fortunately, we can leverage one of built-in features of SugarCRM to bypass the issue. Using the Module Loader tool, we can install or uninstall the logic hook at will.

But to do this, we must first create a Module Install package. Let us take a look at how we would prepare it for the purposes of installing the proper casing logic hook described in a previous post of mine.

From this point forward, it is assumed that you have already created the files corresponding with that logic hook and we will focus exclusively on the process required to install it via the Module Loader and in turn, apply them to an OnDemand instance.

Friday, March 30, 2012

Logic Hooks: Lead History Transfer

Have you noticed what happens to history information associated with a lead when one converts that lead into a contact within SugarCRM? 

If not, give it a try. Enter a lead record named John Doe, add a Note under its History section. Next, convert the lead into a contact. Now, take a look at the History section on the new contact record for John Doe that was created via the conversion process and compare it to the History section on the lead record. You will notice that the Note entry is nowhere to be found on the contact record and instead, remains associated with the lead record.

This separation allows us to see which interactions were completed when the individual was a lead and which were completed after it was converted into a contact. In turn, it helps us identify processes and techniques that led us to converting it. 

All future activity relating to that individual would be recorded against the contact record, not the lead. However, many users find that the distinction between lead and contact history causes too much confusion.

One problem that is created by this separation of data is that looking at the History section of a contact does not give us a full picture of everything that has occurred over time, as it relates to the individual. One must toggle between the contact and lead record in order to gather that insight. 

How can we address this problem?

One school of thought would bring us to the conclusion that one should not use the Leads module at all and simply enter everyone as a contact. This would solve the History problem, but creates others, such as the inability to track lead conversion rates. 

A second approach would be to carry over the History data from the lead over to the contact record during the conversion. Doing so would solve the problem as all the History would appear on the contact record, but a facility for this does not exist in SugarCRM. Fortunately, it can be easily accomplished via a logic hook.

Let us take a look at the logic hook we would use.

Tuesday, October 11, 2011

SugarCRM Logic Hooks: Unintended Loops


There is something intriguing about working with logic hooks. Through their use, one can accomplish quite a bit given that the only real limitation is our ability to write PHP code. 

For example, we can use a logic hook to modify a value on a record that is being saved. We can also use it to connect to a web service and process data whenever a record is retrieved in SugarCRM. In addition, we can leverage the SugarCRM framework and add records in other modules, such as automatically adding a call upon the creation of a new Lead record.

Our possibilities are virtually endless, but at the same time, this power can sometimes present some odd problems that are difficult to troubleshoot or resolve. 

One such matter relates to the duplication of data, usually the result of what appears to be an unintended loop within the code executed by the logic hook. On the surface, this sounds simple enough to troubleshoot, but looks can be deceiving.

Lets take a look a code snippet which we will assume is being executed by our logic hook:

class LogicHookTest {
        function addContact(&$bean, $event, $arguments)
        {
             //Grab contact ID value stored in custom field on current record
             $contact_id = $bean->contact_id_c;         

             require_once('modules/Contacts/Contact.php');
             $contact = new Contact();

             //Retrieve Contact record with matching ID value
             $contact->retrieve($contact_id); 
             //Set value on Contact's custom field 
             $contact->custom_field_c = 'New Value';  
             $contact->save();
        }
}

To elaborate, the code is grabbing a value from the contact_id_c field of the record currently being accessed in SugarCRM and assigning it to the $contact_id variable. For the purposes of the example we will assume the record being accessed is in a custom module.

Next, the code instantiates a Contact object and uses that same $contact_id value to retrieve the record with the matching ID value from the Contacts module. Lastly, a custom field named custom_field_c is modified on that Contact record and then saved. 

In summary, the logic hook retrieves a record from the Contacts module and modifies a field on that record, without us actually needing to be in the Contacts module.

Assuming the referenced custom fields existed, the above code would work. However, this may not always yield the desired results, which leads us into the problem at the heart of this post.

Friday, July 20, 2012

Logic Hooks: Odds and Ends

On occasion I run into a logic hook use case that ultimately exposes a limitation of the framework, or generates peculiar challenges during its implementation. Lets review some of these items in hopes they may help you avoid frustration and save you some time.

before_save vs. after_save

It is not uncommon to stumble upon references to either of these terms as one reads about logic hooks. They refer to the timing of the execution of your logic hook code. A before_save hook triggers your code before the record a SugarCRM user is interacting with is physically written to the database, and an after_save hook triggers it after the data has been written to the database. 

While those conditions are easy to understand, the same cannot be said for the technical subtleties each carry. It is important to understand these subtleties because some may require one to change from using before_save instead of after_save or vice-versa. More importantly, being aware of these subtleties helps us reduce the amount of time that would otherwise be wasted on troubleshooting the problems the subtleties bring about.

Thursday, February 18, 2010

SugarCRM Logic Hook: Proper Casing Fields

Sorry for my absence. Been meaning to write, but been caught up with other cool things.  Anyway, wanted to post a quick and easy one that many might find helpful. 

One of the biggest challenges with a database application such as SugarCRM is ensuring that data is entered in a uniform manner by its various users. The use of drop down and multi-select fields helps address this challenge quite well, but said field types cannot be used in all places. 

A good example of where they cannot be used is the Last Name field on a Contact entry. However, at the same time, it would be nice to be able to enforce some uniformity in the field's values, for example, ensure that names are being entered in proper case.  

This need provides us with a great opportunity to once again highlight the power of logic hooks. In our example, the uniformity we want to introduce is the proper casing of the text entered into the Last Name field. Thus, values that are typed in as "doe" are automatically corrected and saved to the database as "Doe."

A logic hook is the perfect solution as it is transparent to the user and easily extended to support other fields.

Lets take a look at how we can accomplish the above...

Wednesday, July 27, 2011

Logic Hooks: Truncating Displayed Values

Sometimes minor customizations to SugarCRM go a long way towards addressing important usability aspects. Something that has come up a couple of times in recent interactions with users is the need to truncate data displayed on a subpanel.


At first glance, the reasons why someone would want to do this are not always readily apparent. However, consider the scenario where one uses a text area field (e.g. description) on a module and one wishes to display that field on the subpanel.


The process of including the field on the subpanel is easily accomplished via Studio, but over time, an issue not initially apparent usually starts to surface.


Because a text area field can hold large amounts of text, it is possible for a user to populate the field with a number of pages worth of data. That on its own is not a problem. However, displaying that on a ListView, of which a subpanel is a good example, usually causes undesired display problems, as demonstrated by the image that follows (click to enlarge):




The issue at hand is that the Description field with the longer text value makes the subpanel appear a bit odd, to the point that the additional columns that are part of the view appear to the extreme right of the screen.


So how do we solve this? Easily, via a logic hook. Let us take a look at how we do so.

Saturday, March 17, 2012

SugarCRM Cookbook: Adding Related Records

Lets jump right into this one and begin by looking at a code snippet:

$rel_name = 'contacts';
$record_id = 'some_id_value';


$bean->load_relationship($rel_name);
$bean->$rel_name->add($record_id);

So what does it do?

Assuming we execute the above code within the scope of a before_save logic hook for Opportunities, the above code would add a linked contact to the opportunity being saved. 

While that example may have limited applications, the snippet of code does not. It can be reused within any custom PHP code you are writing for SugarCRM to link records together, all via the SugarCRM framework.

The advantage of this approach is that it is applicable to any module. In addition, and perhaps more importantly, it is upgrade-safe and eliminates the need for us to know about relationship tables, linking fields or any of the finer details that SugarCRM relies upon to establish relationships between records.

In order to see the power of this little snippet, we need to dissect it line-by-line and expand scope of our example.

Monday, June 1, 2009

Simple SugarCRM Logic Hook Example

Logic hooks are one of the most powerful features of SugarCRM, however, their power also introduces complexities. If you are not familiar with this feature, more detailed information on the topic can be found on the SugarCRM Developer site.
In a nutshell, their power lies in the fact that they allow a programmer to extend SugarCRM functionality with custom code which in turn can be designed do just about anything.
Some capabilities include:
  • Modifying values on a record before it is saved to the database
  • Updating other databases based on actions performed within SugarCRM
  • Conditional sending of e-mail messages
A common task that users will want to accomplish with a logic hook is to interact with the database at some level when an action is performed within SugarCRM.
Consider the following scenario:
Workflow requirements dictate that the Assigned To value of a Case always match the Assigned To value specified on the Account record to which the Case is linked.
Thus, we must do two things:

1. Determine the assigned_user_id value of the parent Account record
and
2. Ensure that the assigned_user_id value of the Case record matches that of the parent Account

Both steps are easily accomplished via a logic hook and demonstrate the feature's ability to query the database as well as modify the current record's values.
We will use the before_save hook in this example, causing it to trigger whenever a Case record is committed to the database.

First we'll need to create a file called logic_hooks.php and put the following PHP code in it:
$hook_version = 1;
$hook_array = Array();
$hook_array['before_save'][] = Array(1, 'assignUser', 'custom/modules/Cases/autoUserAssignment.php', 'UserAssignment', 'updateCase');


Make sure to save the file to the [sugar]/custom/modules/Cases directory.


The logic_hooks.php file described above provides the parameters necessary for SugarCRM to know not only when the custom code should execute, but also where the code can be found.
Notice the reference to the file autoUserAssignment.php. That is the file that SugarCRM will examine for the custom code that needs to be executed when the appropriate conditions are met. 


Create a PHP file by that name and store it in the [sugar]/custom/modules/Cases directory.
Add the following to said file:


<?php


class UserAssignment {
      function updateCase(&$bean, $event, $arguments) 

      {
           //Query ACCOUNTS table for assigned_user_id value of parent Account
           $case_id = $bean->id;
           $acct_id = $bean->account_id;
$query = "SELECT accts.assigned_user_id FROM accounts accts ";
$query .= "WHERE accts.id = '$acct_id' LIMIT 1";
$results = $bean->db->query($query, true);
$row = $bean->db->fetchByAssoc($results);
$user_id = $row['assigned_user_id'];


           //Change assigned_user_id value on Case
           $bean->assigned_user_id = $user_id;
}
}
?>



That should do it! 


From now on, whenever a user clicks Save on a Case, SugarCRM will automatically set the Assigned To value to match that of the related Account.



Tuesday, November 24, 2009

SugarCRM Customization: Custom Workflow E-mails

E-mail has become a popular tool for communication and for a number of purposes.

Within the scope of SugarCRM, the topic usually comes up in relation to the automation of some aspect of a business process, such as alerting a user when a record within the database has been assigned to them.  SugarCRM includes such a feature out of the box, but what if one wanted a bit more flexibility?

Suppose we encounter the following scenario:

Our deployment uses the Leads module to track and qualify potential customers.  Leads enter the system via two different ways: manual entry and web-to-lead.

Entries are required to have an e-mail address or they are not considered valid as our internal process use it for communications and other purposes.  Whenever a new lead is entered, it is automatically assigned to a specific user, who in turn receives an e-mail alerting them of the new record.  However, we want to expand this functionality to also automatically send a generic "Welcome/Thank You For Your Interest" message to the  Lead itself.

How do we go about accomplishing the above?

Monday, July 15, 2019

SugarCRM Customization: Sending Emails - New and Improved

It seems like an eternity since I posted examples on programmatically sending emails through Sugar.

As some of you might have already correctly surmised, a number of changes have occurred to Sugar since those blog entries were written. One of the major additions to Sugar since then has been SugarBPM, which itself includes an email template engine.

Let us revisit the original problem of programmatically sending emails and examine how we can accomplish the same via SugarBPM. This time around, we will assume our intention is to send an email about an Account record.

We will first need to create the email template containing the content to be sent. Said template can be static or, if desired, may also include references to specific fields from the target module, to be parsed at send time. For our example, we may wish to make an email template that reads as follows:

ACME Corporation
123 Main Street
Some City, CA 90000

...but rather than typing specific values, we would instead insert references to the corresponding fields that contain the values we want from the Accounts module -- our Target Module. That would make the template much more flexible.

Note that the process of creating such a template for SugarBPM differs than that for a standard email template. To create an email template for SugarBPM, select Process Email Templates from the Sugar navigation bar and then click Create. Further information pertaining to this process can be found here:

https://support.sugarcrm.com/Documentation/Sugar_Versions/9.0/Ent/Administration_Guide/SugarBPM/Process_Email_Templates/index.html

Sunday, November 7, 2010

My Two Rules of Logic Hooks

As you may have ascertained from prior posts, something about the logic hooks feature really draws my attention.  I think a lot of it has to do with the fact that the main limit on its capabilities is one's creativity and that power is quite appealing.


Regardless of the reason or the intended purpose of the logic hook, there are a couple of rules that I've learned one should always adhere to in order to avoid problems.


Curious about what they are?  Keep reading.


Tuesday, February 24, 2015

SugarCRM Customization: Custom Blur Event

One of the ideas that I regularly try to convey when talking about the customization capabilities of the Sugar 7 framework relates to leveraging JavaScript wherever possible. This is especially true for projects where our objective is to upgrade heavily customized versions of Sugar up to version 7.x.

In the pre-7.x world, some customizations that can now be implemented natively via the Sugar 7.x framework used to require the use of SugarLogic functionality or inclusion of third party JavaScript libraries. The case of SugarLogic can be particularly problematic if one utilizes a large number of such customizations, as it might imply the execution of additional server side code. The greater the number of these type of customizations and the greater the potential to introduce performance problems. This is also true for logic hooks. For example, a hook that automatically converts the last name field to upper case upon a record being saved.

If we step back and analyze these customizations, we would likely find that some could be implemented via JavaScript. Doing so would in turn offload some of the server load to the client -- likely helping correct performance problems. The latter example of the logic hook upper casing the last name field is a good case in point. 

Suppose we wanted to convert such a customization to implement it through JavaScript instead of using a logic hook. How would we do that? 

The general idea would be to use a standard onBlur() event, tied to the last_name field of a module such as Contacts and then automatically updating the content of that same field when focus is lost.

As it turns out, the Sugar 7.x framework makes this a very easy task. The code for making such a customization is found below:



I hope you find it helpful!

Thursday, January 6, 2011

January is Logic Hooks Month

According to the stats for this blog, logic hooks are a popular subject amongst visitors.  As such, I figure the topic would be a great way to kick off an idea of mine that I have been tossing around for a bit.

Going forward, I will select a topic of interest, or theme, on a monthly basis.  The objective: to discuss the topic at hand in further depth throughout the month, with other posts sprinkled in between for variety.

However, this idea can only work with your assistance.  

To help, simply reply to the post announcing the month's topic (e.g. this post) and suggest a facet of said topic for discussion.  For example, perhaps you have been wanting to build a logic hook to execute an SQL query, but are unsure about how to get started.  Simply share your scenario within the comments area.  

In turn, I will select one of the suggestions on a weekly basis and provide a detailed post discussing the process involved in addressing the issue.

Now, while all suggestions are welcome, there are some rules to consider:

1. For obvious reasons, I cannot create a detailed post for every suggestion, but if time permits, I will tackle more than 1 per week.  

2. Please be as clear as possible in your description of your scenario.  If the description is not clear, I will not consider it.

3. Do not post sample code or the like.  A clear description of the goal will suffice.  

4. Some scenarios may require very specific configurations, such as custom modules, etc.  I will not be able to create mirror environments for all cases, but my response will include sufficient guidance to fulfill the vast majority (if not all) of your goal.

5. Suggestions on themes for upcoming months are welcome and highly encouraged.

Thanks and now lets have the suggestions relating to logic hooks (in the comments section)!  

Friday, September 9, 2011

Commentary: SugarCRM OnDemand

The idea of Software-as-a-Service (SaaS) is a rather nifty one.

As a customer, you pay a set fee on a predefined schedule and in turn, software is quickly made available for your use -- usually within minutes. It eliminates the need and hassle of installing software, maintaining servers, setting up backups, etc., plus the vendor normally provides technical support services as part of the subscription. The concept is not new, and is quite popular with a number of CRM vendors, including SugarCRM.

Sugar OnDemand is the common name associated with the SugarCRM SaaS offering. While it delivers on the idea of fast deployment, my preference is to not use it except for the most basic of deployments. It is not inherently bad, but enhancements to the platform are necessary make it a much more acceptable solution, specially considering the sales strategy that surrounds it.

As a solutions implementer, some of the shortcomings are frustrating, not only because they complicate customization of the system, but more importantly, they prolong the work involved which usually translates to additional expenditures in professional services.

What are some of the things that would make it a more palatable solution from my perspective?

Thursday, June 9, 2011

SugarCRM Customization: Workflow Emails with Templates

Some time ago I posted an article describing the manner in which one can send custom email messages via a logic hook. Since then, several folks have asked if it is possible to leverage the email template system built into SugarCRM for generating the actual message. 


It is certainly possible and that is exactly what we will cover in this post.


To save ourselves some time, we will simply modify the script from the previous post and change the relevant portions so as to cause it to use an e-mail template instead of the file based template it previously used. But before that, we need to create the e-mail template.


Create your e-mail template as you would any other, following these steps:


1. Select Emails > Create Email Template within SugarCRM 
2. Compose your message and click Save when done 


Next, we need the ID of the email template you just created. This will allow us to leverage it within the script, giving us our desired result. 


To retrieve the ID:


1. Select Emails > View Email Templates  
2. Click on the email template you just created
3. Copy the content from the address field in your web browser to your clipboard
4. Paste the content to Notepad or other format where it can be easily inspected


Once pasted, you should find that the address field contains something similar to the following:


&record=9940c799-359b-f2fb-2943-4c619dfc696f  


The portion to the right of the equal sign is what we will need. 


With the preliminary work out of the way, we can proceed to modify the script that sends the message. If you want to see the original script, take a look at the original post