id
stringlengths 14
16
| text
stringlengths 33
5.27k
| source
stringlengths 105
270
|
---|---|---|
e690aa0ef188-1 | //Remove the teams
$bean->teams->remove(
array(
$team_id_1,
$team_id_2
)
);
Considerations
If removing teams in a logic hook, the recommended approach is to use an after_save hook rather than a before_save hook as the $_REQUEST may reset any changes you make.
Replacing Team Sets
To replace all of the teams related to a bean, you will need to load the team's relationship and use the replace() method. This method accepts an array of team ids. An example is shown below:
//Retrieve the bean
$bean = BeanFactory::getBean($module, $record_id);
//Load the team relationship
$bean->load_relationship('teams');
//Set the primary team
$bean->team_id = $team_id_1
//Replace the teams
$bean->teams->replace(
array(
$team_id_1,
$team_id_2
)
);
//Save to update primary team
$bean->save()
Considerations
If replacing teams in a logic hook, the recommended approach is to use an after_save hook rather than a before_save hook as the $_REQUEST or workflow may reset any changes you make.
This method does not replace (or set) the primary team for the record. When replacing teams, you need to also make sure that the primary team, determined by the team_id field, is set appropriately and included in the replacement ids. If this is being done in a logic hook you should set the primary team in a before_save hook and replace the team set in the after_save hook.
When using an after_save hook, be sure to call $bean->teams->setSaved(false) to explicitly reset the save state. This ensures that the updates to the team sets are applied.
Example: | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Manipulating_Teams_Programmatically/index.html |
e690aa0ef188-2 | Example:
//before save function
public function before_save_hook($bean, $event, $arguments)
{
$bean->team_id = $team_id_1;
}
//after save function
public function after_save_hook($bean, $event, $arguments)
{
$bean->teams->setSaved(false); // Manually reset TeamSet state for save
$bean->teams->replace(
array(
$team_id_1,
$team_id_2
)
);
}
Creating and Retrieving Team Set IDs
To create or retrieve the team_set_id for a group of teams, you will need to retrieve an instance of a TeamSet object and use the addTeams() method. If a team set does not exist, this method will create it and return an id. An example is below:
//Create a TeamSet bean - no BeanFactory
require_once 'modules/Teams/TeamSet.php';
$teamSetBean = new TeamSet();
//Retrieve/create the team_set_id
$team_set_id = $teamSetBean->addTeams(
array(
$team_id_1,
$team_id_2
)
);
Adding Additional Access
To enable additional access for a record, you can either set the team id or team set to the beans acl_team_set_id field. An example of this is shown below:
require_once 'modules/Teams/TeamSet.php';
// Create a new teamset or fetch the id of an existing teamset
$teamSetBean = new TeamSet();
$teamSetId = $teamSetBean->addTeams([
'East', // Demo Team ID
'West', // Demo Team ID
]); | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Manipulating_Teams_Programmatically/index.html |
e690aa0ef188-3 | 'East', // Demo Team ID
'West', // Demo Team ID
]);
$bean = BeanFactory::getBean('Accounts', '15bcf01c-1e1e-11e8-9e13-f45c89a8598f');
// Set additional access
$bean->acl_team_set_id = $teamSetId; // if set to NULL, this will remove any existing value
$bean->save();
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Manipulating_Teams_Programmatically/index.html |
2488a9c58980-0 | Data Framework
The Sugar application comprises core elements such as modules, fields, vardefs, and other foundational components. The Data Framework pages document how these core elements are modeled and implemented in Sugar.
TopicsModulesHow modules are defined and used within the systemModelsAn overview of the SugarBean model.VardefsVardefs (Variable Definitions) provide the Sugar application with information about SugarBeans. Vardefs specify information on the individual fields, relationships between beans, and the indexes for a given bean.FieldsHow fields interact with the various aspects of Sugar.RelationshipsRelationships are the basis for linking information within the system. This page explains the various aspects of relationships. For information on custom relationships, please refer to the Custom Relationships documentation.SubpanelsFor Sidecar, Sugar's subpanel layouts have been modified to work as simplified metadata. This page is an overview of the metadata framework for subpanels.DatabaseAll Sugar products support the MySQL and Microsoft SQL Server databases. Sugar Enterprise and Sugar Ultimate also support the DB2 and Oracle databases. In general, Sugar uses only common database functionality, and the application logic is embedded in the PHP code. Sugar does not use or recommend database triggers or stored procedures. This design simplifies coding and testing across different database vendors. The only implementation difference across the various supported databases is column types.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/index.html |
dfff445c31e0-0 | Modules
Overview
How modules are defined and used within the system
Module Definitions
The module definitions, defined in ./include/modules.php, determine how modules are displayed and used throughout the application. Any custom metadata, whether from a plugin or a custom module, should be loaded through the Include extension. Prior to 6.3.x, module definitions could be added by creating the file ./include/modules_override.php. This method of creating module definitions is still compatible but is not recommended from a best practices standpoint.Â
Hierarchy Diagram
The modules metadata are loaded in the following manner:
$moduleList
The $moduleList is an array containing a list of modules in the system. The format of the array is to have a numeric index and a value of the modules unique key.
$moduleList[] = 'Accounts';
$beanList
The $beanList variable is an array that stores a list of all active beans (modules) in the application. The format of the array is array('<bean plural name>' => '<bean singular name>');. The $beanList key is used to lookup values in the $beanFiles variable.
$beanList['Accounts'] = 'Account';
$beanFiles
The $beanFiles variable is an array used to reference the class files for a bean. The format of the array is array('<bean singular name>' => '<relative class file>');. The bean name, stored in singular form, is a reference to the class name of the object, which is looked up from the $beanList 'key'.
$beanFiles['Account'] = 'modules/Accounts/Account.php';
$modInvisList | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Modules/index.html |
dfff445c31e0-1 | $modInvisList
The $modInvisList variable removes a module from the navigation tab in the MegaMenu, reporting, and it's subpanels under related modules.To enable a hidden module for reporting, you can use $report_include_modules. To enable a hidden modules subpanels on related modules, you can use $modules_exempt_from_availability_check. TheÂ
$modInvisList[] = 'Prospects';
$modules_exempt_from_availability_check
The $modules_exempt_from_availability_check variable is used in conjunction with $modInvisList. When a module has been removed from the MegaMenu view with $modInvisList, this will allow for the display of the modules subpanels under related modules.
$modules_exempt_from_availability_check['OAuthKeys'] = 'OAuthKeys';
$report_include_modules
 The $report_include_modules variable is used in conjunction with $modInvisList. When a module has been hidden with $modInvisList, this will allow for the module to be enabled for reporting.
$report_include_modules['Prospects'] = 'Prospect';
$adminOnlyList
The $adminOnlyList variable is an extra level of security for modules that are can be accessed only by administrators through the Admin page. Specifying all will restrict all actions to be admin only.
$adminOnlyList['PdfManager'] = array(
'all' => 1
);
$bwcModules
The $bwcModules variable determines which modules are in backward compatibility mode. More information on backward compatibility can be found in the Backward Compatibility section.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Modules/index.html |
3c261ad5c3c2-0 | Relationships
Overview
Relationships are the basis for linking information within the system. This page explains the various aspects of relationships. For information on custom relationships, please refer to the Custom Relationships documentation.
Definitions
Relationships are initially defined in the module's vardefs file under the relationships array. For reference, you can find them using the vardef path ./modules/<module>/vardefs.php.
Database Structure
In Sugar, most relationships are stored using a joining table. This applies to both one-to-many (1:M) relationships as well as many-to-many (M:M) relationships. An example of this is the relationship between Accounts and Opportunities where there are three tables: accounts, accounts_opportunities, and opportunities. You will find that the joining table, accounts_opportunities, will contain the fields needed in order to establish the relationship link.
The fields on the accounts_opportunities table are listed below:
Fields
Description
id
A unique identifier for the relationship row (not typically used)
opportunity_id
The ID for the related opportunity record. This is named uniquely based on the relationship
account_id
The ID for the related account record. This is named uniquely based on the relationship
date_modified
The date the row was last modified
deleted
Whether or not the relationship still exists
Relationship Cache
All relationships in Sugar are compiled into the cache directory ./cache/Relationships/relationships.cache.php. If needed, the relationships cache can be rebuilt by navigating to Admin > Repair > Rebuild Relationships.
TopicsCustom RelationshipsThis page needs an overview
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Relationships/index.html |
ca45634a7d7d-0 | Custom Relationships
Overview
This page needs an overview
Creating Custom Relationships
Relationships are initially defined in the module's vardefs file under the relationships array. For reference, you can find them using the vardef path as follows:
./modules/<module>/vardefs.php
Custom relationships are created in a different way using the Extension Framework. The process requires two steps which are explained in the following sections:
Defining the Relationship MetaData
Defining the Relationship in the TableDictionary
Defining the Relationship MetaData
The definitions for custom relationships will be found in a path similar to:
./custom/metadata/<relatonship name>MetaData.php
This file will contain the $dictionary information needed for the system to generate the relationship. The $dictionary array will contain the following:
Index
Type
Description
true_relationship_type
String
The relationship's structure (possible values: 'one-to-many' or 'many-to-many')
from_studio
Boolean
Whether the relationship was created in Studio
table
String
The name of the table that is created in the database to contain the link ids
fields
Array
An array of fields to be created on the relationship join table
indices
Array
The list of indexes to be created
relationships
Array
An array defining relationships
relationships.<rel>
Array
The array defining the relationship
relationships.<rel>.lhs_module
String
Left-hand module (should match $beanList index)
relationships.<rel>.lhs_table
String
Left-hand table name
relationships.<rel>.lhs_key
String
The key to use from the table on the left
relationships.<rel>.rhs_module
String
Right-hand module (should match $beanList index)
relationships.<rel>.rhs_table
String
Right-hand table name
relationships.<rel>.rhs_key
String
The key to use from the table on the right
relationships.<rel>.relationship_type
String | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Relationships/Custom_Relationships/index.html |
ca45634a7d7d-1 | The key to use from the table on the right
relationships.<rel>.relationship_type
String
The relationship type, typically stored as 'many-to-many'
relationships.<rel>.join_table
String
The join table
relationships.<rel>.join_key_lhs
String
Left table key, should exist in table field definitions above
relationships.<rel>.join_key_rhs
String
Right table key, should exist in table field definitions above
MetaData Example
Creating a custom 1:M relationship between Accounts and Contacts will yield the following metadata file:
./custom/metadata/accounts_contacts_1MetaData.php
<?php
// created: 2013-09-20 15:15:47
$dictionary["accounts_contacts_1"] = array (
'true_relationship_type' => 'one-to-many',
'from_studio' => true,
'relationships' =>
array (
'accounts_contacts_1' =>
array (
'lhs_module' => 'Accounts',
'lhs_table' => 'accounts',
'lhs_key' => 'id',
'rhs_module' => 'Contacts',
'rhs_table' => 'contacts',
'rhs_key' => 'id',
'relationship_type' => 'many-to-many',
'join_table' => 'accounts_contacts_1_c',
'join_key_lhs' => 'accounts_contacts_1accounts_ida',
'join_key_rhs' => 'accounts_contacts_1contacts_idb',
),
),
'table' => 'accounts_contacts_1_c',
'fields' =>
array (
0 =>
array (
'name' => 'id',
'type' => 'varchar',
'len' => 36,
),
1 =>
array ( | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Relationships/Custom_Relationships/index.html |
ca45634a7d7d-2 | ),
1 =>
array (
'name' => 'date_modified',
'type' => 'datetime',
),
2 =>
array (
'name' => 'deleted',
'type' => 'bool',
'len' => '1',
'default' => '0',
'required' => true,
),
3 =>
array (
'name' => 'accounts_contacts_1accounts_ida',
'type' => 'varchar',
'len' => 36,
),
4 =>
array (
'name' => 'accounts_contacts_1contacts_idb',
'type' => 'varchar',
'len' => 36,
),
),
'indices' =>
array (
0 =>
array (
'name' => 'accounts_contacts_1spk',
'type' => 'primary',
'fields' =>
array (
0 => 'id',
),
),
1 =>
array (
'name' => 'accounts_contacts_1_ida1',
'type' => 'index',
'fields' =>
array (
0 => 'accounts_contacts_1accounts_ida',
),
),
2 =>
array (
'name' => 'accounts_contacts_1_alt',
'type' => 'alternate_key',
'fields' =>
array (
0 => 'accounts_contacts_1contacts_idb',
),
),
),
);
Defining the Relationship in the TableDictionary | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Relationships/Custom_Relationships/index.html |
ca45634a7d7d-3 | ),
),
),
);
Defining the Relationship in the TableDictionary
Once a relationship's metadata has been created, the metadata file will have a reference placed in the TableDictionary:
./custom/Extension/application/Ext/TableDictionary/<relationship name>.php
This file will contain an 'include' reference to the metadata file:
<?php
include('custom/metadata/<relationship name>MetaData.php');
?>
TableDictionary Example
The custom 1:M relationship between Accounts and Contacts will yield the following TableDictionary file:
./custom/Extension/application/Ext/TableDictionary/accounts_contacts_1.php
<?php
//WARNING: The contents of this file are auto-generated
include('custom/metadata/accounts_contacts_1MetaData.php');
?>
If you have created the relationship through Studio, the files above will be automatically created. If you are manually creating the files, run a Quick Repair and Rebuild and run any SQL scripts generated. The Quick Repair and Rebuild will rebuild the file map and relationship cache as well as populate the relationship in the relationships table.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Relationships/Custom_Relationships/index.html |
9b27bb27bb41-0 | Database
Overview
All Sugar products support the MySQL and Microsoft SQL Server databases. Sugar Enterprise and Sugar Ultimate also support the DB2 and Oracle databases. In general, Sugar uses only common database functionality, and the application logic is embedded in the PHP code. Sugar does not use or recommend database triggers or stored procedures. This design simplifies coding and testing across different database vendors. The only implementation difference across the various supported databases is column types.Â
Primary Keys, Foreign Keys, and GUIDs
By default, Sugar uses globally unique identification values (GUIDs) for primary keys for all database records. Sugar provides a Sugarcrm\Sugarcrm\Util\Uuid::uuid1() utility function for creating these GUIDs in the following format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee. The primary key's column length is 36 characters.Â
The GUID format and value has no special meaning (relevance) in Sugar other than the ability to match records in the database. Sugar links two records (such as an Accounts record with a Contacts record) with a specified ID in the record type relationship table (e.g. accounts_contacts).
Primary keys in Sugar may contain any unique string such as a GUID algorithm, a key that has some meaning (e.g. bean type first, followed by info), an external key, or auto-incrementing numbers converted to strings. Sugar chose GUIDs over auto-incrementing keys to enable easier data synchronization across databases and avoid primary-key collisions.
You can also import data from a previous system with one primary key format and make all new records in Sugar use the GUID primary key format. All keys must be stored as globally unique strings with no more than 36 characters.
Notice If multiple records between modules contain matching ids, you may experience undesired behaviors within the system. | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/index.html |
9b27bb27bb41-1 | To implement a new primary key method or to import data with a different primary key format (based on the existing GUID mechanism for new records), keep in mind the following rules of primary key behavior:
Quote characters : Sugar expects primary keys to be string types and will format the SQL with quotes. If you change the primary key types to an integer type, SQL errors may occur since Sugar stores all ID values in quotes in the generated SQL. The database may be able to ignore this issue. MySQL running in Safe mode experiences issues, for instance.
Case sensitivity : The ID values abc and ABC are treated the same in MySQL but represent different values in Oracle. When migrating data to Sugar, some CRM systems may use case-sensitive strings as their IDs on export. If this is the case, and you are running MySQL, you must run an algorithm on the data to make sure all of the IDs are unique. One simple algorithm is to MD5 the ID values that they provide. A quick check will let you know if there is a problem. If you imported 80,000 leads and there are only 60,000 in the system, some may have been lost due to non-unique primary keys caused by case insensitivity.
Key size : Sugar only tracks the first 36 characters in the primary key. Any replacement primary key will either require changing all of the ID columns with one of an appropriate size or to make sure you do not run into any truncation or padding issues. MySQL in some versions has had issues with Sugar where the IDs were not matching because it was adding spaces to pad the row out to the full size. MySQL's handling of char and varchar padding has changed in later versions. To protect against this, make sure the GUIDs are not padded with blanks in the database by removing any leading or trailing space characters.
Indexes | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/index.html |
9b27bb27bb41-2 | Indexes
Indexes can be defined in the main or custom vardefs.php for a module in an array under the key indices. See below for an example of defining several indices:
'indices' => array(
array(
'name' => 'idx_modulename_name',
'type' => 'index',
'fields' => array('name'),
),
array(
'name' => 'idx_modulename_assigned_deleted',
'type' => 'index',
'fields' => array('assigned_user_id', 'deleted'),
),
),
The name of the index must start with idx_ and must be unique across the database. Possible values for type include primary for a primary key or index for a normal index. The fields list matches the column names used in the database.
Doctrine
In order to provide robust support for Prepared Statements, which provide more security and better database access performance, Sugar 7.9 has adopted parts of Doctrine's Database Abstraction Layer, especially the QueryBuilder class, for working with prepared statements. The picture below shows how Sugar objects like DBManager and SugarQuery utilize Doctrine to provide this functionality, while still using the same toolset that has existed in Sugar.
Â
DBManager
The DBManager class will use Doctrine QueryBuilder for building INSERT and UPDATE queries.
SugarQuery
The SugarQuery class will use Doctrine QueryBuilder for building SELECT queries.
SugarBean
The SugarBean class will continue to use DBManager class for saving all fields.
TopicsDBManagerThe DBManager Object provides an interface for working with the database.SugarQuerySugarQuery, located in ./include/SugarQuery/SugarQuery.php, provides an object-oriented approach to working with the database. This allows developers to generate the applicable SQL for a Sugar system without having to know which database backend the instance is using. SugarQuery supports all databases supported by Sugar. | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/index.html |
9b27bb27bb41-3 | Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/index.html |
596861757546-0 | DBManager
Overview
The DBManager Object provides an interface for working with the database.
Instantiating the DBManager Object
The DBManagerFactory class, located in ./include/database/DBManagerFactory.php, can help instantiate a DBManager object using the getInstance() method.
$db = \DBManagerFactory::getInstance();
For best practices, we recommend using the global DBManager Object:
$GLOBALS['db']
Querying The Database
Sugar supports prepared statements. The following sections outline the legacy usage and the newly prepared statement usage.
SELECT queries
For select queries that do not have a dynamic portion of the where clause, you can use the query()Â method on the DBManager object. For queries that are accepting data passed into the system in the where clause, the following examples demonstrate how best utilize the new Prepared Statement functionality.
Legacy:
$id = '1234-abcde-fgh45-6789';
$query = 'SELECT * FROM accounts WHERE id = ' . $GLOBALS['db']->quoted($id);
$results = $GLOBALS['db']->query($query);
Best Practice:
Use the getConnection() method to retrieve a Doctrine Connection Object which handles prepared statements.
$id = '1234-abcde-fgh45-6789';
$query = 'SELECT * FROM accounts WHERE id = ?';
$conn = $GLOBALS['db']->getConnection();
$result = $conn->executeQuery($query, [$id]);
In the case that query logic is variable or conditionally built then it makes sense to use Doctrine QueryBuilder directly.
Legacy:
$query = 'SELECT * FROM accounts';
if ($status !== null) {
$query .= ' WHERE status = ' . $GLOBALS['db']->quoted($status);
}
$results = $GLOBALS['db']->query($query);
Best Practice: | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/DBManager/index.html |
596861757546-1 | }
$results = $GLOBALS['db']->query($query);
Best Practice:
Use the getConnection() method to retrieve the Doctrine Connection Object, and then use the createQueryBuilder() method on the Connection Object to retrieve the QueryBuilder Object.
$builder = $GLOBALS['db']->getConnection()->createQueryBuilder();
$builder->select('*')->from('accounts');
if ($status !== null) {
$builder->where('status = ' . $builder->createPositionalParameter($status));
}
$result = $builder->executeQuery();
Retrieving Results
Legacy:
After using the query() method, such as in the Legacy code examples above, you can use the fetchByAssoc() method to retrieve results. The query() method will submit the query and retrieve the results while the fetchByAssoc() method will iterate through the results:
$sql = "SELECT id FROM accounts WHERE deleted = 0";
$result = $GLOBALS['db']->query($sql);
while($row = $GLOBALS['db']->fetchByAssoc($result) )
{
//Use $row['id'] to grab the id fields value
$id = $row['id'];
}
Best Practice:
When using Prepared Statements, both the Doctrine Query Builder and the Doctrine Connection Object will return a Doctrine\DBAL\Result Object to allow iterating through the results of the query. You can use the fetchNumeric() , fetchAssociative() or fetchAllNumeric() or fetchAllAssociative() methods to retrieve results.
fetchAllAssociative() Example
The fetchAllAssociative() method will return the entire result set as an associative array, with each index containing a row of data.
$conn = $GLOBALS['db']->getConnection();
$result = $conn->executeQuery("SELECT * FROM accounts");
foreach ($result->iterateAssociative() as $row) { | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/DBManager/index.html |
596861757546-2 | foreach ($result->iterateAssociative() as $row) {
$name = $row['name'];
// do something
}
iterateAssociativeIndexed() Example
The iterateAssociativeIndexed() method executes the query and iterate over the result with the key representing the first column and the value is an associative array of the rest of the columns and their values:
$query = 'SELECT id, name FROM accounts';
$conn = $GLOBALS['db']->getConnection();
foreach ($conn->iterateAssociativeIndexed($query) as $id => $data) {
// ...
}
Retrieving a Single Result
To retrieve a single result from the database, such as a specific record field, you can use the getOne() method for Legacy query usage.
$sql = "SELECT name FROM accounts WHERE id = :id";
$conn = $GLOBALS['db']->getConnection();
$row = $conn->fetchAssociative($sql, ['id' => $id]);
// alternative
$sql = "SELECT name FROM accounts WHERE id = '{$id}'";
$name = $GLOBALS['db']->getOne($sql);
Limiting Results
To limit the results of a query, you can add a limit to the SQL string or for legacy query usage you can use the limitQuery() method on the DBManager Object:
Legacy:
$sql = "SELECT id FROM accounts WHERE deleted = 0";
$offset = 0;
$limit = 1;
$result = $GLOBALS['db']->limitQuery($sql, $offset, $limit);
while($row = $GLOBALS['db']->fetchByAssoc($result) )
{
//Use $row['id'] to grab the id fields value
$id = $row['id'];
}
Prepared Statements: | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/DBManager/index.html |
596861757546-3 | $id = $row['id'];
}
Prepared Statements:
When using the Doctrine Query Builder, you can limit the results of the query by using the setMaxResults() method.
$builder = $GLOBALS['db']->getConnection()->createQueryBuilder();
$builder->select('*')->from('accounts');
if ($status !== null) {
$builder->where('status = ' . $builder->createPositionalParameter($status));
}
$builder->setMaxResults(2);
$result = $builder->executeQuery();
INSERT queries
INSERT queries can be easily performed using DBManager class.
Legacy:
$query = 'INSERT INTO table (foo, bar) VALUES ("foo", "bar")';
$GLOBALS['db']->query($query);
Best Practice:
$fieldDefs = $GLOBALS['dictionary']['table']['fields'];
$GLOBALS['db']->insertParams('table', $fieldDefs, ['foo' => 'foo','bar' => 'bar']);
UPDATE queries
When updating records with known IDs or a set of records with simple filtering criteria, then DBManager can be used:
Legacy:
$query = 'UPDATE table SET foo = "bar" WHERE id = ' . $GLOBALS['db']->quoted($id);
$GLOBALS['db']->query($query);
Best Practice:
$fieldDefs = $GLOBALS['dictionary']['table']['fields'];
$GLOBALS['db']->updateParams('table', $fieldDefs, ['foo' => 'bar',], ['id' => $id]);
For more complex criteria or when column values contain expressions or references to other fields in the table then Doctrine QueryBuilder can be used.
Legacy:
$query = 'UPDATE table SET foo = "bar" WHERE foo = "foo" OR foo IS NULL';
$GLOBALS['db']->query($query);
Best Practice: | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/DBManager/index.html |
596861757546-4 | $GLOBALS['db']->query($query);
Best Practice:
$query = 'UPDATE table SET foo = ? WHERE foo = ? OR foo IS NULL';
$conn = $GLOBALS['db']->getConnection();
$rowCount = $conn->executeStatement($query, ['bar', 'foo']);
Generating SQL Queries from SugarBean
To have Sugar automatically generate SQL queries, you can use the following methods from the bean class.
Select Queries
To create a select query you can use the create_new_list_query() method:
$bean = BeanFactory::newBean($module);
$order_by = '';
$where = '';
$fields = array(
'id',
'name',
);
$sql = $bean->create_new_list_query($order_by, $where, $fields);
Count Queries
You can also run the generated SQL through the create_list_count_query() method to generate a count query:
$bean = BeanFactory::newBean('Accounts');
$sql = "SELECT * FROM accounts WHERE deleted = 0";
$count_sql = $bean->create_list_count_query($sql);
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/DBManager/index.html |
6ba0a71f4c57-0 | SugarQuery
Overview
SugarQuery, located in ./include/SugarQuery/SugarQuery.php, provides an object-oriented approach to working with the database. This allows developers to generate the applicable SQL for a Sugar system without having to know which database backend the instance is using. SugarQuery supports all databases supported by Sugar.
Note: SugarQuery only supports reading data from the database at this time (i.e. SELECT statements).Â
Setup
To use SugarQuery, simply create a new SugarQuery object.
$sugarQuery = new SugarQuery();
Basic Usage
Using the SugarQuery object to retrieve records or generate SQL queries is very simple. At a minimum you need to set the Module you are working with, using the from() method, however, there are helper methods for just about any operation you would need in a SQL query. The methods listed below will outline the major methods you should consider utilizing on the SugarQuery object in order to achieve your development goals.
from()
The from() method is used to set the primary module the SugarQuery object will be querying from. It is also used to set some crucial options for the query, such as whether Team Security should be used or if only non-deleted records should be queried. The following example will set the SugarQuery object to query from the Accounts module.
$sugarQuery->from(BeanFactory::newBean('Accounts'));
Arguments
Name
Type
Required
Description
$bean
SugarBean Object
true
The SugarBean object for a specified module. The SugarBean object does not have to be a blank or new Bean as seen in the example above, but can be a previously instantiated SugarBean object.
$options
Array
false
An associative array that can specify any of the following options: | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/index.html |
6ba0a71f4c57-1 | Array
false
An associative array that can specify any of the following options:
alias - string -Â The alias for the module table in the generated SQL query
team_security -Â boolean - Whether or not Team Security should be added to the generated SQLÂ queryÂ
add_deleted -Â boolean - Whether or not 'deleted' = 0 should be added to Where clause of generated SQL query
Returns
SugarQuery Object
Allows for method chaining on the SugarQuery object.
select()
The example above demonstrates the most basic example of retrieving records from a module. The select() method can be used on the SugarQuery object to specify the specific fields you wish to retrieve from the query.
//Alter the Selected Fields
$sugarQuery->select(array('id', 'name'));
Arguments
Name
Type
Required
Description
$fields
Array
false
Sets the fields that should be added to the SELECT portion of the SQL query
Returns
SugarQuery_Builder_Select Object
You cannot chain SugarQuery methods off of the select() method, however, you can use the returned Select object to modify the SELECT portion of the statement. Review the SugarQuery_Builder_Select object in ./include/SugarQuery/Builder/Select.php for additional information on usage.
where()
To add a WHERE clause to the query, use the where() method to generate the Where object, and then use method chaining with the various helper methods to add conditions. To add a WHERE clause for records with the name field containing the letter "I", you could add the following code.Â
//add the where clause
$sugarQuery->where()->contains('name', 'I');
Arguments
None
Returns
SugarQuery_Builder_Where Object | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/index.html |
6ba0a71f4c57-2 | Arguments
None
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object as shown above. Review the SugarQuery Conditions documentation for a full spectrum of where() method usage.
Relationships
join()
To add data from a related module to the SugarQuery, use the join() method. Adding to the same SugarQuery code example in this page, the following code would add the JOIN from Accounts module tables to Contacts table:
//add join
$sugarQuery->join('contacts');
Arguments
Name
Type
Required
Description
$link_name
String
true
The name of the relationship
$options
Array
false
Â
An associative array that can specify any of the following options:
alias - string -Â The alias for the module table in the generated SQL query
relatedJoin - string - If joining to a secondary table (related to a related module), such as joining on Opportunities related to Contacts, when querying from Accounts, you can specify either the name of the relationship or the alias you specified for that relationship table.
Returns
SugarQuery_Builder_Join Object
Allows for method chaining on the SugarQuery_Builder_Join Object, to add additional conditions to the WHERE clause of the SQL condition.Â
joinTable()
If you were using the joinRaw() method in previous versions of Sugar, this is the replacement method which allows for joining to a related table in SugarQuery. Adding to the same SugarQuery code example in this page, the following code would add the JOIN from Accounts module tables to the accounts_contacts table:
//add join
$sugarQuery->joinTable('accounts_contacts', array('alias' => 'ac'))->on()
->equalsField('accounts.id','ac.account_id') | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/index.html |
6ba0a71f4c57-3 | ->equalsField('accounts.id','ac.account_id')
->equals('ac.primary_account',1);
Arguments
Name
Type
Required
Description
$table_name
String
true
The name of the database table to join.Â
$options
Array
false
Â
An associative array that can specify any of the following options:
alias - string -Â The alias for the module table in the generated SQL query
Returns
SugarQuery_Builder_Join Object
Allows for method chaining on the SugarQuery_Builder_Join Object, to add additional conditions to the ONÂ clause using the on() method.Â
Altering Results
Altering the result set of a query can help the performance, as well as be crucial to finding the correct data. The following methods provide ways to limit the result set and change the order.
distinct()
To group the query on a field, you can use the corresponding distinct() method.
//add group by
$sugarQuery->distinct(true);
Arguments
Name
Type
Required
Description
$value
Boolean
true
Set whether or not the DISTINCT statement should be added to the query
Returns
Current SugarQuery Object
Allows for method chaining on the SugarQuery Object.
limit()
To limit the results of the query, you can use the limit() method.Â
//set the limit
$sugarQuery->limit(10);
Arguments
Name
Type
Required
Description
$number
Integer
true
The max amount of rows that should be returned by the query
Returns
Current SugarQuery Object
Allows for method chaining on the SugarQuery Object.
offset() | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/index.html |
6ba0a71f4c57-4 | Current SugarQuery Object
Allows for method chaining on the SugarQuery Object.
offset()
Adding a limit to the query limits the rows returned, however when doing so, you may need to alter the offset of the query to account for pagination or access other portions of the result set. To set an offset, you can use the offset() method.
//set the offset
$sugarQuery->offset(5);
Arguments
Name
Type
Required
Description
$number
Integer
true
The offset amount of rows, or starting point, of the result
Returns
Current SugarQuery Object
Allows for method chaining on the SugarQuery Object.
orderBy()
To order the query on a field, you can use the corresponding orderBy() method. This method can be called multiple times, to add multiple fields to the order by clause of the query.
//add group by
$sugarQuery->orderBy('account_type');
Arguments
Name
Type
Required
Description
$column
String
true
The field you want the query to be grouped on
$direction
String
false
Sets the direction of sorting. Must be 'ASC' or 'DESC'. The default is 'DESC'.
Returns
Current SugarQuery Object
Allows for method chaining on the SugarQuery Object.
Execution
Once you have the SugarQuery object setup and configured for your statement, you will want to retrieve the results of the query, or simply get the generated query for the object. The following methods are used for executing the SugarQuery object.
execute()
To query the database for a result set, you will use the execute() method. The execute() method will retrieve the results and return them as a raw string, db object, json, or an array depending on the $type parameter. By default, results are returned as an array. An example of fetching records from an account is below: | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/index.html |
6ba0a71f4c57-5 | //fetch the result
$result = $sugarQuery->execute();
The execute() function will return an array of results that you can iterate through as shown below:
Array
(
[0] => Array
(
[id] => f39593da-3f88-3059-4f18-524b4d23d07b
[name] => International Art Inc
)
)
Note:Â An empty resultset will return an empty array.
Arguments
Name
Type
Required
Description
$type
String
false
How you want the results of the Query returned. Can be one of the following options:
db - Returns the result directly from the DatabaseManager resource
array - Default - Returns the results as a formatted array
json - Returns the results encoded as JSON
Returns
Default: Array. See above argument details for details on other Return options.
compile()
If you want to log the query being generated or want to output the query without running it during development, the compile() method is what should be used retrieve the Prepared Statement. You can then retrieve the Prepared Statement Object to retrieve the Parameterized SQL and the Parameters. For further information on Prepared Statement usage, see our Database documentation.
//get the compiled prepared statement
$preparedStmt = $sugarQuery->compile();
//Retrieve the Parameterized SQL
$sql = $preparedStmt->getSQL();
//Retrieve the parameters as an array
$parameters = $preparedStmt->getParameters();
Arguments
No arguments
Returns
Object
The compiled SQL Query built by the SugarQuery object.
TopicsSugarQuery ConditionsLearn about the various methods that can be utilized with SugarQuery to add conditional statements to a query.Advanced TechniquesLearn about some of the advanced methods that SugarQuery has to offer, that are not as commonly used. | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/index.html |
6ba0a71f4c57-6 | Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/index.html |
c07c7ba83dd9-0 | SugarQuery Conditions
Overview
Learn about the various methods that can be utilized with SugarQuery to add conditional statements to a query.Â
Where Clause
Manipulating, the WHERE clause of a SugarQuery object is crucial for getting the correct results. To create a WHERE clause on the query, use the where() method on the SugarQuery object, as outlined in the SugarQuery documentation. Once you have the Where object, you can utilize the following methods on the Where object to add conditional statements.
equals() | notEquals()
Used to equate a field to a given value. Wildcards will not work with this function, as it is looking for an exact match.
//add equals
$SugarQuery->where()->equals('name','Test');
//add Not Equals
$SugarQuery->where()->notEquals('name','Tester');
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
$value
String
true
The value the field should be equal to
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object to add additional conditions.
equalsField() | notEqualsField()
Used to equate a field to another field in the result set.
//add an Equals Field statement
$SugarQuery->where()->equalsField('industry','account_type');
//add a Not Equals Field statement
$SugarQuery->where()->notEqualsField('name','account_type');
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
$field
String
true
The other field you want the first field to be equal to
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object to add additional conditions.Â
isEmpty() | isNotEmpty() | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/SugarQuery_Conditions/index.html |
c07c7ba83dd9-1 | isEmpty() | isNotEmpty()
Used to check if a field is or isn't empty.
//add an isEmpty statement
$SugarQuery->where()->isEmpty('industry');
//add an isNotEmpty statement
$SugarQuery->where()->isNotEmpty('name');
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object to add additional conditions.Â
isNull() | notNull()
Used to check if a field is or isn't equal to NULL.
//add an isNull statement
$SugarQuery->where()->isNull('industry');
//add a notNull statement
$SugarQuery->where()->notNull('name');
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object to add additional conditions.Â
contains() | notContains()
Used to check if a field has or doesn't have a specified string in its value. Utilizes the LIKE statement, and wildcards on both sides of the provided string.
//add an isNull statement
$SugarQuery->where()->contains('name','Test');
//add a notNull statement
$SugarQuery->where()->notContains('industry','Test');
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
$value
String
true
The string being searched for in the value of the field
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where Object to add additional conditions.Â
starts() | ends() | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/SugarQuery_Conditions/index.html |
c07c7ba83dd9-2 | starts() | ends()
Similar to the above contains() method, these methods use the LIKE statement in the SQL query and wildcards for searching for a specified string in the field's value. However, the starts() and ends() methods only wildcard the right side and the left side, respectively. The following example demonstrates searching for records where the Name field starts with A, and ends with E.
//add an starts and ends statement
$SugarQuery->where()->starts('name','A')->ends('name','e');
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
$value
String
true
The string being searched for in the value of the field
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object to add additional conditions.Â
in() | notIn()
Used to check if a field's value is or isn't one of a set of specified values. The following examples look for records where the industry field is in a list of values, and not in a separate list of values.
$values = array(
'Support',
'Sales',
'Engineering'
);
//add in statement
$SugarQuery->where()->in('industry',$values);
$values = array(
'Marketing',
'Accounting'
);
//add NotIn Statement
$SugarQuery->where()->notIn('industry',$values);
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checkingÂ
$values
Array
true
The array of values which the field is being checked against
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object to add additional conditions.Â
between() | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/SugarQuery_Conditions/index.html |
c07c7ba83dd9-3 | Allows for method chaining on the Where object to add additional conditions.Â
between()
Used primarily for numeric type fields, to check if the value is greater than the minimum number specified and less than the maximum number specified. The following code would check for records where the employees field is between 50 and 1000.
//add Between statement
$SugarQuery->where()->between('employees',50,1000);
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
$min
Number
true
The lowest number the field's value should be
$max
Number
true
The highest number the field's value should be
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object to add additional conditions.Â
lt() | lte() | gt() | gte()
These methods are primarily for numeric fields, to check if a field's value is less than (<), less than or equal (<=), greater than (>), or greater than or equal (>=) to a specified value.
//Add Less Than Statement
$SugarQuery->where()->lt('gross_revenue',1000000);
//Add Less Than or Equal to Statement
$SugarQuery->where()->lte('net_revenue','500000');
//Add Greater Than Statement
$SugarQuery->where()->gt('gross_revenue',500000);
//Add Greater Than or Equal to Statement
$SugarQuery->where()->gte('net_revenue',100000);
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
$value
Number
true
The numeric value for comparisonÂ
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object to add additional conditions. | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/SugarQuery_Conditions/index.html |
c07c7ba83dd9-4 | Allows for method chaining on the Where object to add additional conditions.Â
dateRange()
Used to check if a field's value is between a preset date range from the current time. See the TimeDate documentation on the available date range keys.
//add DateRange statement
$SugarQuery->where()->dateRange('date_modified','last_30_days');
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
$value
String
true
The string specifying the date range key that will be used for comparison. Example 'next_7_days'
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object to add additional conditions.Â
dateBetween()
To group the query on a field, you can use the corresponding groupBy() method. This method can be called multiple times, to add multiple fields to the grouping of the query.
//add group by
$SugarQuery->where()->dateBetween('date_created',array('2016-01-01','2016-03-01'));
Arguments
Name
Type
Required
Description
$field
String
true
The field you are checking againstÂ
$value
Array
true
An array containing the minimum date in the first key, and the maximum date in the second.
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where Object to add additional conditions.Â
Combinations | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/SugarQuery_Conditions/index.html |
c07c7ba83dd9-5 | Combinations
Now that you have reviewed all of the available conditional statements for SugarQuery, you may want to combine them using AND and OR all within the same query. By default when the where() method is called, chained conditional methods will be added with AND to the where clause. You can specify an OR where clause on the main SugarQuery object by using the orWhere() method, which works the same as the where() method, just adds conditional statements with OR instead. The following methods allow for adding internal AND and OR logic to conditional statements on the Where object.
queryAnd()
To start a group of conditional statements that should all evaluate to True, use the queryAnd() method. For example, if you want to query for Accounts, where the name contains 'Test' AND description contains 'Test', you might use the following code:
$SugarQuery = new SugarQuery();
$SugarQuery->select(array('name'));
$SugarQuery->from(BeanFactory::newBean('Accounts'));
//Using queryAnd
$SugarQuery->where()->queryAnd()->contains('name','Test')->contains('description','Test');
The above use of queryAnd() method isn't entirely needed, as the main Where object would be using AND for all conditions anyway, but it does group the two conditions inside of their own parenthesis in the compiled query, as shown below, to demonstrate how it can be used for altering query logic.
SELECT accounts.name name FROM accounts WHERE accounts.deleted = 0 AND (accounts.name LIKE '%Test%' AND accounts.description LIKE '%Test%')
queryOr()
To start a group of conditional statements that should evaluate to true, if any condition is true, you can use the queryOr() method. For example, if you want to query for Accounts, where the name contains 'Test' or where the description contains 'Test', you might use the following code: | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/SugarQuery_Conditions/index.html |
c07c7ba83dd9-6 | $SugarQuery = new SugarQuery();
$SugarQuery->select(array('name'));
$SugarQuery->from(BeanFactory::newBean('Accounts'));
//Using queryOr
$SugarQuery->where()->queryOr()->contains('name','Test')->contains('description','Test');
This will group the two conditions inside of their own parenthesis in the compiled query. If either of the conditions is True, it will return a record. An example is shown below.
SELECT accounts.name name FROM accounts WHERE accounts.deleted = 0 AND (accounts.name LIKE '%Test%' OR accounts.description LIKE '%Test%')
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/SugarQuery_Conditions/index.html |
5e4d4d2e78f6-0 | Advanced Techniques
Overview
Learn about some of the advanced methods that SugarQuery has to offer, that are not as commonly used.
Get First Record
Getting the first record in a result set, can be accomplished by using the limit() method. The getOne() method is similar in that it gets the first record, but it also returns the first piece of data for that record.Â
getOne()
Get the first piece of data on the first record returned by the generated query. In this example, we want the 'name' from the Account with a given ID.
$SugarQuery = new SugarQuery();
$SugarQuery->select(array('name'));
$SugarQuery->from(BeanFactory::newBean('Accounts'));
$SugarQuery->where()->equals('id',$id);
//Get the Name of the account
$accountName = $SugarQuery->getOne();
Aggregates
setCountQuery()
Currently, the only method available for creating an aggregate column, is the setCountQuery() method on the SugarQuery_Builder_Select Object. You can add this method to your select() method chain, to add count(0) as record_count to the SQL SELECT statement.
$SugarQuery = new SugarQuery();
$SugarQuery->select(array('name'))->setCountQuery();
$SugarQuery->from(BeanFactory::newBean('Accounts'));
$SugarQuery->groupByRaw('accounts.name');
The above example will output the following prepared statement when using compile():
SELECT accounts.name, COUNT(0) AS record_count FROM accounts WHERE accounts.deleted = ? GROUP BY accounts.name, accounts.name
Parameters
array (
[1] => 0
)
Arguments
No arguments
Returns
SugarQuery_Builder_Select Object
Allows for method chaining on the Select Object.
Joins | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/Advanced_Techniques/index.html |
5e4d4d2e78f6-1 | Allows for method chaining on the Select Object.
Joins
Joining to tables and joining via SugarBean relationships is outlined in the SugarQuery documentation, however the SugarQuery_Builder_Join Object has a few helpful methods not mentioned there.
joinName()
If you are not using a custom alias for the relationship or table, you may want to retrieve the generated name used by SugarQuery to add a conditions or join to.
$SugarQuery = new SugarQuery();
$SugarQuery->from(BeanFactory::getBean('Accounts'));
$contacts = $SugarQuery->join('contacts')->joinName();
$SugarQuery->select(array("$contacts.full_name"));
$SugarQuery->where()->equals('industry', 'Media');
The above example will output the following prepared statement when using compile():
SELECT jt0_contacts.salutation rel_full_name_salutation, jt0_contacts.first_name rel_full_name_first_name, jt0_contacts.last_name rel_full_name_last_name FROM accounts INNER JOIN accounts_contacts jt1_accounts_contacts ON (accounts.id = jt1_accounts_contacts.account_id) AND (jt1_accounts_contacts.deleted = ?) INNER JOIN contacts jt0_contacts ON (jt0_contacts.id = jt1_accounts_contacts.contact_id) AND (jt0_contacts.deleted = ?) WHERE (accounts.industry = ?) AND (accounts.deleted = ?)
Parameters:
array (
[1] => 0
[2] => 0
[3] => Media
[4] => 0
)
Â
Arguments
No arguments
Returns
string
The name used in Query to identify the joined table
Unions
Unions allow joining multiple queries with the same selected fields to be combined during output. You can use Unions in SugarQuery by using the union() method.
union() | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/Advanced_Techniques/index.html |
5e4d4d2e78f6-2 | union()
To add a union, you can use the corresponding union() method. The example below will join two SQL queries:
//Fetch the bean of the module to query
$bean = BeanFactory::newBean('Accounts');
//Specify fields to fetch
$fields = array(
'id',
'name'
);
//Create first query
$sq1 = new SugarQuery();
$sq1->select($fields);
$sq1->from($bean, array('team_security' => false));
$sq1->Where()->in('account_type', array('Customer'));
//Create second query
$sq2 = new SugarQuery();
$sq2->select($fields);
$sq2->from($bean, array('team_security' => false));
$sq2->Where()->in('account_type', array('Investor'));
//Create union
$sqUnion = new SugarQuery();
$sqUnion->union($sq1);
$sqUnion->union($sq2);
$sqUnion->limit(5);
The above example will output the following prepared statement when using compile():
SELECT accounts.id, accounts.name FROM accounts WHERE (accounts.account_type IN (?)) AND (accounts.deleted = ?) UNION ALL SELECT accounts.id, accounts.name FROM accounts WHERE (accounts.account_type IN (?)) AND (accounts.deleted = ?) LIMIT 5
Parameters:
array (
[1] => Customer
[2] => 0
[3] => Investor
[4] => 0
)
Arguments
Name
Type
Required
Description
$selectÂ
SugarQuery
true
The SugarQuery Object you wish to add to the UNION query
$all
Boolean
false
Whether to use UNION ALL or just UNION in the query. The default value is TRUE.
Returns
SugarQuery_Builder_Union Object | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/Advanced_Techniques/index.html |
5e4d4d2e78f6-3 | Returns
SugarQuery_Builder_Union Object
Allows for method chaining on the Union Object.
Having
When using aggregates in a query, you might want to filter out values based on a condition. SugarQuery provides the having() method for adding HAVING clause to the query.
having()
To use the having() method, you have to build a SugarQuery_Builder_Condition Object and set the field, operator, and value that condition is based on.
$SugarQuery = new SugarQuery();
$SugarQuery->from(BeanFactory::getBean('Accounts'));
$SugarQuery->join('contacts', array('alias' => 'industryContacts'));
$SugarQuery->join('opportunities', array('relatedJoin' => 'industryContacts', 'alias' => 'contactsOpportunities'));
$SugarQuery->select()->setCountQuery();
$SugarQuery->where()->equals('contactsOpportunities.sales_stage', 'closed');
$havingCondition = new SugarQuery_Builder_Condition($SugarQuery);
$havingCondition->setField('contactsOpportunities.amount')->setOperator('>')->setValues('1000');
$SugarQuery->having($havingCondition);
The above example will output the following prepared statement when using compile(): | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/Advanced_Techniques/index.html |
5e4d4d2e78f6-4 | The above example will output the following prepared statement when using compile():
SELECT COUNT(0) AS record_count FROM accounts INNER JOIN accounts_contacts jt0_accounts_contacts ON (accounts.id = jt0_accounts_contacts.account_id) AND (jt0_accounts_contacts.deleted = ?) INNER JOIN contacts industryContacts ON (industryContacts.id = jt0_accounts_contacts.contact_id) AND (industryContacts.deleted = ?) INNER JOIN opportunities_contacts jt1_opportunities_contacts ON jt1_opportunities_contacts.deleted = ? INNER JOIN opportunities contactsOpportunities ON (contactsOpportunities.id = jt1_opportunities_contacts.opportunity_id) AND (contactsOpportunities.deleted = ?) WHERE (contactsOpportunities.sales_stage = ?) AND (accounts.deleted = ?) HAVING contactsOpportunities.amount > ?
Parameters:
array (
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => closed
[6] => 0
[7] => 1000
)
Arguments
Name
Type
Required
Description
$conditionÂ
SugarQuery_Builder_Condition
true
The conditional object used to generate the HAVING clause
Returns
SugarQuery_Builder_Having Object
Allows for method chaining on the Having Object to add additional conditions.
Raw Methods
The SugarQuery Object has a few helper methods that allow raw SQL statement parts to be passed into. This allows for more complex statements or edge case scenarios where a helper function may not have met the requirements for the query.Â
whereRaw() | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/Advanced_Techniques/index.html |
5e4d4d2e78f6-5 | whereRaw()
To add to the WHERE clause of SugarQuery Object with raw SQL syntax, you can utilize the whereRaw() method. This method will append the specified statement, to the WHERE clause using an AND operator, and will wrap the entire statement in parenthesis. The following is an example use with the output:
$SugarQuery = new SugarQuery();
$SugarQuery->select(array('name'));
$SugarQuery->from(BeanFactory::newBean('Accounts'));
$SugarQuery->whereRaw("name LIKE '%T%'");
The above example will output the following prepared statement when using compile():
SELECT accounts.name FROM accounts WHERE (name LIKE '%T%') AND (accounts.deleted = ?)
Parameters:
array (
[1] => 0
)
Arguments
Name
Type
Required
Description
$sql
String
true
The WHERE clause SQL to be appended to the where clause on the SugarQuery object. All conditions passed in are wrapped in parenthesis and appended using AND (if other conditions exist on where clause).
Returns
SugarQuery_Builder_Where Object
Allows for method chaining on the Where object.
groupByRaw()
To add multiple fields to the GROUP BY statement on the SugarQuery Object, it may be easiest to use the groupByRaw() method.
$SugarQuery = new SugarQuery();
$SugarQuery->select(array('account_type', 'industry'));
$SugarQuery->from(BeanFactory::newBean('Accounts'));
$SugarQuery->groupByRaw("accounts.account_type,accounts.industry");
The above example will output the following prepared statement when using compile():
SELECT accounts.account_type, accounts.industry FROM accounts WHERE accounts.deleted = ? GROUP BY accounts.account_type,accounts.industry
Parameters:
array (
[1] => 0
)
Arguments
Name
Type
Required
Description
$sql | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/Advanced_Techniques/index.html |
5e4d4d2e78f6-6 | )
Arguments
Name
Type
Required
Description
$sql
String
true
The GROUP BY statement, without the GROUP BY keyword.Â
Returns
SugarQuery Object
Allows for method chaining on the SugarQuery Object.
orderByRaw()
Using the oderBy() method only allows for adding a single field to the SugarQuery object at a time. In some cases, you might consider using the orderByRaw() method to add multiple fields or the entire ORDER BY statement to the SugarQuery object.Â
$SugarQuery = new SugarQuery();
$SugarQuery->select(array('name'));
$SugarQuery->from(BeanFactory::newBean('Accounts'));
$SugarQuery->orderByRaw("accounts.name DESC, accounts.date_modified");
The above example will output the following prepared statement when using compile():
SELECT accounts.name FROM accounts WHERE accounts.deleted = ? ORDER BY accounts.name DESC, accounts.date_modified DESC, accounts.id DESC
Parameters:
array (
[1] => 0
)
Arguments
Name
Type
Required
Description
$sql
String
true
The ORDER BY statement, without the ORDER BY keyword.
Returns
SugarQuery Object
Allows for method chaining on the SugarQuery Object.
havingRaw()
Using the havingRaw() method allows for adding a having statement to the SugarQuery object.Â
$SugarQuery = new SugarQuery();
$SugarQuery->from(BeanFactory::getBean('Accounts'));
$SugarQuery->join('contacts', array('alias' => 'industryContacts'));
$SugarQuery->join('opportunities', array('relatedJoin' => 'industryContacts', 'alias' => 'contactsOpportunities'));
$SugarQuery->select()->setCountQuery();
$SugarQuery->where()->equals('contactsOpportunities.sales_stage', 'closed'); | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/Advanced_Techniques/index.html |
5e4d4d2e78f6-7 | $SugarQuery->where()->equals('contactsOpportunities.sales_stage', 'closed');
$SugarQuery->havingRaw("contactsOpportunities.amount > 1000");
The above example will output the following prepared statement when using compile():
SELECT COUNT(0) AS record_count FROM accounts INNER JOIN accounts_contacts jt0_accounts_contacts ON (accounts.id = jt0_accounts_contacts.account_id) AND (jt0_accounts_contacts.deleted = ?) INNER JOIN contacts industryContacts ON (industryContacts.id = jt0_accounts_contacts.contact_id) AND (industryContacts.deleted = ?) INNER JOIN opportunities_contacts jt1_opportunities_contacts ON jt1_opportunities_contacts.deleted = ? INNER JOIN opportunities contactsOpportunities ON (contactsOpportunities.id = jt1_opportunities_contacts.opportunity_id) AND (contactsOpportunities.deleted = ?) WHERE (contactsOpportunities.sales_stage = ?) AND (accounts.deleted = ?) HAVING contactsOpportunities.amount > 1000
Parameters:
array (
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => closed
[6] => 0
)
Arguments
Name
Type
Required
Description
$sql
String
true
The HAVINGÂ statement, without the HAVINGÂ keyword.
Returns
SugarQuery Object
Allows for method chaining on the SugarQuery Object.Â
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Database/SugarQuery/Advanced_Techniques/index.html |
bea6643217df-0 | Subpanels
Overview
For Sidecar, Sugar's subpanel layouts have been modified to work as simplified metadata. This page is an overview of the metadata framework for subpanels.Â
The reason for this change is that previous versions of Sugar generated the metadata from various sources such as the SubPanelLayout and MetaDataManager classes. This eliminates the need for generating and processing the layouts and allows the metadata to be easily loaded to Sidecar.
Note:Â Modules running in backward compatibility mode do not use the Sidecar subpanel layouts as they use the legacy MVC framework.
Hierarchy Diagram
When loading the Sidecar subpanel layouts, the system processes the layout in the following manner:
Note: The Sugar application's client type is "base". For more information on the various client types, please refer to the User Interface page.
Subpanels and Subpanel Layouts
Sugar contains both a subpanels (plural) layout and a subpanel (singular) layout. The subpanels layout contains the collection of subpanels, whereas the subpanel layout renders the actual subpanel widget.
An example of a stock module's subpanels layout is:
./modules/Bugs/clients/base/layouts/subpanels/subpanels.php
<?php
$viewdefs['Bugs']['base']['layout']['subpanels'] = array (
'components' => array (
array (
'layout' => 'subpanel',
'label' => 'LBL_DOCUMENTS_SUBPANEL_TITLE',
'context' => array (
'link' => 'documents',
),
),
array (
'layout' => 'subpanel',
'label' => 'LBL_CONTACTS_SUBPANEL_TITLE',
'context' => array (
'link' => 'contacts',
),
),
array ( | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Subpanels/index.html |
bea6643217df-1 | 'link' => 'contacts',
),
),
array (
'layout' => 'subpanel',
'label' => 'LBL_ACCOUNTS_SUBPANEL_TITLE',
'context' => array (
'link' => 'accounts',
),
),
array (
'layout' => 'subpanel',
'label' => 'LBL_CASES_SUBPANEL_TITLE',
'context' => array (
'link' => 'cases',
),
),
),
'type' => 'subpanels',
'span' => 12,
);
You can see that the layout incorporates the use of the subpanel layout for each module. As most of the subpanel data is similar, this approach allows us to use less duplicate code. The subpanel layout, shown below, shows the three views that make up the subpanel widgets users see.
./clients/base/layouts/subpanel/subpanel.php
<?php
$viewdefs['base']['layout']['subpanel'] = array (
'components' => array (
array (
'view' => 'panel-top',
)
array (
'view' => 'subpanel-list',
),
array (
'view' => 'list-bottom',
),
),
'span' => 12,
'last_state' => array(
'id' => 'subpanel'
),
);
Adding Subpanel Layouts | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Subpanels/index.html |
bea6643217df-2 | ),
);
Adding Subpanel Layouts
When a new relationship is deployed from Studio, the relationship creation process will generate the layouts using the extension framework. You should note that for stock relationships and custom deployed relationships, layouts are generated for both Sidecar and Legacy MVC Subpanel formats. This is done to ensure that any related modules, whether in Sidecar or Backward Compatibility mode, display a related subpanel as expected.
Sidecar Layouts
Custom Sidecar layouts, located in ./custom/Extension/modules/<module>/Ext/clients/<client>/layouts/subpanels/, are compiled into ./custom/modules/<module>/Ext/clients/<client>/layouts/subpanels/subpanels.ext.php using the extension framework. When a relationship is saved, layout files are created for both the "base" and "mobile" client types.
For example, deploying a 1:M relationship from Bugs to Leads will generate the following Sidecar files:
./custom/Extension/modules/Bugs/Ext/clients/base/layouts/subpanels/bugs_leads_1_Bugs.php
<?php
$viewdefs['Bugs']['base']['layout']['subpanels']['components'][] = array (
'layout' => 'subpanel',
'label' => 'LBL_BUGS_LEADS_1_FROM_LEADS_TITLE',
'context' =>
array (
'link' => 'bugs_leads_1',
),
);
./custom/Extension/modules/Bugs/Ext/clients/mobile/layouts/subpanels/bugs_leads_1_Bugs.php
<?php
$viewdefs['Bugs']['mobile']['layout']['subpanels']['components'][] = array (
'layout' => 'subpanel',
'label' => 'LBL_BUGS_LEADS_1_FROM_LEADS_TITLE',
'context' =>
array (
'link' => 'bugs_leads_1',
), | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Subpanels/index.html |
bea6643217df-3 | array (
'link' => 'bugs_leads_1',
),
);
Note: The additional legacy MVC layouts generated by a relationships deployment are described below.
Legacy MVC Subpanel Layouts
Custom Legacy MVC Subpanel layouts, located in ./custom/Extension/modules/<module>/Ext/Layoutdefs/, are compiled into ./custom/modules/<module>/Ext/Layoutdefs/layoutdefs.ext.php using the extension framework. You should also note that when a relationship is saved, wireless layouts, located in ./custom/Extension/modules/<module>/Ext/WirelessLayoutdefs/, are created and compiled into ./custom/modules/<module>/Ext/Layoutdefs/layoutdefs.ext.php.
An example of this is when deploying a 1-M relationship from Bugs to Leads, the following layoutdef files are generated:
./custom/Extension/modules/Bugs/Ext/Layoutdefs/bugs_leads_1_Bugs.php
<?php
$layout_defs["Bugs"]["subpanel_setup"]['bugs_leads_1'] = array (
'order' => 100,
'module' => 'Leads',
'subpanel_name' => 'default',
'sort_order' => 'asc',
'sort_by' => 'id',
'title_key' => 'LBL_BUGS_LEADS_1_FROM_LEADS_TITLE',
'get_subpanel_data' => 'bugs_leads_1',
'top_buttons' =>
array (
0 =>
array (
'widget_class' => 'SubPanelTopButtonQuickCreate',
),
1 =>
array (
'widget_class' => 'SubPanelTopSelectButton',
'mode' => 'MultiSelect',
),
),
); | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Subpanels/index.html |
bea6643217df-4 | 'mode' => 'MultiSelect',
),
),
);
./custom/Extension/modules/Bugs/Ext/WirelessLayoutdefs/bugs_leads_1_Bugs.php
<?php
$layout_defs["Bugs"]["subpanel_setup"]['bugs_leads_1'] = array (
'order' => 100,
'module' => 'Leads',
'subpanel_name' => 'default',
'title_key' => 'LBL_BUGS_LEADS_1_FROM_LEADS_TITLE',
'get_subpanel_data' => 'bugs_leads_1',
);
Fields Metadata
Sidecar's subpanel field layouts are initially defined by the subpanel list-view metadata.
Hierarchy Diagram
The subpanel list metadata is loaded in the following manner:
Note: The Sugar application's client type is "base". For more information on the various client types, please refer to the User Interface page.
Subpanel List Views
By default, all modules come with a default set of subpanel fields for when they are rendered as a subpanel. An example of this is can be found in the Bugs module:
./modules/Bugs/clients/base/views/subpanel-list/subpanel-list.php
<?php
$subpanel_layout['list_fields'] = array (
'full_name' =>
array (
'type' => 'fullname',
'link' => true,
'studio' =>
array (
'listview' => false,
),
'vname' => 'LBL_NAME',
'width' => '10%',
'default' => true,
),
'date_entered' =>
array (
'type' => 'datetime',
'studio' =>
array ( | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Subpanels/index.html |
bea6643217df-5 | 'type' => 'datetime',
'studio' =>
array (
'portaleditview' => false,
),
'readonly' => true,
'vname' => 'LBL_DATE_ENTERED',
'width' => '10%',
'default' => true,
),
'refered_by' =>
array (
'vname' => 'LBL_LIST_REFERED_BY',
'width' => '10%',
'default' => true,
),
'lead_source' =>
array (
'vname' => 'LBL_LIST_LEAD_SOURCE',
'width' => '10%',
'default' => true,
),
'phone_work' =>
array (
'vname' => 'LBL_LIST_PHONE',
'width' => '10%',
'default' => true,
),
'lead_source_description' =>
array (
'name' => 'lead_source_description',
'vname' => 'LBL_LIST_LEAD_SOURCE_DESCRIPTION',
'width' => '10%',
'sortable' => false,
'default' => true,
),
'assigned_user_name' =>
array (
'name' => 'assigned_user_name',
'vname' => 'LBL_LIST_ASSIGNED_TO_NAME',
'widget_class' => 'SubPanelDetailViewLink',
'target_record_key' => 'assigned_user_id',
'target_module' => 'Employees',
'width' => '10%',
'default' => true,
),
'first_name' =>
array (
'usage' => 'query_only',
),
'last_name' => | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Subpanels/index.html |
bea6643217df-6 | 'usage' => 'query_only',
),
'last_name' =>
array (
'usage' => 'query_only',
),
'salutation' =>
array (
'name' => 'salutation',
'usage' => 'query_only',
),
);
To modify this layout, navigate to Admin > Studio > {Parent Module} > Subpanels > Bugs and make your changes. Once saved, Sugar will generate ./custom/modules/Bugs/clients/<client>/views/subpanel-for-<link>/subpanel-for-<link>.php which will be used for rendering the fields you selected.
You should note that, just as Sugar mimics the Sidecar layouts in the legacy MVC framework for modules in backward compatibility, it also mimics the field list in ./modules/<module>/metadata/subpanels/default.php and ./custom/modules/<module>/metadata/subpanels/default.php. This is done to ensure that any related modules, whether in Sidecar or Backward Compatibility mode, display the same field list as expected.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Subpanels/index.html |
4d892d78da0b-0 | Models
Overview
Each module in Sugar is extending the Sugar Model. This model is determined by the SugarBean, which contains methods to create, read/retrieve, update, and delete records in the database and any subclass of the SugarBean. Many of the common Sugar modules also use the SugarObjects class, which is explained in the next section.
SugarObject Templates
Sugar objects extend the concept of subclassing a step further and allow you to subclass the vardefs. This includes inheriting of fields, relationships, indexes, and language files. However, unlike subclassing, you are not limited to a single inheritance. For example, if there were a Sugar object for fields used in every module (e.g. id, deleted, or date_modified), you could have the module inherit from both the Basic Sugar object and the Person Sugar object.
To further illustrate this, let's say the Basic object type has a field 'name' with length 10 and the Company object has a field 'name' with length 20. If you inherit from Basic first and then Company, your field will inherit the Company object's length of 20. However, the module-level setting always overrides any values provided by Sugar objects, so, if the field 'name' in your module has been set to length 60, then the field's length will ultimately be 60.
There are six types of SugarObject templates:
Basic : Contains the basic fields required by all Sugar modules
Person : Based on the Contacts, Prospects, and Leads modules
Issue : Based on the Bugs and Cases modules
Company : Based on the Accounts module
File : Based on the Documents module
Sale : Based on the Opportunities module
SugarObject Interfaces | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/index.html |
4d892d78da0b-1 | File : Based on the Documents module
Sale : Based on the Opportunities module
SugarObject Interfaces
In addition to the object templates above, "assignable" object templates can be used for modules with records that should contain an Assigned To field. Although every module does not use this, most modules allow assignment of records to users. SugarObject interfaces allow us to add the assignable attribute to these modules.
SugarObject interfaces and SugarObject templates are very similar to one another, but the main distinction is that templates have a base class you can subclass while interfaces do not. If you look into the file structure, templates include many additional files, including a full metadata directory. This is used primarily for Module Builder.
File Structure
./include/SugarObjects/interfaces
./include/SugarObjects/templates
Implementation
There are two things you need to do to take advantage of Sugar objects:
Subclass the SugarObject class you wish to extend for your class:class MyClass extends Person
{
function MyClass()
{
parent::Person();
}
}
Add the following line to the end of the vardefs.php file:VardefManager::createVardef('Contacts', 'Contact', array('default', 'assignable', 'team_security', 'person'));
This snippet tells the VardefManager to create a cache of the Contacts vardefs with the addition of all the default fields, assignable fields, team security fields, and all fields from the person class.
Performance Considerations
VardefManager caches the generated vardefs into a single file that is loaded at runtime. If that file is not found, Sugar loads the vardefs.php file, located in your module's directory. The same is true for language files. This caching also includes data for custom fields and any vardef or language extensions that are dropped into the extension framework.
Cache Files | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/index.html |
4d892d78da0b-2 | Cache Files
./cache/modules/<module>/<object_name>vardefs.php
./cache/modules/<module>/languages/en_us.lang.php
TopicsSugarBean$bean = BeanFactory::retrieveBean($module, $id);BeanFactoryThe BeanFactory class, located in ./data/BeanFactory.php, is used for loading an instance of a SugarBean. This class should be used any time you are creating or retrieving bean objects. It will automatically handle any classes required for the bean.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/index.html |
de30369e5c75-0 | SugarBean
//Retrieve bean
$bean = BeanFactory::retrieveBean($module, $id);
//Set deleted to true
$bean->mark_deleted($bean->id);
//Save
$bean->save();
Overview
The SugarBean class supports all the model operations to and from the database. Any module that interacts with the database utilizes the SugarBean class, which contains methods to create, read/retrieve, update, and delete records in the database (CRUD), as well as fetch related records.
CRUD Handling
The SugarBean handles the most basic functions of the Sugar database, allowing you to create, retrieve, update, and delete data.Â
Creating and Retrieving Records
The BeanFactory class is used for bean loading. The class should be used whenever you are creating or retrieving bean objects. It will automatically handle any classes required for the bean. More information on this can be found in the BeanFactory section.
Obtaining the Id of a Recently Saved Bean
For new records, a GUID is generated and assigned to the record id field. Saving new or existing records returns a single value to the calling routine, which is the id attribute of the saved record. The id has the following format:
aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
You can retrieve a newly created record's id with the following:
//Create bean
$bean = BeanFactory::newBean($module);
//Populate bean fields
$bean->name = 'Example Record';
//Save
$bean->save();
//Retrieve the bean id
$record_id = $bean->id;
Saving a Bean with a Specific ID | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/index.html |
de30369e5c75-1 | $record_id = $bean->id;
Saving a Bean with a Specific ID
Saving a record with a specific id requires the id and new_with_id attribute of the bean to be set. When doing so, it is important that you use a globally unique identifier. Failing to do so may result in unexpected behavior in the system. An example setting an id is shown below:
//Create bean
$bean = BeanFactory::newBean($module);
//set the new flag
$bean->new_with_id = true;
//Set the record id with a static id
$id = '38c90c70-7788-13a2-668d-513e2b8df5e1';
$bean->id = $id;
//or have the system generate an id for you
//$id = Sugarcrm\Sugarcrm\Util\Uuid::uuid1()
//$bean->id = $id;
//Populate bean fields
$bean->name = 'Example Record';
//Save
$bean->save();
Setting new_with_id to true prevents the save method from creating a new id value and uses the assigned id attribute. If the id attribute is empty and the new_with_id attribute is set to true, the save will fail. If you would like for the system to generate an id for you, you can use Sugarcrm\Sugarcrm\Util\Uuid::uuid1().
Distinguishing New from Existing Records
To identify whether or not a record is new or existing, you can check the fetched_rows property. If the $bean has a fetched_row, it was loaded from the database. An example is shown below:
if (!isset($bean->fetched_row['id'])) {
//new record
} else {
//existing record
} | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/index.html |
de30369e5c75-2 | //new record
} else {
//existing record
}
If you are working with a logic hook such as before_save or after_save, you should check the arguments.isUpdate property to determine this as shown below:
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class logic_hooks_class
{
function hook_method($bean, $event, $arguments)
{
if (isset($arguments['isUpdate']) && $arguments['isUpdate'] == false) {
//new record
} else {
//existing record
}
}
}
?>
Retrieving a Bean by Unique Field
Sometimes developers have a need to fetch a record based on a unique field other than the id. In previous versions you were able to use the retrieve_by_string_fields() method to accomplish this, however, that has now been deprecated. To search and fetch records, you should use the SugarQuery builder. An example of this is shown below:
require_once('include/SugarQuery/SugarQuery.php');
$sugarQuery = new SugarQuery();
//fetch the bean of the module to query
$bean = BeanFactory::newBean('<modules>');
//create first query
$sql = new SugarQuery();
$sql->select('id');
$sql->from($bean);
$sql->Where()->equals('<field>', '<unique value>');
$result = $sql->execute();
$count = count($result);
if ($count == 0) {
//no results were found
} elseif ($count == 1) {
//one result was found
$bean = BeanFactory::getBean('<module>', $result[0]['id']);
} else {
//multiple results were found
} | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/index.html |
de30369e5c75-3 | } else {
//multiple results were found
}
Updating a Bean
You can update a bean by fetching a record and then updating the property:
//Retrieve bean
$bean = BeanFactory::retrieveBean($module, $id);
//Fields to update
$bean->name = 'Updated Name';
//Save
$bean->save();
Note: Disabling row-level security when accessing a bean should be set to true only when it is absolutely necessary to bypass security, for example, when updating a Lead record from a custom Entry Point. An example of accessing the bean while bypassing row security is:
$bean = BeanFactory::retrieveBean($module, $record_id, array('disable_row_level_security' => true));
Updating a Bean Without Changing the Date Modified
The SugarBean class contains an attribute called update_date_modified, which is set to true when the class is instantiated and means that the date_modified attribute is updated to the current database date timestamp. Setting update_date_modified to false would result in the date_modified attribute not being set with the current database date timestamp.
//Retrieve bean
$bean = BeanFactory::retrieveBean($module, $id);
//Set modified flag
$bean->update_date_modified = false;
//Fields to update
$bean->name = 'Updated Name';
//Save
$bean->save();
Note: Disabling row-level security when accessing a bean should be set to true only when it is absolutely necessary to bypass security, for example, when updating a Lead record from a custom Entry Point. An example of accessing the bean while bypassing row security is:
$bean = BeanFactory::retrieveBean($module, $record_id, array('disable_row_level_security' => true));
Deleting a Bean | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/index.html |
de30369e5c75-4 | Deleting a Bean
Deleting a bean can be done by fetching it then calling the mark_deleted() method which makes sure any relationships with related records are removed as well:
//Retrieve bean
$bean = BeanFactory::retrieveBean($module, $id);
//Set deleted to true
$bean->mark_deleted($id);
//Save
$bean->save();
Note: Disabling row-level security when accessing a bean should be set to true only when it is absolutely necessary to bypass security, for example, when updating a Lead record from a custom Entry Point. An example of accessing the bean while bypassing row security is:
$bean = BeanFactory::retrieveBean($module, $record_id, array('disable_row_level_security' => true));
Fetching Relationships
This section explains how the SugarBean class can be used to fetch related information from the database.
Fetching Related Records
To fetch related records, load the relationship using the link:
//If relationship is loaded
if ($bean->load_relationship($link)) {
//Fetch related beans
$relatedBeans = $bean->$link->getBeans();
}
An example of this is to load the contacts related to an account:
//Load Account
$bean = BeanFactory::getBean('Accounts', $id);
//If relationship is loaded
if ($bean->load_relationship('contacts')) {
//Fetch related beans
$relatedBeans = $bean->contacts->getBeans();
}
Fetching Related Record IDs
To fetch only related record IDs, load the relationship using the link:
//If relationship is loaded
if ($bean->load_relationship($link)) {
//Fetch related record IDs
$relatedBeans = $bean->$link->get();
} | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/index.html |
de30369e5c75-5 | $relatedBeans = $bean->$link->get();
}
An example of this is to load the record IDs of contacts related to an account:
//Load Account
$bean = BeanFactory::getBean('Accounts', $id);
//If relationship is loaded
if ($bean->load_relationship('contacts')) {
//Fetch related beans
$relatedBeans = $bean->contacts->get();
}
Fetching a Parent Record
Fetching a parent record is similar to fetching child records in that you will still need to load the relationship using the link:
//If relationship is loaded
if ($bean->load_relationship($link)) {
//Fetch related beans
$relatedBeans = $bean->$link->getBeans();
$parentBean = false;
if (!empty($relatedBeans)) {
//order the results
reset($relatedBeans);
//first record in the list is the parent
$parentBean = current($relatedBeans);
}
}
An example of this is to load a contact and fetch its parent account:
//Load Contact
$bean = BeanFactory::getBean('Contacts', $id);
//If relationship is loaded
if ($bean->load_relationship('accounts')) {
//Fetch related beans
$relatedBeans = $bean->accounts->getBeans();
$parentBean = false;
if (!empty($relatedBeans)) {
//order the results
reset($relatedBeans);
//first record in the list is the parent
$parentBean = current($relatedBeans);
}
} | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/index.html |
de30369e5c75-6 | $parentBean = current($relatedBeans);
}
}
TopicsCustomizing Core SugarBeansThis article covers how to extend core SugarBean objects to implement custom code. This can be used to alter the stock assignment notification message or to add logic to change the default modules behavior.Implementing Custom SugarBean TemplatesThis article covers how to implement custom SugarBean templates, which can then be extended by custom modules. It also covers vardef templates, which can more portable and used by multiple modules. By default, Sugar comes with a few templates such as Company, Person, Issue, and File templates.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/index.html |
940b70070615-0 | Customizing Core SugarBeans
Overview
This article covers how to extend core SugarBean objects to implement custom code. This can be used to alter the stock assignment notification message or to add logic to change the default modules behavior.
Customizing a Core Module
The best approach to customizing a core SugarBean object is to become familiar with how the core Bean operates and only modify the bean logic where absolutely necessary. After understanding where you wish to make your customization in the module Bean class, you can extend the class in the custom directory. In order to avoid duplicating code from the core Bean class, it is always best to extend the class rather than duplicate the class to the custom directory.Â
Extending the SugarBean
For this example, we will look at modifying the Leads SugarBean object. To extend the core Leads bean, create the following file:
./custom/modules/Leads/CustomLead.php
<?php
require_once 'modules/Leads/Lead.php';
class CustomLead extends Lead
{
/**
* Saves the record
* - You can use this method to implement before save or after save logic
*
* @param bool $check_notify
* @return string
*/
function save($check_notify = FALSE)
{
$id = parent::save($check_notify);
return $id;
}
/**
* Retrieves a record
* - You can use this method to set properties when fetching a bean
*
* @param string $id
* @param bool $encode
* @param bool $deleted
* @return $this
*/
function retrieve($id = '-1', $encode = true, $deleted = true)
{
return parent::retrieve($id, $encode, $deleted);
} | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Customizing_Core_SugarBeans/index.html |
940b70070615-1 | return parent::retrieve($id, $encode, $deleted);
}
/**
* Calls custom logic events
* - You can use this method to watch for specific logic hook events
*
* @param $event
* @param array $arguments
*/
function call_custom_logic($event, $arguments = array())
{
parent::call_custom_logic($event, $arguments);
}
}
Register the Custom Class
Once the custom SugarBean class file has been created, register that class to be used by the module so that the BeanFactory knows which class to use. To register the class you will create the following file in the ./custom/Extension/ directory:
./custom/Extension/application/Ext/Include/customLead.php
<?php
/**
* The $objectList array, maps the module name to the Vardef property
* By default only a few core modules have this defined, since their Class/Object names differs from their Vardef Property
**/
$objectList['Leads'] = 'Lead';
// $beanList maps the Bean/Module name to the Class name
$beanList['Leads'] = 'CustomLead';
// $beanFiles maps the Class name to the PHP Class file
$beanFiles['CustomLead'] = 'custom/modules/Leads/CustomLead.php';
Note: The $objectList array only needs to be set on those modules that do not have it set already. You can view ./include/modules.php to see the core modules that have it defined already.
Once the registration file is in place, go to Admin > Repairs, and run a Quick Repair and Rebuild so that the system starts using the custom class.
Things to Note
Overriding a core SugarBean class comes with some caveats: | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Customizing_Core_SugarBeans/index.html |
940b70070615-2 | Things to Note
Overriding a core SugarBean class comes with some caveats:
The custom class is only used when the product core code uses the BeanFactory.Â
For most circumstances, Sugar is set up to use BeanFactory, however, legacy code or specific logic that is pairs core modules together may use direct calls to a core SugarBean class, which would then cause the custom class to not be used. In those scenarios, it is recommended to use a logic look instead.
Extending the Cases module doesn't affect the email Import process.
If the $objectList property is not defined for the module, the custom object will be used, however, things like Studio will no longer work correctly.
For the example above, we defined the $objectList property for the Leads module to make sure that Studio continued working as expected. Without this definition, if you navigate to Admin > Studio, fields and relationships will not render properly.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Customizing_Core_SugarBeans/index.html |
8964a443506b-0 | Implementing Custom SugarBean Templates
Overview
This article covers how to implement custom SugarBean templates, which can then be extended by custom modules. It also covers vardef templates, which can more portable and used by multiple modules. By default, Sugar comes with a few templates such as Company, Person, Issue, and File templates.
Creating a Custom SugarBean Template
The following example will create a custom Bean template that can be used by custom modules to shrink down the overall size of the Bean model, by only implementing the two fields required by all modules, the id field and the deleted field. In order to do this, we will have to override some core SugarBean methods, as the base SugarBean is statically configured to do things like Save/Delete the model with the date_entered, date_modified, modified_user_id and created_user_id fields. In order to accommodate custom Beans that wish to use those fields, this template will also have properties for configuring those types of fields so that they are populated using the default SugarBean logic.
To create a template for use by custom modules, you create a class that extends from SugarBean in ./custom/include/SugarObjects/templates/<template_name>/<class_name>.php. For this example, we will create the "bare" template with the following file:
./custom/include/SugarObjects/templates/bare/BareBean.php
<?php
class BareBean extends SugarBean
{
/**
* The configured modified date field
* @var string|false
*/
protected $_modified_date_field = false;
/**
* The configured modified user field
* @var string|false
*/
protected $_modified_user_field = false;
/**
* The configured created date field
* @var string|false
*/
protected $_created_date_field = false;
/**
* The configured created user field | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-1 | /**
* The configured created user field
* @var string|false
*/
protected $_created_user_field = false;
/**
* Get the field name where modified date is stored, if in use by Module
* @return string|false
*/
public function getModifiedDateField()
{
if ($this->_modified_date_field !== FALSE){
$field = $this->_modified_date_field;
if (isset($this->field_defs[$field]) && $this->field_defs[$field]['type'] == 'datetime'){
return $field;
}
}
return FALSE;
}
/**
* Override the stock setModifiedDate method
* - Check that field is in use by this Module
* - If in use, set the configured field to current time
* @inheritdoc
**/
public function setModifiedDate($date = '')
{
global $timedate;
$field = $this->getModifiedDateField();
if ($field !== FALSE){
// This code was duplicated from the stock SugarBean::setModifiedDate
if ($this->update_date_modified || empty($this->$field)) {
// This only needs to be calculated if it is going to be used
if (empty($date)) {
$date = $timedate->nowDb();
}
$this->$field = $date;
}
}
}
/**
* Get the field name where modified user ID is stored, if in use by Module
* @return string|false
**/
public function getModifiedUserField()
{
if ($this->_modified_user_field !== FALSE){ | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-2 | {
if ($this->_modified_user_field !== FALSE){
$field = $this->_modified_user_field;
if (isset($this->field_defs[$field]) && $this->field_defs[$field]['type'] == 'assigned_user_name'){
return $field;
}
}
return FALSE;
}
/**
* Override the stock setModifiedUser Method
* - Check that field is in use by this Module
* - If in use, set the configured field to user_id
* @inheritdoc
* @param User|null $user [description]
*/
public function setModifiedUser(User $user = null)
{
global $current_user;
$field = $this->getModifiedUserField();
if ($field !== FALSE){
// If the update date modified by flag is set then carry out this directive
if ($this->update_modified_by) {
// Default the modified user id to the default
$this->$field = 1;
// If a user was not presented, default to the current user
if (empty($user)) {
$user = $current_user;
}
// If the user is set, use it
if (!empty($user)) {
$this->$field = $user->id;
}
}
}
}
/**
* Get the field name where created date is stored, if in use by Module
* @return string|false
*/
public function getCreatedDateField()
{
if ($this->_created_date_field !== FALSE){
$field = $this->_created_date_field; | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-3 | $field = $this->_created_date_field;
if (isset($this->field_defs[$field]) && $this->field_defs[$field]['type'] == 'datetime'){
return $field;
}
}
return FALSE;
}
/**
* Get the field name where created user ID is stored, if in use by Module
* @return string|false
*/
public function getCreatedUserField()
{
if ($this->_created_user_field !== FALSE){
$field = $this->_created_user_field;
if (isset($this->field_defs[$field]) && $this->field_defs[$field]['type'] == 'assigned_user_name'){
return $field;
}
}
return FALSE;
}
/**
* Override the stock setCreateData method
* - Code was duplicated from stock, to accommodate not having created date or created user fields
* @inheritdoc
*/
public function setCreateData($isUpdate, User $user = null)
{
if (!$isUpdate) {
global $current_user;
$field = $this->getCreatedDateField();
if ($field !== FALSE){
//Duplicated from SugarBean::setCreateData with modifications for dynamic field name
if (empty($this->$field)) {
$this->$field = $this->getDateModified();
}
if (empty($this->$field)){
global $timedate;
$this->$field = $timedate->nowDb();
}
}
$field = $this->getCreatedUserField();
if ($field !== FALSE){
//Duplicated from SugarBean::setCreateData with modifications for dynamic field name | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-4 | //Duplicated from SugarBean::setCreateData with modifications for dynamic field name
if ($this->set_created_by == true) {
// created by should always be this user
// unless it was set outside of the bean
if ($user) {
$this->$field = $user->id;
} else {
$this->$field = isset($current_user) ? $current_user->id : "";
}
}
}
if ($this->new_with_id == false) {
$this->id = Sugarcrm\Sugarcrm\Util\Uuid::uuid1();
}
}
}
/**
* Get the Date Modified fields value
* @return mixed|false
*/
public function getDateModified()
{
if ($this->_modified_date_field !== FALSE){
$field = $this->_modified_date_field;
return $this->$field;
}
return FALSE;
}
/**
* Get the Date Created Fields value
* @return mixed|false
*/
public function getDateCreated()
{
if ($this->_created_date_field !== FALSE){
$field = $this->_created_date_field;
return $this->$field;
}
return FALSE;
}
/**
* @inheritdoc
*/
public function mark_deleted($id)
{
$date_modified = $GLOBALS['timedate']->nowDb();
if (isset($_SESSION['show_deleted'])) {
$this->mark_undeleted($id);
} else {
// Ensure that Activity Messages do not occur in the context of a Delete action (e.g. unlink) | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-5 | // and do so for all nested calls within the Top Level Delete Context
$opflag = static::enterOperation('delete');
$aflag = Activity::isEnabled();
Activity::disable();
// call the custom business logic
$custom_logic_arguments['id'] = $id;
$this->call_custom_logic("before_delete", $custom_logic_arguments);
$this->deleted = 1;
if (isset($this->field_defs['team_id'])) {
if (empty($this->teams)) {
$this->load_relationship('teams');
}
if (!empty($this->teams)) {
$this->teams->removeTeamSetModule();
}
}
$this->mark_relationships_deleted($id);
$updateFields = array('deleted' => 1);
$field = $this->getModifiedDateField();
if ($field !== FALSE){
$this->setModifiedDate();
$updateFields[$field] = $this->$field;
}
$field = $this->getModifiedUserField();
if ($field !== FALSE){
$this->setModifiedUser();
$updateFields[$field] = $this->$field;
}
$this->db->updateParams(
$this->table_name,
$this->field_defs,
$updateFields,
array('id' => $id)
);
if ($this->isFavoritesEnabled()) {
SugarFavorites::markRecordDeletedInFavorites($id, $date_modified);
}
// Take the item off the recently viewed lists
$tracker = BeanFactory::newBean('Trackers');
$tracker->makeInvisibleForAll($id); | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-6 | $tracker->makeInvisibleForAll($id);
SugarRelationship::resaveRelatedBeans();
// call the custom business logic
$this->call_custom_logic("after_delete", $custom_logic_arguments);
if(static::leaveOperation('delete', $opflag) && $aflag) {
Activity::enable();
}
}
}
/**
* @inheritdoc
*/
public function mark_undeleted($id)
{
// call the custom business logic
$custom_logic_arguments['id'] = $id;
$this->call_custom_logic("before_restore", $custom_logic_arguments);
$this->deleted = 0;
$modified_date_field = $this->getModifiedDateField();
if ($modified_date_field !== FALSE){
$this->setModifiedDate();
}
$query = "UPDATE {$this->table_name} SET deleted = ?".(!$modified_date_field?"":",$modified_date_field = ?")." WHERE id = ?";
$conn = $this->db->getConnection();
$params = array($this->deleted);
if ($modified_date_field){
$params[] = $this->$modified_date_field;
}
$params[] = $id;
$conn->executeQuery($query, $params);
// call the custom business logic
$this->call_custom_logic("after_restore", $custom_logic_arguments);
}
}
With the Bean template in place, we can define the default vardefs for the template by creating the following file:
./custom/include/SugarObjects/templates/bare/vardefs.php
<?php
$vardefs = array(
'audited' => false,
'favorites' => false,
'activity_enabled' => false, | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-7 | 'favorites' => false,
'activity_enabled' => false,
'fields' => array(
'id' => array(
'name' => 'id',
'vname' => 'LBL_ID',
'type' => 'id',
'required' => true,
'reportable' => true,
'duplicate_on_record_copy' => 'no',
'comment' => 'Unique identifier',
'mandatory_fetch' => true,
),
'deleted' => array(
'name' => 'deleted',
'vname' => 'LBL_DELETED',
'type' => 'bool',
'default' => '0',
'reportable' => false,
'duplicate_on_record_copy' => 'no',
'comment' => 'Record deletion indicator'
)
),
'indices' => array(
'id' => array(
'name' => 'idx_' . preg_replace('/[^a-z0-9_\-]/i', '', strtolower($module)) . '_pk',
'type' => 'primary',
'fields' => array('id')
),
'deleted' => array(
'name' => 'idx_' . strtolower($table_name) . '_id_del',
'type' => 'index',
'fields' => array('id', 'deleted')
)
),
'duplicate_check' => array(
'enabled' => false
)
);
Note: This vardef template also shrinks the SugarBean template down even further, by defaulting auditing, favorites, and activity stream to false.
Using a Custom Bean Template | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-8 | Using a Custom Bean Template
With the custom SugarBean template in place, we can now implement the template on a custom module. Typically if you deployed a module from Module Builder, there would be two classes generated by Sugar, "custom_Module_sugar" and "custom_Module". The "_sugar" generated class extends from the Bean template that was selected in Module Builder, and the primary Bean class is what is utilized in the system and where your development would take place. For the above example template that is created, the assumption is that you are writing the Bean class, rather than using the generated classes by Module Builder, or at the very least removing the intermediary "_sugar" class generated by Module Builder and extending from the desired template. If you deployed a module via Module Builder, and are going to switch to a custom template, please note that some of the stock templates contain internal logic for the setup of fields for that template and that would need to be duplicated if you intend to continue using those fields. The stock templates, located in ./include/SugarObjects/templates/, are available for your reference to copy over any of the required logic to your custom Bean class. With all that being said, let us take a look at a custom Bean class that extends from our custom template.
This example will use the "custom_Module" module which is a module that will be used for Tagging records. Since the module is just storing tags, a slimmed down Bean works well as we only need a "name" field to store those tags. The following class would implement the custom Bean template created above.
./modules/custom_Module/custom_Module.php
<?php
require_once 'custom/include/SugarObjects/templates/bare/BareBean.php';
class custom_Module extends BareBean {
public $new_schema = true;
public $module_dir = 'custom_Module';
public $object_name = 'custom_Module'; | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-9 | public $object_name = 'custom_Module';
public $table_name = 'custom_Module';
public $importable = true;
public $id;
public $name;
public $deleted;
public function __construct(){
parent::__construct();
}
public function bean_implements($interface){
switch($interface){
case 'ACL': return true;
}
return false;
}
}
With the modules SugarBean class created, the other thing that needs to be implemented is the vardefs.php file:
./modules/custom_Module/vardefs.php
<?php
$module = 'custom_Module';
$table_name = strtolower($module);
$dictionary[$module] = array(
'table' => $table_name,
'fields' => array(
'name' => array(
'name' => 'name',
'vname' => 'LBL_NAME',
'type' => 'username',
'link' => true,
'dbType' => 'varchar',
'len' => 255,
'unified_search' => true,
'full_text_search' => array(),
'required' => true,
'importable' => 'required',
'duplicate_merge' => 'enabled',
//'duplicate_merge_dom_value' => '3',
'merge_filter' => 'selected',
'duplicate_on_record_copy' => 'always',
),
),
'relationships' => array (
),
'optimistic_locking' => false,
'unified_search' => false,
);
VardefManager::createVardef(
$module,
$module, | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-10 | VardefManager::createVardef(
$module,
$module,
//Specify the bare template to be used to create the vardefs
array('bare')
);
With these files implemented, the "custom_Module" module would implement the "bare" template we created.
Creating Custom Vardef Templates
For some customizations, you might not need a SugarBean template as you may not be implementing logic that needs to be shared across multiple module's Bean classes. However, you may have field definitions that are common across multiple modules that would be beneficial for implementing as Vardef Templates. To create a vardef template, a file as follows, ./custom/include/SugarObjects/implements/<template_name>/vardefs.php.
Continuing on with our example custom_Module module from above, we might want to have a creation date on this custom tags module since our 'bare' SugarBean template does not come with one by default. We could easily just add one in the modules vardef file, but for our example purposes, we know that we will use our 'bare' SugarBean template on other customizations, and on some of those we might also want to include a creation date. To implement the vardef template for the creation date field, we create the following:
./custom/include/SugarObjects/implements/date_entered/vardefs.php
<?php
$vardefs = array(
'fields' => array(
'date_entered' => array(
'name' => 'date_entered',
'vname' => 'LBL_DATE_ENTERED',
'type' => 'datetime',
'group' => 'created_by_name',
'comment' => 'Date record created',
'enable_range_search' => true,
'options' => 'date_range_search_dom',
'studio' => array( | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-11 | 'options' => 'date_range_search_dom',
'studio' => array(
'portaleditview' => false,
),
'duplicate_on_record_copy' => 'no',
'readonly' => true,
'massupdate' => false,
'full_text_search' => array(
'enabled' => true,
'searchable' => false
),
)
),
'indices' => array(
'date_entered' => array(
'name' => 'idx_' . strtolower($table_name) . '_date_entered',
'type' => 'index',
'fields' => array('date_entered')
)
)
);
Using a Custom Vardef Template
Once the vardef template is in place, you can use the template by adding it to the 'uses' array property of your module vardefs. Continuing with our example module custom_Module, we can update the vardefs file as follows:
./modules/custom_Module/vardefs.php
<?php
$module = 'custom_Module';
$table_name = strtolower($module);
$dictionary[$module] = array(
'table' => $table_name,
'fields' => array(
'name' => array(
'name' => 'name',
'vname' => 'LBL_NAME',
'type' => 'username',
'link' => true,
'dbType' => 'varchar',
'len' => 255,
'unified_search' => true,
'full_text_search' => array(),
'required' => true,
'importable' => 'required',
'duplicate_merge' => 'enabled',
//'duplicate_merge_dom_value' => '3', | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
8964a443506b-12 | //'duplicate_merge_dom_value' => '3',
'merge_filter' => 'selected',
'duplicate_on_record_copy' => 'always',
),
),
'relationships' => array (
),
//Add the desired vardef templates to this list
'uses' => array(
'date_entered'
),
'optimistic_locking' => false,
'unified_search' => false,
);
VardefManager::createVardef(
$module,
$module,
//Specify the bare template to be used to create the vardefs
array('bare')
);
After a Quick Repair and Rebuild, a SQL statement should be generated to update the table of the module with the new date_entered field that was added to the vardefs using the vardef template.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/SugarBean/Implementing_Custom_SugarBean_Templates/index.html |
e62207531ec6-0 | BeanFactory
Overview
The BeanFactory class, located in ./data/BeanFactory.php, is used for loading an instance of a SugarBean. This class should be used any time you are creating or retrieving bean objects. It will automatically handle any classes required for the bean.
Creating a SugarBean Object
newBean()
To create a new, empty SugarBean, use the newBean() method. This method is typically used when creating a new record for a module or to call properties of the module's bean object.
$bean = BeanFactory::newBean($module);
newBeanByName()
Used to fetch a bean by its beanList name.
$bean = BeanFactory::newBeanByName($name);
Retrieving a SugarBean Object
getBean()
The getBean() method can be used to retrieve a specific record from the database. If a record id is not passed, a new bean object will be created.
$bean = BeanFactory::getBean($module, $record_id);
Note: Disabling row-level security when accessing a bean should be set to true only when it is absolutely necessary to bypass security, for example when updating a Lead record from a custom Entry Point. An example of accessing the bean while bypassing row security is:
$bean = BeanFactory::getBean($module, $record_id, array('disable_row_level_security' => true));
retrieveBean()
The retrieveBean() method can also be used to retrieve a specific record from the database. The difference between this method and getBean() is that null will be returned instead of an empty bean object if the retrieve fails.
$bean = BeanFactory::retrieveBean($module, $record_id); | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/BeanFactory/index.html |
e62207531ec6-1 | $bean = BeanFactory::retrieveBean($module, $record_id);
Note: Disabling row-level security when accessing a bean should be set to true only when it is absolutely necessary to bypass security, for example, when updating a Lead record from a custom Entry Point. An example of accessing the bean while bypassing row security is:
$bean = BeanFactory::retrieveBean($module, $record_id, array('disable_row_level_security' => true));
Retrieving Module Keys
getObjectName()
The getObjectName() method will return the object name / dictionary key for a given module. This is normally the same as the bean name, but may not be for some modules such as Cases which has a key of 'aCase' and a name of 'Case'.
$moduleKey = BeanFactory::getObjectName($moduleName);
getBeanName()
The getBeanName() method will retrieve the bean class name given a module name.
$moduleClass = BeanFactory::getBeanName($module);
Â
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Models/BeanFactory/index.html |
ceaaded7b31f-0 | Vardefs
Overview
Vardefs (Variable Definitions) provide the Sugar application with information about SugarBeans. Vardefs specify information on the individual fields, relationships between beans, and the indexes for a given bean.Â
Each module that contains a SugarBean file has a vardefs.php file located in it, which specifies the fields for that SugarBean. For example, the vardefs for the Contact bean are located in ./modules/Contacts/vardefs.php.
Dictionary Array
Vardef files create an array called $dictionary, which contains several entries including tables, fields, indices, and relationships.
table : The name of the database table (usually, the name of the module) for this bean that contains the fields
audited : Specifies whether the module has field-level auditing enabled
duplicate_check : Determines if duplicate checking is enabled on the module, and what duplicate check strategy will be used if enabled.Â
fields : A list of fields and their attributes
indices : A list of indexes that should be created in the database
optimistic_locking : Determines whether the module has optimistic locking enabled
Optimistic locking prevents loss of data by using the bean's modified date to ensure that it is not being modified simultaneously by more than one person or process.
unified_search : Determines whether the module can be searched via Global Search This setting defaults to false and has no effect if all of the fields in the fields array have the 'unified_search' field attribute set to false.
unified_search_default_enabled : Determines whether the module should be searched by default for new users via Global Search
This setting defaults to true but has no effect if unified_search is set to false.
visibility : A list of visibility classes enabled on the module
Duplicate Check Array | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/index.html |
ceaaded7b31f-1 | visibility : A list of visibility classes enabled on the module
Duplicate Check Array
The duplicate_check array contains two properties, that control if duplicate checking is enabled on the module, and which duplicate check strategy will be used to check for duplicates.
The two properties for the array are as follows:
Name
Type
Description
enabled
Boolean
Specifies whether or not the Bean is utilizing the duplicate check framework
<class_name>
Array
<class_name> is the name of the duplicate check strategy class that is handling the duplicate checking. It is set to an array of Metadata, specific to the strategy defined in the key. Review the Duplicate Check Framework for further information.
Fields Array
The fields array contains one array for each field in the SugarBean. At the top level of this array, the key is the name of the field, and the value is an array of attributes about that field.
The list of possible attributes are as follows:
name : The name of the field
vname : The language pack ID for the label of this field
type : The type of the attribute
assigned_user_name : A linked user name
bool : A boolean value
char : A character array
date : A date value with no time
datetime : A date and time
email : An email address field
enum : An enumeration (dropdown list from the language pack)
id : A database GUID
image : A photo-type field
link : A link through an explicit relationship. This attribute should only be used when working with related fields. It does not make the field render as a link.
name : A non-database field type that concatenates other field values
phone : A phone number field to utilize with callto:// links
relate : Related bean
team_list : A team-based ID
text : A text area field
url : A hyperlinked field on the detail view
varchar : A variable-sized string | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/index.html |
ceaaded7b31f-2 | url : A hyperlinked field on the detail view
varchar : A variable-sized string
table : The database table the field comes from.
The table attribute is only needed to join fields from another table outside of the module in focus.
isnull : Whether the field can contain a null value
len : The length of the field (number of characters if a string)
options : The name of the enumeration (dropdown list) in the language pack for the field
dbtype : The database type of the field (if different than the type)
reportable : Determines whether the field will be available in the Reports and Workflow modules
default : The default value for this field. Default values for the record are populated by default on create for the record view (for Sidecar modules) and edit view (for Legacy modules) layout but can be modified by users. The Default Value option is available for all data type fields except HTML, Image, Flex Relate, and Relate.
massupdate : Determines whether the field will show up in the mass-update panel on its module's list view
Some field types are restricted from mass update regardless of this setting.
rname : For relate-type fields, the field from the related variable that contains the text
id_name : For relate-type fields, the field from the bean that stores the ID for the related bean
source : Set to 'non-db' if the field value does not come from the database
The source attribute can be used for calculated values or values retrieved in some other way.
sort_on : The field to sort by if multiple fields are used in the presentation of field's information
fields : For concatenated values, an array containing the fields that are concatenated
db_concat_fields : For concatenated values, an array containing the fields to concatenate in the database
unified_search : Determines whether the field can be searched via Global Search | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/index.html |
ceaaded7b31f-3 | unified_search : Determines whether the field can be searched via Global Search
This has no effect if the dictionary array setting 'unified_search' is not set to true.
enable_range_search : For date, datetime, and numeric fields, determines if this field should be searchable by range in module searches
dependency : Allows a field to have a predefined formula to control the field's visibility
studio : Controls the visibility of the field in the Studio editor
If set to false, then the field will not appear in any studio screens for the module. Otherwise, you may specify an Array of view keys from which the field's visibility should be removed (e.g. array('listview'=>false) will hide the field in the listview layout screen).
The following example illustrates a standard ID field for a bean:
'id' => array (
'name' => 'id',
'vname' => 'LBL_ID',
'type' => 'id',
'required' => true,
),
Indices Array
This array contains a list of arrays that are used to create indices in the database. The fields in this array are:
name : The unique name of the index
type : The type of index (primary, unique, or index)
fields : An ordered array of the fields to index
source : Set to 'non-db' if you are creating an index for added application functionality such as duplication checking on imports
The following example creates a primary index called 'userspk' on the 'id' column:
array(
'name' => 'userspk',
'type' => 'primary',
'fields'=> array('id')
),
Relationships Array
The relationships array specifies relationships between beans. Like the indices array entries, it is a list of names with array values. | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/index.html |
ceaaded7b31f-4 | lhs_module : The module on the left-hand side of the relationship
lhs_table : The table on the left-hand side of the relationship
lhs_key : The primary key column of the left-hand side of the relationship
rhs_module : The module on the right-hand side of the relationship
rhs_table : The table on the right-hand side of the relationship
rhs_key : The primary key column of the right-hand side of the relationship
relationship_type : The type of relationship (e.g. one-to-many, many-to-many)
relationship_role_column : The type of relationship role
relationship_role_column_value : Defines the unique identifier for the relationship role
The following example creates a relationship between a contact and the contact that they report to. The reports_to_id field maps to the id of the record that belongs to the higher-ranked contact. This is a one-to-many relationship in that a contact may only report to one person, but many people may report to the same contact.
'contact_direct_reports' => array(
'lhs_module' => 'Contacts',
'lhs_table' => 'contacts',
'lhs_key' => 'id',
'rhs_module' => 'Contacts',
'rhs_table' => 'contacts',
'rhs_key' => 'reports_to_id',
'relationship_type' => 'one-to-many'
),
Visibility Array
The visibility array specifies the row level visibility classes that are enabled on the bean. Each entry in the array, is a key-value pair, where the key is the name of the Visibility class and the value is set to boolean True. More information on configuring custom Visibility strategies can be found in the Architecture section under Visibility Framework.
Extending Vardefs
More information about extending and overriding vardefs can be found in the Extensions Framework documentation under Vardefs. | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/index.html |
ceaaded7b31f-5 | TopicsManually Creating Custom FieldsThe most common way to create custom fields in Sugar is via Studio inside the application. This page describes how to use the ModuleInstaller class or vardef extensions as alternative methods of creating custom fields.Specifying Custom Indexes for Import Duplicate CheckingWhen importing records to Sugar via the Import Wizard, users can select which of the mapped fields they would like to use to perform a duplicate check and thereby avoid creating duplicate records. This article explains how to enable an additional field or set of fields for selection in this step.Working With IndexesSugar provides a simple method for creating custom indexes through the vardef framework. Indexes can be built on one or more fields within a module. Indexes can be saved down to the database level or made available only in the application for functions such as Import Duplicate Checking.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/index.html |
868da64eb622-0 | Working With Indexes
Overview
Sugar provides a simple method for creating custom indexes through the vardef framework. Indexes can be built on one or more fields within a module. Indexes can be saved down to the database level or made available only in the application for functions such as Import Duplicate Checking.
Index Metadata
Indexes have the following metadata options that can be configured per index:
Key
Value
DescriptionÂ
name
string
A Unique identifier to define the index. Best practices recommend indexes start with idx and contain the suffix cstm to avoid conflicting with a stock index.Â
Note : Some databases have restrictions on the length of index names. Please check with your database vendor to avoid any issues.
type
stringÂ
 All indexes should use the type of "index"
fields
array
A PHP array of the fields for the index to utilizeÂ
source
string
Specify as "non-db" to avoid creating the index in the database
Creating Indexes
Stock indexes are initially defined in the module's vardefs file under the indices array. For reference, you can find them using the vardef path of your module. The path will be  ./modules/<module>/vardefs.php.
Custom indexes should  be created using the Extension Framework. First, create a PHP file in the extension directory of your desired module. The path should similar to ./custom/Extension/modules/<module>/Ext/Vardefs/<name>.php.
In the new file, add the appropriate $dictionary reference to define the custom index:
<?php
$dictionary['<module>']['indices'][] = array(
'name' => '<index name>',
'type' => 'index',
'fields' => array(
'field1',
'field2',
)
); | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Working_With_Indexes/index.html |
868da64eb622-1 | 'field1',
'field2',
)
);
Note : For performance reasons, it is not recommended to create an index on a single field unless the source is set to non-db.
Once installed,you will need to navigate to Admin > Repair > Quick Repair and Rebuild to enable the custom index. You will need to execute any scripts generated by the rebuild process.
Removing Indexes
Stock indexes are initially defined in the module's vardefs file under the indices array. For reference, you can find them using the vardef path of your module. The path will be ./modules/<module>/vardefs.php.
Stock indexes should be removed using the Extension Framework. First, create a PHP file in the extension directory of your desired module. The path should similar to ./custom/Extension/modules/<module>/Ext/Vardefs/<name>.php.
In the new file, loop through the existing 'indices' sub-array of the $dictionary to locate the stock index to remove, and use unset() to remove it from the array.
Example
The following is an example to remove the idx_calls_date_start index from the Call module's vardefs.
First, create ./custom/Extension/modules/Calls/Ext/Vardefs/remove_idx_calls_date_start.php from the root directory of your Sugar installation on the web server. When creating the file, keep in mind the following requirements:
The name of the file is not important, as long as it ends with a .php extension.
The rest of the directory path is case sensitive so be sure to create the directories as shown.
If you are removing the index for a module other than Calls, then substitute the corresponding directory name with that module.
Ensure that the entire directory path and file have the correct ownership and sufficient permissions for the web server to access the file.
The contents of the file should look similar to the following code: | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Working_With_Indexes/index.html |
868da64eb622-2 | The contents of the file should look similar to the following code:
<?php
$call_indexes = $dictionary['Call']['indices'];
$remove_index = "idx_calls_date_start";
foreach($call_indexes as $index_key => $index_item) {
if( $index_item['name'] == $remove_index ) {
unset($dictionary['Call']['indices'][$index_key]);
}
}
Note : Removing the reference to the index from the module's indices array does not actually remove the index from the module's database table. Removing the reference from the indices array ensures that the index is not added back to the module's database table when performing any future Quick Repair and Rebuilds. The database index must be removed directly at the database level. On MySQL, with the current example, this could be done with a query like:
ALTER TABLE calls DROP INDEX idx_calls_date_start;
Once installed,you will need to navigate to Admin > Repair > Quick Repair and Rebuild to remove the index from the $dictionary array. You will need to execute any scripts generated by the rebuilding process.
Creating Indexes for Import Duplicate Checking
When importing records to Sugar via the Import Wizard, users can select which of the mapped fields they would like to use to perform a duplicate check and thereby avoid creating duplicate records. The following instructions explain how to enable an additional field or set of fields for selection in this step.
Example
The following is an example to add the home phone field to the Contact module's duplicate check.
First, create ./custom/Extension/modules/Contacts/Ext/Vardefs/custom_import_index.php from the root directory of your Sugar installation on the web server. When creating the file, keep in mind the following requirements:
The name of the file is not important, as long as it ends with a .php extension. | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Working_With_Indexes/index.html |
868da64eb622-3 | The rest of the directory path is case sensitive so be sure to create the directories as shown.
If you are creating the import index for a module other than Contacts, then substitute the corresponding directory name with that module.
Ensure that the entire directory path and file have the correct ownership and sufficient permissions for the web server to access the file.
The contents of the file should look similar to the following code:
<?php
$dictionary['Contact']['indices'][] = array(
'name' => 'idx_home_phone_cstm',
'type' => 'index',
'fields' => array(
0 => 'phone_home',
),
'source' => 'non-db',
);
Please note that the module name in line 2 of the code is singular (i.e. Contact, not Contacts). If you are unsure of what to enter for the module name, you can verify the name by opening the ./cache/modules/<module_name>/<module_name>vardefs.php file. The second line of that file will have text like the following:
$GLOBALS["dictionary"]["Contact"] = array (...);
The parameter following "dictionary" is the same parameter you should use in the file defining the custom index. To verify duplicates against a combination of fields (i.e. duplicates will only be flagged if the values of multiple fields match those of an existing record), then simply add the desired fields to the 'fields' array in the code example.
Finally, navigate to Admin > Repair > Quick Repair and Rebuild to enable the custom index for duplicate verification when importing records in the module.Â
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Working_With_Indexes/index.html |
195edd6f1e4c-0 | Manually Creating Custom Fields
Overview
The most common way to create custom fields in Sugar is via Studio inside the application. This page describes how to use the ModuleInstaller class or vardef extensions as alternative methods of creating custom fields.
Note: Sugar Sell Essentials customers do not have the ability to upload custom file packages to Sugar using Module Loader.
Using ModuleInstaller to Create Custom Fields
There are two ways to create a field using the ModuleInstaller class: via installer package or programmatically. An example of creating a field from a module-loadable package is explained in the Module Loader documentation,, Creating an Installable Package that Creates New Fields. The following example shows how to programmatically add custom fields using the ModuleInstaller class with the install_custom_fields() method:
<?php
$fields = array (
//Text
array(
'name' => 'text_field_example',
'label' => 'LBL_TEXT_FIELD_EXAMPLE',
'type' => 'varchar',
'module' => 'Accounts',
'help' => 'Text Field Help Text',
'comment' => 'Text Field Comment Text',
'default_value' => '',
'max_size' => 255,
'required' => false, // true or false
'reportable' => true, // true or false
'audited' => false, // true or false
'importable' => 'true', // 'true', 'false', 'required'
'duplicate_merge' => false, // true or false
),
//DropDown
array(
'name' => 'dropdown_field_example',
'label' => 'LBL_DROPDOWN_FIELD_EXAMPLE',
'type' => 'enum',
'module' => 'Accounts', | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Manually_Creating_Custom_Fields/index.html |
195edd6f1e4c-1 | 'type' => 'enum',
'module' => 'Accounts',
'help' => 'Enum Field Help Text',
'comment' => 'Enum Field Comment Text',
'ext1' => 'account_type_dom', //maps to options - specify list name
'default_value' => 'Analyst', //key of entry in specified list
'mass_update' => false, // true or false
'required' => false, // true or false
'reportable' => true, // true or false
'audited' => false, // true or false
'importable' => 'true', // 'true', 'false' or 'required'
'duplicate_merge' => false, // true or false
),
//MultiSelect
array(
'name' => 'multiselect_field_example',
'label' => 'LBL_MULTISELECT_FIELD_EXAMPLE',
'type' => 'multienum',
'module' => 'Accounts',
'help' => 'Multi-Enum Field Help Text',
'comment' => 'Multi-Enum Field Comment Text',
'ext1' => 'account_type_dom', //maps to options - specify list name
'default_value' => 'Analyst', //key of entry in specified list
'mass_update' => false, // true or false
'required' => false, // true or false
'reportable' => true, // true or false
'audited' => false, // true or false
'importable' => 'true', // 'true', 'false' or 'required'
'duplicate_merge' => false, // true or false
),
//Checkbox
array(
'name' => 'checkbox_field_example', | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Manually_Creating_Custom_Fields/index.html |
195edd6f1e4c-2 | //Checkbox
array(
'name' => 'checkbox_field_example',
'label' => 'LBL_CHECKBOX_FIELD_EXAMPLE',
'type' => 'bool',
'module' => 'Accounts',
'default_value' => true, // true or false
'help' => 'Bool Field Help Text',
'comment' => 'Bool Field Comment',
'audited' => false, // true or false
'mass_update' => false, // true or false
'duplicate_merge' => false, // true or false
'reportable' => true, // true or false
'importable' => 'true', // 'true', 'false' or 'required'
),
//Date
array(
'name' => 'date_field_example',
'label' => 'LBL_DATE_FIELD_EXAMPLE',
'type' => 'date',
'module' => 'Accounts',
'default_value' => '',
'help' => 'Date Field Help Text',
'comment' => 'Date Field Comment',
'mass_update' => false, // true or false
'required' => false, // true or false
'reportable' => true, // true or false
'audited' => false, // true or false
'duplicate_merge' => false, // true or false
'importable' => 'true', // 'true', 'false' or 'required'
),
//DateTime
array(
'name' => 'datetime_field_example',
'label' => 'LBL_DATETIME_FIELD_EXAMPLE',
'type' => 'datetime',
'module' => 'Accounts',
'default_value' => '', | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Manually_Creating_Custom_Fields/index.html |
195edd6f1e4c-3 | 'module' => 'Accounts',
'default_value' => '',
'help' => 'DateTime Field Help Text',
'comment' => 'DateTime Field Comment',
'mass_update' => false, // true or false
'enable_range_search' => false, // true or false
'required' => false, // true or false
'reportable' => true, // true or false
'audited' => false, // true or false
'duplicate_merge' => false, // true or false
'importable' => 'true', // 'true', 'false' or 'required'
),
//Encrypt
array(
'name' => 'encrypt_field_example',
'label' => 'LBL_ENCRYPT_FIELD_EXAMPLE',
'type' => 'encrypt',
'module' => 'Accounts',
'default_value' => '',
'help' => 'Encrypt Field Help Text',
'comment' => 'Encrypt Field Comment',
'reportable' => true, // true or false
'audited' => false, // true or false
'duplicate_merge' => false, // true or false
'importable' => 'true', // 'true', 'false' or 'required'
),
);
require_once('ModuleInstall/ModuleInstaller.php');
$moduleInstaller = new ModuleInstaller();
$moduleInstaller->install_custom_fields($fields);
Add labels for custom fields by creating a corresponding language extension file:
./custom/Extension/modules/Accounts/Ext/Language/en_us.<name>.php
<?php
$mod_strings['LBL_TEXT_FIELD_EXAMPLE'] = 'Text Field Example';
$mod_strings['LBL_DROPDOWN_FIELD_EXAMPLE'] = 'DropDown Field Example'; | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Manually_Creating_Custom_Fields/index.html |
195edd6f1e4c-4 | $mod_strings['LBL_DROPDOWN_FIELD_EXAMPLE'] = 'DropDown Field Example';
$mod_strings['LBL_CHECKBOX_FIELD_EXAMPLE'] = 'Checkbox Field Example';
$mod_strings['LBL_MULTISELECT_FIELD_EXAMPLE'] = 'Multi-Select Field Example';
$mod_strings['LBL_DATE_FIELD_EXAMPLE'] = 'Date Field Example';
$mod_strings['LBL_DATETIME_FIELD_EXAMPLE'] = 'DateTime Field Example';
$mod_strings['LBL_ENCRYPT_FIELD_EXAMPLE'] = 'Encrypt Field Example';
Finally, navigate to Admin > Repair > Quick Repair and Rebuild to make the new field available for users.
Using the Vardef Extensions
You should try to avoid creating your own custom fields using the vardefs as there are several caveats:
If your installation does not already contain custom fields, you must manually create the custom table. Otherwise, the system will not recognize your field's custom vardef. This situation is outlined in the following section.
You must run a Quick Repair and Rebuild and then execute the generated SQL after the vardef is installed.
You must correctly define the properties of a vardef. If you miss any, the field may not work properly.
Your field name must end with "_c" and have the property 'source' set to 'custom_fields'. This is required as you should not modify core tables in Sugar and it is not permitted on Sugar's cloud service.
Your vardef must specify the exact indexes of the properties you want to set. For example, use: Â $dictionary['<module singular>']['fields']['example_c']['name'] = 'myfield_c';Â instead of $dictionary['<module singular>']['fields']['example_c'] = array(['name' => 'myfield_c');. This will help prevent the system from losing any properties when loading from the extension framework. | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Manually_Creating_Custom_Fields/index.html |
195edd6f1e4c-5 | The initial challenge when creating your own custom vardef is getting the system to recognize the vardef and generate the database field. This issue is illustrated with the example below:
./custom/Extension/modules/<module>/Ext/Vardefs/<file>.php
<?php
$dictionary['<module singular>']['fields']['example_c']['name'] = 'example_c';
$dictionary['<module singular>']['fields']['example_c']['vname'] = 'LBL_EXAMPLE_C';
$dictionary['<module singular>']['fields']['example_c']['type'] = 'varchar';
$dictionary['<module singular>']['fields']['example_c']['enforced'] = '';
$dictionary['<module singular>']['fields']['example_c']['dependency'] = '';
$dictionary['<module singular>']['fields']['example_c']['required'] = false;
$dictionary['<module singular>']['fields']['example_c']['massupdate'] = '0';
$dictionary['<module singular>']['fields']['example_c']['default'] = '';
$dictionary['<module singular>']['fields']['example_c']['no_default'] = false;
$dictionary['<module singular>']['fields']['example_c']['comments'] = 'Example Varchar Vardef';
$dictionary['<module singular>']['fields']['example_c']['help'] = '';
$dictionary['<module singular>']['fields']['example_c']['importable'] = 'true';
$dictionary['<module singular>']['fields']['example_c']['duplicate_merge'] = 'disabled';
$dictionary['<module singular>']['fields']['example_c']['duplicate_merge_dom_value'] = '0';
$dictionary['<module singular>']['fields']['example_c']['audited'] = false;
$dictionary['<module singular>']['fields']['example_c']['reportable'] = true; | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Manually_Creating_Custom_Fields/index.html |
195edd6f1e4c-6 | $dictionary['<module singular>']['fields']['example_c']['reportable'] = true;
$dictionary['<module singular>']['fields']['example_c']['unified_search'] = false;
$dictionary['<module singular>']['fields']['example_c']['merge_filter'] = 'disabled';
$dictionary['<module singular>']['fields']['example_c']['calculated'] = false;
$dictionary['<module singular>']['fields']['example_c']['len'] = '255';
$dictionary['<module singular>']['fields']['example_c']['size'] = '20';
$dictionary['<module singular>']['fields']['example_c']['id'] = 'example_c';
$dictionary['<module singular>']['fields']['example_c']['custom_module'] = '';
//required to create the field in the _cstm table
$dictionary['<module singular>']['fields']['example_c']['source'] = 'custom_fields';
Once the vardef is in place, determine whether the custom field's module already contains any other custom fields. If there are not any existing custom fields, create a corresponding record in fields_meta_data that will trigger the comparison process.
INSERT INTO fields_meta_data (id, name, vname, comments, custom_module, type, len, required, deleted, audited, massupdate, duplicate_merge, reportable, importable) VALUES ('<module>example_c', 'example_c', 'LBL_EXAMPLE_C', 'Example Varchar Vardef', '<module>', 'varchar', 255, 0, 0, 0, 0, 0, 1, 'true'); | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Manually_Creating_Custom_Fields/index.html |
195edd6f1e4c-7 | Finally, navigate to Admin > Repair > Quick Repair and Rebuild. The system will then rebuild the extensions. After the repair, you will notice a section at the bottom stating that there are differences between the database and vardefs. Execute the scripts generated to create theSave custom field:
Missing <module>_cstm Table:
/*Checking Custom Fields for module : <module>*/
CREATE TABLE <module>_cstm (id_c char(36) NOT NULL , PRIMARY KEY (id_c)) CHARACTER SET utf8 COLLATE utf8_general_ci;
Missing Columns:
/*MISSING IN DATABASE - example_c - ROW*/
ALTER TABLE <module>_cstm add COLUMN example_c varchar(255) NULL ;
Â
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Manually_Creating_Custom_Fields/index.html |
f11c0c9b2d3c-0 | Specifying Custom Indexes for Import Duplicate Checking
Overview
When importing records to Sugar via the Import Wizard, users can select which of the mapped fields they would like to use to perform a duplicate check and thereby avoid creating duplicate records. This article explains how to enable an additional field or set of fields for selection in this step.
Resolution
The import wizard's duplicate check operates based on indices defined for that module. You can create a non-database index to check for a field. It is important that it is non-database as single column indices on your database can hamper overall performance. The following is an example to add the home phone field to the Contact module's duplicate check.
First, create the following file from the root directory of your Sugar installation on the web server:
./custom/Extension/modules/Contacts/Ext/Vardefs/custom_import_index.php
When creating the file, keep in mind the following requirements:
The name of the file is not important, as long as it ends with a .php extension.
The rest of the directory path is case sensitive so be sure to create the directories as shown.
If you are creating the import index for a module other than Contacts, then substitute the corresponding directory name with that module.
Ensure that the entire directory path and file have the correct ownership and sufficient permissions for the web server to access the file.
The contents of the file should look similar to the following code:
<?php
$dictionary['Contact']['indices'][] = array(
'name' => 'idx_home_phone_cstm',
'type' => 'index',
'fields' => array(
0 => 'phone_home',
),
'source' => 'non-db',
); | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Specifying_Custom_Indexes_for_Import_Duplicate_Checking/index.html |
f11c0c9b2d3c-1 | ),
'source' => 'non-db',
);
Please note that the module name in line 2 of the code is singular (i.e. Contact, not Contacts). If you are unsure of what to enter for the module name, you can verify the name by opening the ./cache/modules/<module_name>/<module_name>vardefs.php file. The second line of that file will have text like the following:
$GLOBALS["dictionary"]["Contact"] = array (
The parameter following "dictionary" is the same parameter you should use in the file defining the custom index. To verify duplicates against a combination of fields (i.e. duplicates will only be flagged if the values of multiple fields match those of an existing record), then simply add the desired fields to the 'fields' array in the code example.
Finally, navigate to Admin > Repair > Quick Repair and Rebuild to enable the custom index for duplicate verification when importing records in the module.
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Vardefs/Specifying_Custom_Indexes_for_Import_Duplicate_Checking/index.html |
3781bc5b50ec-0 | Fields
Overview
How fields interact with the various aspects of Sugar.Â
SugarField Widgets
The SugarField widgets, located in ./include/SugarFields/Fields/ , define the data formatting and search query structure for the various field types. They also define the rendering of fields for modules running in backward compatibility mode. When creating or overriding field widgets, developers should place their customization in ./custom/include/SugarFields/Fields/. For information on how Sidecar renders fields, please refer to the fields section in our user interface documentation. Creating Custom Fields
Implementation
All fields for a module are defined within vardefs. Within this definition, the type attribute will determine all of the logic applied to the field. For example, the Contacts module has a 'Do Not Call' field. In the vardefs, this field is defined as follows:
'do_not_call' => array (
'name' => 'do_not_call', // the name of the field
'vname' => 'LBL_DO_NOT_CALL', // the label for the field name
'type' => 'bool', // the fields type
'default' => '0', // the fields default value
'audited'=>true, // whether the field is audited
'duplicate_on_record_copy' => 'always', // whether to duplicate the fields value when being copied
'comment' => 'An indicator of whether contact can be called' // admin context of the field
), | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Fields/index.html |
3781bc5b50ec-1 | ),
 The bool type field is rendered in the UI from the ./clients/base/fields/bool/bool.js field controller which renders the appropriate handlebars template as defined by the users current view for sidecar enabled modules. When the user saves data, the controller formats the data for the API and passes it to an endpoint. Once the data is received by the server, The SugarField definition calls any additional logic in the apiSave function to format the data for saving to the database. The same concept is applied in the apiFormatField function when retrieving data from the database to be passed back to the user interface through the API. For modules running in backward compatibility mode, the bool field is rendered using the Smarty .tpl) templates located in ./include/SugarFields/Fields/Bool/.
While the vardefs define the default type for a field, this value can be overridden in the metadata of the view rendering the field. The example being that in ./custom/modules/Contacts/clients/base/views/record/record.php, you can modify the do_not_call field array to point to a custom field type you have created. For more information on creating custom field types, please refer to Creating Custom Fields documentation. Â
Â
Last modified: 2023-02-03 21:04:03 | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Data_Framework/Fields/index.html |
7a1f35b2e450-0 | Introduction
Overview
The Sugar Developer Guide is an essential resource for developers who are new to Sugar or to CRM and web-based applications. It describes how to configure and customize the Sugar platform for a broad range of tasks applicable to any organization that has a need to manage business relationships with people.
Prerequisites
Using and understanding the documentation contained in the Sugar Developer Guide requires basic programming and software development knowledge. Specifically, you should be familiar with the PHP general-purpose scripting language and the SQL programming language for accessing databases.
Understanding Sugar's Framework
Designed as the most modern web-based CRM platform available today, Sugar has quickly become the business application standard for companies around the world. The Sugar application framework has a sophisticated extension model built into it, allowing developers to make significant customizations to the application in an upgrade-safe and modular manner. It is easy to modify the core files in the distribution; you should always check for an upgrade-safe way to make changes. Educating developers on how to make upgrade-safe customizations is one of the key goals of this Developer Guide. For more information on Sugar's structure, please review the architecture section.
Supported Platforms
Originally, Sugar® was written on the LAMP stack (i.e. Linux, Apache, MySQL, and PHP), but has since added support for every operating system on which the PHP programming language runs, for the Microsoft IIS web server, and for the Microsoft SQL Server, IBM® DB2®, and Oracle databases. For more information about supported software versions and recommended stacks, please refer to the main Supported Platforms page.
Sugar Products | https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Introduction/index.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.