Thursday, September 26, 2013

SugarCRM : How to set Relationship between 2 modules


To set the relationship between two module,  for example:
Module 1 : Quotes
Module 2 : Accounts

So in Db there is one table that contains relationship i.e. quotes_accounts table.

Now, if you want to insert data in quotes module with taking care of account relationship then there are 2 methods.

Method 1: Lets assume you have data like this,
I am assuming that you have last insert account id is $account_id

$bean = BeanFactory::getBean('Quotes');
$bean->name = $name;
$bean->purchase_order_num = $value['Order ID'];
$bean->billing_address_street = $value['Billing Address'];
$bean->billing_address_city = $value['Billing City'];
$bean->billing_address_state = $value['Billing State'];

//Save the entry into quotes table
$quote_id = $bean->save(); // will return last insert id

//Now to set the relationship into quotes_accounts table
$dataset = array(
'account_id' => $account_id, //last insert id in accounts module
'quote_id' => $quote_id, //last insert id in quotes module


//will enter relationship entry into quotes_accounts table:
$bean->set_relationship('quotes_accounts', array(), false, false, $dataset);

Above method is bit lengthy process.

Method 2:
in spite-of creating set_relationship() function, just use firebug tool(available in firefox)
Inspect the "Billing Account Name" textbox element, you will see the hidden element just below of it.
Copy the hidden element id, then assign it as :

$bean->billing_account_id = $account_id ;

Here, billing_account_id is hidden element ID and $account_id is last insert account module id.

then save the bean i.e.

Now you will see that data inserted into quotes and quotes_accounts table simultaneously.

I hope you got the my point :) 

If you get any doubt,   Please let me know.