Monday, August 30, 2010

SugarCRM design flaw (I believe it is)

i have a website. When a user submits a form, it will create a Lead in SugarCRM by calling its REST API.

It all works good until I create a logic hook for the Lead module. This is a after_save logic hook, which means it should only be executed after a Lead is saved.

The logic hook function is very simple, with only one line:
function RunMe(SugarBean $bean, $event, $arguments)
{
$bean->retrieve($bean->id);
}

Now, the problem comes out. The Leads created through REST service lost their Email information!

I try to create a Lead within SugarCRM, the Email information is saved properly.

This brings up two questions:
1. it seems $bean->retrieve($bean->id) cannot retrieve its email properly.
2. how can email get lost due to this after_save logic hook. Shouldn't the email get saved before this logic hook is fired? Further more, it only happens when we create Leads through REST. Leads created within SugarCRM Lead Module do not have this problem.

Solution:
I change my logic hook code like below
function RunMe(SugarBean $bean, $event, $arguments)
{
$emailAddress = clone $bean->emailAddress;
$bean->retrieve($bean->id);
$bean->emailAddress = $emailAddress;
}
Now, problem solved. Here is a thread on SugarCRM forum with similar problem. http://panther.sugarcrm.com/forums/showthread.php?t=44872

"The problem was that after_save, the bean discards all the new field info. So we needed to use $bean->retrieve($bean->id); to get it back. Then, it didn't retrieve the email addresses properly, so we needed to pull the email address out before we ran the retrieve".

In SugarCRM, Leads extends Person. When we save a Lead, SugarCRM will call Person::save() method. Within the Person's save method, it will call SugarBean's save() method first, and only after that, it calls $this->emailAddress->save() to save the email. But SugarBean's Save() method will fire after_save logic hook, and the logic hook code $bean->retrieve($bean->id) cannot retrieve its emailAddress properly, so, that explains why email is lost.

But the question becomes, why Leads created in Sugarcrm don't have this problem.