id
stringlengths
14
16
text
stringlengths
33
5.27k
source
stringlengths
105
270
032ec26b25b8-5
// Getting tag field and its properties $tagField = $bean->getTagField(); $tagFieldProperties = $bean->field_defs[$tagField]; // Identifying relation link $link = $tagFieldProperties['link']; // Loading relationship if ($bean->load_relationship($link)) { // Adding newly created Tag Bean $bean->$link->add($tagBean->id); } Removing Tags from a Record Here is an example that demonstrates how to remove a tag from a contact record: // Getting the Contacts Bean $bean = BeanFactory::getBean("Contacts", "<RECORD_ID>"); // Getting tag field and its properties $tagField = $bean->getTagField(); $tagFieldProperties = $bean->field_defs[$tagField]; // Identifying relation link $link = $tagFieldProperties['link']; // Loading relationship if($bean->load_relationship($link)){ // Removing the Tag ID $bean->$link->delete($bean->id, "<TAG_RECORD_ID>"); } Synchronizing Tags by Name With API Helpers If you have multiple tags that you need to add and delete at the same time, then you can use SugarFieldTag->apiSave method. Here is an example that demonstrates how to sync tags by using SugarFieldTag Class for a Contact record. It is important to know that since this is a sync; you will need to keep the existing tags if you want them to still exist in the record.  // Getting the Contacts Bean $bean = BeanFactory::getBean("Contacts", "<RECORD_ID>"); // Getting Tag Field ID $tagField = $bean->getTagField(); // Getting Tag Field Properties $tagFieldProperties = $bean->field_defs[$tagField];
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Tags/index.html
032ec26b25b8-6
$tagFieldProperties = $bean->field_defs[$tagField]; // Preparing the latest Tags to be sync with the record $tags = [ // Note: Already attached tags will be automatically removed from the record // If you want to keep some of the existing tags then you will need to keep them in the array "tag" => [ // Since this tag is already added, it will be preserved 'already added tag' => 'Already Added Tag', // The new tags to add - All other tags that previously existed will be deleted 'new tag' => 'New Tag', 'new tag2' => 'New Tag2', ], ]; // Building SugarFieldTag instance $SugarFieldTag = new SugarFieldTag(); // Passing the arguments to save the Tags $SugarFieldTag->apiSave($bean, $tags, $tagField, $tagFieldProperties); Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Tags/index.html
9717bb124f9b-0
Backward Compatibility Overview As of Sugar® 7, modules are built using the Sidecar framework. Any modules that still use the MVC architecture and have not yet migrated to the Sidecar framework are set in what Sugar refers to as "backward compatibility" (BWC) mode. For the list of Studio-enabled modules in backward compatibility for your version of Sugar, please refer to the User Interface (Legacy Modules) documentation for your version of Sugar. URL Differences There are some important differences between the legacy MVC and Sidecar URLs. When a module is set in backward compatibility, the URL will contain "/#bwc/" in the path and use query string parameters to identify the module and action. An example of the Sidecar BWC URL is shown below. http://{site url}/#bwc/index.php?module=<module>&action=<action> You can see that this differs from the standard route of: http://{site url}/#<module>/<record id> Studio Differences There are some important differences between the legacy MVC modules and Sidecar modules. When a module is in backward compatibility mode, an asterisk is placed next to the modules name in Studio. Modules in backward compatibility will use the legacy MVC metadata layouts, located in ./modules/<module>/metadata/, as follows: Layouts Edit View Detail View List View Search Basic Search Advanced Search These layouts differ from Sidecar in many ways. The underlying metadata is very different and you should notice that the MVC layouts have a separation between the Edit View and Detail View whereas the Sidercar layouts make use of the Record View. The Sidecar metadata for Sugar is located in ./modules/<module>/clients/base/views/. Layouts Record View List View Search Search TopicsEnabling Backward CompatibilityHow to enable backward compatibility for modules.Converting Legacy Modules To SidecarHow to upgrade a legacy module to be Sidecar enabled.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Backward_Compatibility/index.html
9717bb124f9b-1
Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Backward_Compatibility/index.html
e1ca9b298b14-0
Enabling Backward Compatibility Overview How to enable backward compatibility for a module. Enabling Backward Compatibility Backward Compatibility Mode is not a permanent solution for modules with legacy customizations. If you should need to temporarily get a module working due to legacy customizations, you can follow the steps below to enable the legacy MVC framework. Please note that switching stock Sugar modules from the Sidecar framework to backward compatibility mode is not supported and may result in unexpected behaviors in the application. Enabling BWC To enable backward compatibility, you must first create a file in ./custom/Extension/application/Ext/Include/ for the module. If the module is custom, there will already be an existing file in this folder pertaining to the module that you can edit. ./custom/Extension/application/Ext/Include/<file>.php <?php $bwcModules[] = '<module key>'; Once the file is in place, you will need to navigate to Admin > Repair > Quick Repair and Rebuild. The Quick Repair can wait until you have completed the following sections for this customization. Verifying BWC Is Enabled To verify that backward compatibility is enabled, you can inspect App.metadata.get().modules after running a Quick Repair and Rebuild in your browser's console window: Using Developer Tools in Google Chrome Open Developer Tools This can be done in the following ways: Command + Option + i View > Developer > Developer Tools Right-click on the web page and selecting "Inspect Element" Select the "Console" tab Run the following command, replacing <module key> and verify that it returns true: App.metadata.get().modules.<module key>.isBwcEnabled Using Firebug in Google Chrome or Mozilla Firefox Open Firebug Select the "Console" tab Run the following command, replacing <module key>, and verify that it returns true:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Backward_Compatibility/Enabling_Backward_Compatibility/index.html
e1ca9b298b14-1
Run the following command, replacing <module key>, and verify that it returns true: App.metadata.get().modules.<module key>.isBwcEnabled Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Backward_Compatibility/Enabling_Backward_Compatibility/index.html
f289356a1c8c-0
Converting Legacy Modules To Sidecar How to upgrade a legacy module to be Sidecar enabled. Overview After upgrading your instance to Sugar 7.x, some custom modules may be left in the legacy backward compatible format. This is normally due to the module containing a custom view or file that Sugar does not recognize as being a supported customization for Sidecar. To get your module working with Sidecar, you will need to remove the unsupported customization and run the UpgradeModule.php script. Note: The following commands should be run on a sandbox instance before being applied to any production environment. It is also important to note that this script should only be run against custom modules. Stock modules in backward compatibility should remain in backward compatibility. Steps to Complete The following steps require access to both the Sugar filesystem as well as an administrative user. Note: As of Sugar 10.0, the UpgradeModule.php script has been removed from the codebase. We are providing a zip of the files that were removed so that it is still possible to run the upgrade. Begin by downloading this zip file that contains the previously removed code Unzip the file and move the contents into your Sugar application at ./modules/UpgradeWizard/ To upgrade a custom module, identify the module's unique key. This key can be easily found by identifying the module's folder name in ./modules/<module key name>/. The module's key name will be in the format of abc_module.  Next, change to the ./modules/UpgradeWizard/ path relative to your Sugar root directory in your terminal or command line application:cd <sugar root>/modules/UpgradeWizard/ Run the UpgradeModule.php script, passing in the sugar root directory and the unique key of the legacy module:php UpgradeModule.php <sugar root> <module key>
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Backward_Compatibility/Converting_Legacy_Modules_To_Sidecar/index.html
f289356a1c8c-1
An example is shown below:php UpgradeModule.php /var/www/html/sugarcrm/ abc_module The script with then output a series of messages identifying issues that need to be corrected. Once the issues have been addressed, you can then run the UpgradeModule.php script again to confirm no errors have been found. Once completed, log into your instance and navigate to Admin > Repair > Quick Repair and Rebuild. Test the custom module to ensure it is working as expected. There is no guarantee that the module will be fully functional in Sidecar and may therefore require additional development effort to ensure compatibility. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Backward_Compatibility/Converting_Legacy_Modules_To_Sidecar/index.html
3da9e8c0abc3-0
Access Control Lists Overview Access Control Lists (ACLs) are used to control access to the modules, data, and actions available to users in Sugar. By default, Sugar comes with a default ACL Strategy that is configurable by an Admin through the Roles module via Admin > Role Management. Sugar also comes with other ACL strategies that are located in the ./data/acl/ folder, and are used in other parts of the system such as the Administration module, Emails module, Locked Fields functionality, and many others. They can also be leveraged by customizations and custom ACL strategies can be implemented to control your own customizations. Actions Actions are the use cases in which a User interacts with a particular module in the system. ACLs control access by using different logic to determine if a user can do an action. Below is a list of actions that are utilized by Sugar and will be requested actions against a custom ACL strategy implementation. You can add your own actions to be checked against in a custom strategy, but the following list should always be considered: index, list, listview - for module ListView access detail, detailview, view - module DetailView access popupeditview, editview - module EditView access edit, save - editing module data import - import into the module export - export from the module delete - delete module record team_security - should this module have team security enabled? field - access field ACLs. The field action is specified via context array, see below subpanel - checks if subpanel should be displayed. Should have "subpanel" context option. Note: Action names are not case sensitive, although the standard practice is to use them in all lowercase Field Actions When using the field action, the action for the particular field that is being checked is passed via Context. The field actions that are used in Sugar are: access - any access to field data
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Access_Control_Lists/index.html
3da9e8c0abc3-1
access - any access to field data read, detail - read access write, edit - write access Context The context array is used throughout Sugar's ACL architecture as a way to pass extra contextual data that is used by an ACL Strategy to determine the access request. The following context parameters are used in stock contexts, and should be used as a guideline for custom ACL implementations as parameters that should be accommodated or used: bean (SugarBean) - the current SugarBean object user (User) - the user to check access for, otherwise defaults to the current user. user_id (String) - the current user ID (also overrides global current user). If the current user object is available, use the user context, since it has precedent. owner_override (Bool) - if set to true, apply ACLs as if the current user were the owner of the object. subpanel (aSubPanel) - used in subpanel action to provide aSubPanel object describing the panel. field, action (String) - used to specify field name and action name for field ACL requests. massupdate (Bool) - true if save operation is a mass update SugarACL The SugarACL Class, ./data/SugarACL.php, is the static API for checking access for an action against a module.  checkAccess() The checkAccess() method is used to check a users access for a given action against a module.  SugarACL::checkAccess('Accounts','edit'); Arguments Name Type Required Description $module String true The name of the module $action String true The name of the action. See Actions section. $context Array false The associative array of context data. See Context section. Returns Boolean checkField()
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Access_Control_Lists/index.html
3da9e8c0abc3-2
The associative array of context data. See Context section. Returns Boolean checkField() The checkField() method is used to check a users access for a given field against a module.  SugarACL::checkField('Accounts','account_type','view'); Arguments Name Type Required Description $module String true The name of the module $field String true The name of the field $action String true The name of the action. See Actions section. $context Array false The associative array of context data. See Context section. Returns Boolean getFieldAccess() The getFieldAccess() method is used to get the access level for a specific $access = SugarACL::getFieldAccess('Accounts','account_type'); Arguments Name Type Required Description $module String true The name of the module $field String true The name of the field $context Array false The associative array of context data. See Context section. Returns Integer The integers are represented as constants in the SugarACL class, and correspond as follows: SugarACL::ACL_NO_ACCESS = 0 - access denied SugarACL::ACL_READ_ONLY = 1 - read only access SugarACL::ACL_READ_WRITE = 4 - full access filterModuleList() The filterModuleList() method is used to filter the list of modules available for a given action. For example, if you wanted to get all the modules the current user had edit access to, you might call the following in code: global $app_list_strings; $modules = $app_list_strings['module_list']; $editableModules = SugarACL::filterModuleList($modules,'edit'); Arguments Name Type Required Description $modules Array true The list of modules you want to filter
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Access_Control_Lists/index.html
3da9e8c0abc3-3
Required Description $modules Array true The list of modules you want to filter $action String false The action to check for, See Actions section. Defaults to 'access' action $use_value Boolean false Whether to the module name in the $modules array is in the Key or the Value of the array. Defaults to false For example, if filtering an array of modules, where the modules are defined in the values of the array: $modules = array( 'Accounts', 'Cases', 'Administration' ); $accessModules = SugarACL::filterModuleList($modules,'access',true); Returns Array The filtered list of modules. disabledModuleList() Similar to the previous method, the disableModuleList() method filters a list of modules to those that the user does not have access to. global $app_list_strings; $modules = $app_list_strings['module_list']; $disabledModules = SugarACL::disabledModuleList($modules,'access'); Arguments Name Type Required Description $modules Array true The list of modules you want to filter $action String false The action to check for, See Actions section. Defaults to 'access' action $use_value Boolean false Whether to the module name in the $modules array is in the Key or the Value of the array. Defaults to false For example, if filtering an array of modules, where the modules are defined in the values of the array: $modules = array( 'Accounts', 'Cases', 'Administration' ); $accessModules = SugarACL::filterModuleList($modules,'access',true); Returns Array The filtered list of modules. moduleSupportsACL()
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Access_Control_Lists/index.html
3da9e8c0abc3-4
Returns Array The filtered list of modules. moduleSupportsACL() The moduleSupportsACL() method is used to check if a module has ACLs defined on the vardefs. A good use case for this method is to not run any ACL checks if module has no ACL definitions. SugarACL::moduleSupportsACL('Accounts'); Arguments Name Type Required Description $module String true The name of the module Returns Boolean listFilter() The listFilter() method allows for filtering an array of fields for a module to remove those which the user does not have access to. The removal can be done in a couple of different ways, provided by the $options argument. The filtering of the array is done in place, rather than returning the filtered list. $Account = BeanFactory::getBean('Accounts','12345'); $fields = array( 'account_type' => 'foobar', 'status' => 'New', 'name' => 'Customer' ); $context = array( 'bean' => $Account ); $options = array( 'blank_value' => true ); SugarACL::listFilter('Accounts',$fields,$context,$options); echo <pre>json_encode($fields)</pre>; Should the user not have access to the 'status' field, the above might output: { "account_type": "foobar", "status": "", "name": "Customer" } Arguments Name Type Required Description $module String true The name of the module $list Array true The array, as a reference, which will be filtered $context Array false The associative array of context data. See Context section. $options Array false
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Access_Control_Lists/index.html
3da9e8c0abc3-5
false The associative array of context data. See Context section. $options Array false An associative array containing some of the following options: blank_value (Bool) - instead of removing inaccessible field put '' there add_acl (Bool) - instead of removing fields add 'acl' value with access level suffix (String) - strip suffix from field names min_access (Int) - require this level of access for the field. Defaults to SugarACL::ACL_READ_ONLY or 0 use_value (Bool) - look for field name in value, not in the key of the list Returns Void SugarBean Usage The SugarBean class also comes with some methods for working with the ACLs in regards to the current SugarBean context. These methods automatically provide the 'bean' context parameter and provide a wrapper that utilizes the SugarACL class getACLCategory() The getACLCategory() method is used by all of the ACL helper methods that exist on the SugarBean and is used to determine the module name that should be checked against for the current Bean. By default, it will return the acl_category property set on the Bean, otherwise if that is not set, it will use the module_dir property that is configured on the Bean. This method can be overridden by a custom Bean implementation, but the following code shows which properties on a Bean implementation should be set for usage with ACLs. <?php class testBean extends SugarBean { public $module_dir = 'testBean'; //all the other SugarBean class logic... } class test_SubmoduleBean extends SugarBean { public $module_dir = 'testBean/submodule'; public $acl_category = 'test_SubmoduleBean'; ///all the other SugarBean class logic... } $test = new testBean(); //echoes testBean
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Access_Control_Lists/index.html
3da9e8c0abc3-6
} $test = new testBean(); //echoes testBean echo $test->getACLCategory(); $submodule = new test_SubmoduleBean(); //echoes test_SubmoduleBean echo $submodule->getACLCategory(); Arguments None Returns String ACLAccess() The ACLAccess() method is a wrapper for SugarACL::checkField() method, which provides the Bean context as the current SugarBean. $Account = BeanFactory::getBean('Accounts','12345'); if ($Account->ACLFieldAccess('account_type','edit')){ //do something if User has account_type edit access } Arguments Name Type Required Description $action String false The name of the action to check. See Actions section. $context Array false The associative array of context data. See Context section. Returns Boolean ACLFieldAccess() The ACLFieldAccess() method is a wrapper for SugarACL::checkAccess() method, which provides the Bean context as the current SugarBean. $Account = BeanFactory::getBean('Accounts','12345'); if ($Account->ACLACcess('edit')){ //do something if User has edit access } Arguments Name Type Required Description $field String true The name of the field $action String false The name of the action to check, see Field Actions section. Defaults to 'access' $context Array false The associative array of context data. See Context section. Returns Boolean ACLFieldGet() The ACLFieldGet() method is a wrapper for SugarACL::getFieldAccess() method, which provides the Bean context as the current SugarBean. $Account = BeanFactory::getBean('Accounts','12345');
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Access_Control_Lists/index.html
3da9e8c0abc3-7
$Account = BeanFactory::getBean('Accounts','12345'); $accountTypeAccess = $Account->ACLFieldGet('account_type'); Arguments Name Type Required Description $field String true The name of the field $context Array false The associative array of context data. See Context section. Returns Boolean ACLFilterFields() The ACLFilterFields() method uses the SugarACL::checkField() method to blank out those fields which a user doesn't have access to on the current SugarBean. $Account = BeanFactory::getBean('Accounts','12345'); $Account->status = 'Old'; $Account->ACLFilterFields('edit'); echo $Account->status; Should the user not have 'edit' access to the 'status' field, the above wouldn't output any data since the status field would be blank. Arguments Name Type Required Description $action String true The name of the action to check. See Actions section. $context Array false The associative array of context data. See Context section. Returns Void ACLFilterFieldList() The ACLFilterFieldList() method is a wrapper for SugarACL::listFilter() method, which provides the Bean context as the current SugarBean. $Account = BeanFactory::getBean('Accounts','12345'); $fields = array( 'account_type' => 'foobar', 'status' => 'New', 'name' => 'Customer' ); $options = array( 'blank_value' => true ); $Account->ACLFilterFieldList($fields,array(),$options); echo "<pre>".json_encode($fields)."</pre>"; Should the user not have access to the 'status' field, the above might output: {
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Access_Control_Lists/index.html
3da9e8c0abc3-8
{ "account_type": "foobar", "status": "", "name": "Customer" } Arguments Name Type Required Description $list Array true The array, as a reference, which will be filtered $context Array false The associative array of context data. See Context section. $options Array false An associative array containing some of the following options: blank_value (Bool) - instead of removing inaccessible field put '' there add_acl (Bool) - instead of removing fields add 'acl' value with access level suffix (String) - strip suffix from field names min_access (Int) - require this level of access for the field. Defaults to SugarACL::ACL_READ_ONLY or 0 use_value (Bool) - look for field name in value, not in the key of the list Returns Void Legacy Methods When working in the Sugar codebase there might be areas that still utilize the following legacy ACLController class. The following gives a brief overview of a few methods that might still be used but should be avoided in future custom development. ACLController::checkAcess() The ACLController::checkAccess() method is just a wrapper for SugarACL::checkAccess() method and has been left in place for backward compatibility. ACLController::moduleSupportsACL() The ACLController::moduleSupportsACL() method is just a wrapper for SugarACL::moduleSupportsACL() method and has been left in place for backward compatibility. ACLController::displayNoAccess() This method does an echo to display a "no access" message for pages.  Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Access_Control_Lists/index.html
cd5c8342db0a-0
DateTime Overview The SugarDateTime class, located in, ./include/SugarDateTime.php, extends PHP's built in DateTime class and can be used to perform common operations on date and time values.  Setting With existing SugarDateTime objects, it is recommended to clone the object before modifying or performing operations on it. $new_datetime = clone $datetime; Another option is to instantiate a new SugarDateTime object. // defaults to now $due_date_time = new SugarDateTime(); $due_date_time->setDate($dueYear, $dueMonth, $dueDay); $due_date_time->setTime($dueHour, $dueMin); $due_date_time->setTimezone($dueTZ); Note : When creating a new SugarDateTime object, the date and time will default to the current date and time in the timezone configured in PHP. SugarDateTime Objects can also be modified by passing in common English textual date/time strings to manipulate the value. $due_date = clone $date; $end_of_the_month->modify("last day of this month"); $end_of_next_month->modify("last day of next month"); $thirty_days_later->modify("+30 days"); Formatting When formatting SugarDateTime objects into a string for display or logging purposes, there are a few options you can utilize through the formatDateTime() method. Return the date/time formatted for the database: $db_datetime_string = formatDateTime("datetime", "db"); Return the date/time formatted using a user's preference: global $current_user; $user_datetime_string = formatDateTime("datetime", "user", $current_user); Return the date/time formatted following ISO-8601 standards: $iso_datetime_string = formatDateTime("datetime", "iso");
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/DateTime/index.html
cd5c8342db0a-1
$iso_datetime_string = formatDateTime("datetime", "iso"); There are times when it is needed to return only certain parts of a date or time. The format() method accepts a string parameter to define what parts or information about the date/time should be returned.  // 28 Dec 2016 echo $due_date_time->format("j M Y"); // 2016-12-28 19:01:09 echo $due_date_time->asDb(); // The date/time 2016-12-28T11:01:09-08:00 is set in the timezone of America/Los_Angeles echo "The date/time " . $due_date_time->format("c") . " is set in the timezone of " . $due_date_time->format("e"); // The time when this date/time object was created is 11:01:09 AM -0800 echo "The time when this date/time object was created is " . $due_date_time->format("H:i:s A O"); // There are 31 days in the month of December echo "There are " . $due_date_time->format("t") . " days in the month of " . $due_date_time->format("F"); // There are 366 days in the year of 2016 echo "There are " . $due_date_time->__get("days_in_year") . " days in the year of " . $due_date_time->format("Y"); // Between Wed, 28 Dec 2016 11:01:09 -0800 and the end of the year, there are 4 days. echo "Between " . $due_date_time . " and the end of the year, there are " . ($due_date_time->__get("days_in_year") - $due_date_time->format("z")) . " days.";
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/DateTime/index.html
cd5c8342db0a-2
 For more information on the available options, please refer to http://php.net/manual/en/function.date.php  TimeDate Class The TimeDate class, located in ./include/TimeDate.php, utilizes the SugarDateTime class to provide an extended toolset of methods for date/time usage. Setting With existing TimeDate objects, it is recommended to clone the object before modifying or performing operations on it. $new_timedate = clone $timedate; Another option is to instantiate a new TimeDate object. // current time in UTC $timedate = new TimeDate(); $now_utcTZ = $timedate->getNow(); // current time in user's timezone $timedate = new TimeDate($current_user); $now_userTZ = $timedate->getNow(true); Note : When creating a new TimeDate object, the date and time will default to the current date and time in the UTC timezone unless a user object is passed in.  Formatting TimeDate objects can return the Date/Time in either a string format or in a SugarDateTime object. The TimeDate object has many formatting options; some of the most common ones are : getNow Get the current date/time as a SugarDateTime object  fromUser Get SugarDateTime object from user's date/time string asUser Format DateTime object as user's date/time string fromDb Get SugarDateTime object from a DB date/time string fromString Create a SugarDateTime object from a string get_db_date_time_format Gets the current database date and time format to_display_date_time Format a string as user's display date/time getNow returns SugarDateTime object Parameters Name Data Type Default
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/DateTime/index.html
cd5c8342db0a-3
getNow returns SugarDateTime object Parameters Name Data Type Default Description $userTz bool false Whether to use the user's timezone or not. False will use UTC Returns a SugarDateTime object set to the current date/time. If there is a user object associate to the TimeDate object, passing true to the $userTz parameter will return the object in user's timezone. If no user is associated or false is passed, the timezone returned will be in UTC. Example $timedate = new TimeDate($current_user); // returns current date/time in UTC $now_utcTZ = $timedate->getNow(); // returns current date/time in the user's timezone $now_userTZ = $timedate->getNow(true); fromUser returns SugarDateTime object Parameters Name Data Type Default Description $date string n/a Date/Time string to convert to an object $user User null User to utilize formatting and timezone info from Returns a SugarDateTime object converted from the passed in string. If there is a user object passed in as a parameter will return the object in user's timezone. If no user is passed in, the timezone returned will be in UTC. Example $date = "2016-12-28 13:09"; $timedate = new TimeDate(); $datetime = $timedate->fromUser($date, $current_user); asUser returns string Parameters Name Data Type Default Description $date string n/a Date/Time string to convert to an object $user User null User to utilize formatting and timezone info from
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/DateTime/index.html
cd5c8342db0a-4
$user User null User to utilize formatting and timezone info from Returns a string of the date and time formatted based on the user's profile settings. If there is a user object passed in as a parameter it will return the object in user's timezone. If no user is passed in, the timezone returned will be in UTC. Example $datetime = new datetime("2016-12-28 13:09"); $timedate = new TimeDate(); $formattedDate = $timedate->asUser($datetime, $current_user); fromDb returns SugarDateTime Parameters Name Data Type Default Description $date string n/a Date/Time string in database format to convert to an object Returns a SugarDateTime object converted from the passed in database formatted string. Note : If the string does not match the database format exactly, this function will return boolean false. Example // Y-m-d H:i:s $db_datetime = "2016-12-28 13:09:01"; $timedate = new TimeDate(); $datetime = $timedate->fromDb($db_datetime); // returns bool(false) $wrong_datetime = "2016-12-28 13:09"; $timedate = new TimeDate(); $datetime = $timedate->fromDb($timedate); fromString returns SugarDateTime Parameters Name Data Type Default Description $date string n/a Date/Time string to convert to an object $user User null User to utilize timezone info from
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/DateTime/index.html
cd5c8342db0a-5
$user User null User to utilize timezone info from Returns a SugarDateTime object converted from the passed in database formatted string. If there is a user object passed in as a parameter it will return the object in user's timezone. If no user is passed in, the timezone returned will be in UTC. Example $datetime_str = "December 28th 2016 13:09"; $timedate = new TimeDate(); $datetime = $timedate->fromString($datetime_str); get_db_date_time_format returns string Parameters N/a Returns a string of the current database date and time format settings.  Note : For just the date format use get_db_date_format() and for just the time format use get_db_time_format(). Example $timedate = new TimeDate(); // Y-m-d H:i:s $db_format = $timedate->get_db_date_time_format(); to_display_date_time returns string Parameters Name Data Type Default Description $date string n/a Date/Time string in database format $meridiem boolean true Deprecated -- Remains for backwards compatibility only $convert_tz boolean true Convert to user's timezone $user User null User to utilize formatting and timezone info from Returns a string of the date and time formatted based on the user's profile settings. If no user is passed in, the current user's default will be used. If $convert_tz is true the string returned will be in the passed in user's timezone. If no user is passed in, the timezone returned will be in UTC. Note : If the string does not match the database format exactly, this function will return boolean false. Example
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/DateTime/index.html
cd5c8342db0a-6
Example $datetime_str = "2016-12-28 13:09:01"; // 12-28-2016 07:09 $timedate = new TimeDate(); $datetime = $timedate->to_display_date_time($datetime_str); // 2016-12-28 13:09 $timedate = new TimeDate(); $datetime = $timedate->to_display_date_time($datetime_str, true, false, $diff_user); Parsing In addition to formatting, TimeDate objects can also return Date/Time values based on special parameters. The TimeDate object has many date parsing options; some of the most common ones are : parseDateRange Gets the start and end date/time from a range keyword  parseDateRange returns array Parameters Name Data Type Default Description $range string n/a String from a predetermined list of available ranges $user User null User to utilize formatting and timezone info from $adjustForTimezone boolean true Convert to user's timezone Returns an array of SugarDateTime objects containing the start and Date/Time values calculated based on the entered parameter. If no user is passed in, the current user's default will be used. If $adjustForTimezone is true the string returned will be in the passed in user's timezone. If NULL is passed in as the user, the timezone returned will be in UTC. The available values for $range are : Range String Description yesterday Yesterday's start and end date/time today Today's start and end date/time tomorrow Tomorrows's start and end date/time last_7_days Start and end date/time of the last seven days next_7_days
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/DateTime/index.html
cd5c8342db0a-7
Start and end date/time of the last seven days next_7_days Start and end date/time of the next seven days last_30_days Start and end date/time of the last thirty days next_30_days Start and end date/time of the next thirty days next_month Start and end date/time of next month last_month Start and end date/time of last month this_month Start and end date/time of the current month last_year Start and end date/time of last year this_year Start and end date/time of the current year next_year Start and end date/time of next year Example $timedate = new TimeDate($current_user); // returns today's start and end date/time in UTC $today_utcTZ = $timedate->parseDateRange("today", NULL, false); // returns today's start and end date/time in the user's timezone $today_userTZ = $timedate->parseDateRange("today", $current_user, true); Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/DateTime/index.html
40a0588ef00e-0
SugarPDF Overview An overview of SugarPDF and how it relates to TCPDF. As of version 6.7.x, Sugar includes a Smarty template engine called PDF Manager that is accessible by navigating to Admin > PDF Manager. The PDF Manager allows administrators to create and manage templates for deployed modules without having to write custom code.  The following sections are only specific to developers looking to create their own custom TCPDF templates using PHP. PDF Classes The various classes used in generating PDFs within Sugar. TCPDF Sugar uses the TCPDF 4.6.013 library, located in ./vendor/tcpdf/, as the core engine to generate PDFs. This library is extended by Sugarpdf which is used by the core application to generate PDFs.  Sugarpdf The Sugarpdf class, located in ./include/Sugarpdf/Sugarpdf.php, extends the TCPDF class. Within this class, we have overridden certain functions to integrate sugar features. Some key methods that were overridden are listed below:  Method Description Header Overridden to enable custom logos. SetFont Overridden to allow for the loading of custom fonts. The custom fonts direction is defined by the K_PATH_CUSTOM_FONTS var. By default, this value is set to ./custom/vendor/tcpdf/fonts/ Cell Overridden to apply the prepare_string() function. This allows for the ability to clean the string before sending to PDF.   Some key additional methods that were added are listed below: Method Description predisplay Preprocessing before the display method is called. Is intended to setup general PDF document properties like margin, footer, header, etc. display Performs the actual PDF content generation. This is where the logic to display output to the PDF should be placed. process
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarPDF/index.html
40a0588ef00e-1
process Calls predisplay and display. writeCellTable Method to print a table using the cell print method of TCPDF writeHTMLTable Method to print a table using the writeHTML print method of TCPDF Custom PDF classes that extend Sugarpdf can be located in the following directories: ./include/Sugarpdf/sugarpdf/sugarpdf.<pdf view>.php ./modules/<module>/sugarpdf/sugarpdf.<pdf view>.php ./custom/modules/<module>/sugarpdf/sugarpdf.<pdf view>.php PDF Manager classes that extend Sugarpdf are located in the following directories: ./include/Sugarpdf/sugarpdf/sugarpdf.smarty.php ./include/Sugarpdf/sugarpdf/sugarpdf.pdfmanager.php ./custom/include/Sugarpdf/sugarpdf/sugarpdf.pdfmanager.php Each extended class will define a specific PDF view that is accessible with the following URL parameters: module=<module> action=sugarpdf sugarpdf=<pdf view> Within each custom PDF class, the display method will need to be redefined. If you would like, It is also possible to override other methods like Header. The process method of this class will be called from ViewSugarpdf. When a PDF is being generated, the most relevant sugarpdf.<pdf action>.pdf class is determined by the SugarpdfFactory. ViewSugarpdf The ViewSugarpdf class, located in ./include/MVC/View/views/view.sugarpdf.php, is used to create the SugarViews that generate PDFs. These views can be found and/or created in one of the following directory paths: ./modules/<module>/views/view.sugarpdf.php ./custom/modules/<module>/views/view.sugarpdf.php
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarPDF/index.html
40a0588ef00e-2
./custom/modules/<module>/views/view.sugarpdf.php SugarViews can be called by navigating to a URL in the format of: http://<url>/index.php?module=<module>&action=sugarpdf&sugarpdf=<pdf action> As of 6.7, PDFs are mainly generated using the PDF Manager templating system. To generate the PDF stored in the PDF Manager, you would call a URL in the format of: http://<url>/index.php?module<module>&record=<record id>&action=sugarpdf&sugarpdf=pdfmanager&pdf_template_id=<template id>   SugarpdfFactory The ViewSugarpdf class uses the SugarpdfFactory class, located in ./include/Sugarpdf/SugarpdfFactory.php, to find the most relevant sugarpdf.<pdf action>.pdf class which generates the PDF document for a given PDF view and module. If one is not found, then the core Sugarpdf class is used. The SugarpdfFactory class loads the first class found for the specified PDF action as determined by the following order: ./custom/modules/<module>/sugarpdf/sugarpdf.<pdf view>.php ./modules/<module>/sugarpdf/sugarpdf.<pdf view>.php ./custom/include/Sugarpdf/sugarpdf/sugarpdf.<pdf view>.php ./include/Sugarpdf/sugarpdf/sugarpdf.<pdf view>.php ./include/Sugarpdf/sugarpdf.php SugarpdfHelper
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarPDF/index.html
40a0588ef00e-3
./include/Sugarpdf/sugarpdf.php SugarpdfHelper The SugarpdfHelper, located in ./include/Sugarpdf/SugarpdfHelper.php, is included by Sugarpdf. This is a utility file that contains many of the functions we use to generate PDFs. Available functions are: wrapTag, wrapTD, wrapTable, etc. : These functions help to create an HTML code. prepare_string : This function prepare a string to be ready for the PDF printing. format_number_sugarpdf : This function is a copy of format_number() from currency with a fix for sugarpdf. PdfManagerHelper The PdfManagerHelper, located in ./modules/PdfManager/PdfManagerHelper.php, is primarily utilized by the pdfmanager Sugarpdf view. This class file contains methods useful for accessing PDF Manager templates. Some of the primary methods are: getAvailableModules : Returns an array of available modules for use with PdfManager. getFields : Takes an module name and returns a list of fields and links available for this module in PdfManager. getPublishedTemplatesForModule : Returns an array of the available templates for a specific module. FontManager The FontManagerclass, located in ./include/Sugarpdf/FontManager.php, is a stand-alone class that manages all the fonts for TCPDF. More information can be found in the PDF Fonts section below. Functionality: List all the available fonts from the OOB font directory and the custom font directory (it can create a well-formatted list for select tag). Get the details of each listed font (Type, size, encoding,...) by reading the font php file. Add a new font to the custom font directory from a font file and a metric file. Delete a font from the custom font directory.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarPDF/index.html
40a0588ef00e-4
Delete a font from the custom font directory. Generating a PDF To generate a custom PDF in Sugar, you will need to create a PDF view that extends the Sugarpdf class. To accomplish this, create the file:  ./custom/modules/<module>/sugarpdf/sugarpdf.<pdf view>.php <?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); require_once('include/Sugarpdf/Sugarpdf.php'); class <module>Sugarpdf<pdf view> extends Sugarpdf { /** * Override */ function process(){ $this->preDisplay(); $this->display(); $this->buildFileName(); } /** * Custom header */ public function Header() { $this->SetFont(PDF_FONT_NAME_MAIN, 'B', 16); $this->MultiCell(0, 0, 'TCPDF Header',0,'C'); $this->drawLine(); } /** * Custom header */ public function Footer() { $this->SetFont(PDF_FONT_NAME_MAIN, '', 8); $this->MultiCell(0,0,'TCPDF Footer', 0, 'C'); } /** * Predisplay content */ function preDisplay() { //Adds a predisplay page $this->AddPage(); $this->SetFont(PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN); $this->Ln(); $this->MultiCell(0,0,'Predisplay Content',0,'C'); } /** * Main content */
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarPDF/index.html
40a0588ef00e-5
} /** * Main content */ function display() { //add a display page $this->AddPage(); $this->SetFont(PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN); $this->Ln(); $this->MultiCell(0,0,'Display Content',0,'C'); } /** * Build filename */ function buildFileName() { $this->fileName = 'example.pdf'; } /** * This method draw an horizontal line with a specific style. */ protected function drawLine() { $this->SetLineStyle(array('width' => 0.85 / $this->getScaleFactor(), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(220, 220, 220))); $this->MultiCell(0, 0, '', 'T', 0, 'C'); } } This file will contain the markup for the PDF. The main things to note are the Header(), Footer() and display() methods as they contain most of the styling and display logic. The method buildFileName() will generate the document's name when downloaded by the user. Once in place, navigate to Admin > Repair > Quick Repair and Rebuild. The PDF will now be accessible by navigating to the following url in your browser: http://{sugar url}/index.php?module=<module>&action=sugarpdf&sugarpdf=<pdf action> PDF Settings This section will outline how to configure the PDF settings. These settings determine the widths, heights, images, pdf metadata, and the UI configurations found in:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarPDF/index.html
40a0588ef00e-6
Admin > PDF Manager > Edit Report PDF Template Settings The default PDF settings for TCPDF can be found in ./include/Sugarpdf/sugarpdf_default.php. You can add additional custom settings by creating the following file: ./custom/include/Sugarpdf/sugarpdf_default.php <?php $sugarpdf_default["PDF_NEW_SETTING"] = "Value"; You should note that values specified here will be the default values. Once edited, the updated values are stored in the database config table under the category "sugarpdf" and a name matching the setting name. category: sugarpdf name: pdf_new_setting value: Value Displaying and Editing Settings A select set of settings can be edited within the Sugar UI by navigating to: Admin > PDF Manager > Edit Report PDF Template The settings here are managed in the file ./modules/Configurator/metadata/SugarpdfSettingsdefs.php. A brief description of the settings parameters are listed below: label : This is the display label for the setting. info_label : Hover info text for the display label. value : The PDF Setting. class : Determines which panel the setting resides in. Possible values are 'basic' and 'logo'. 'advanced' is not currently an available value. type : Determines the settings display widget. Possible values are: 'image', 'text', 'percent', 'multiselect', 'bool', 'password', and 'file'. Custom settings can be added to this page by creating ./custom/modules/Configurator/metadata/SugarpdfSettingsdefs.php and specifying a new setting index. An example is below: ./custom/modules/Configurator/metadata/SugarpdfSettingsdefs.php <?php //Retrieve setting info from db defineFromConfig("PDF_NEW_SETTING", $sugarpdf_default["PDF_NEW_SETTING"]);
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarPDF/index.html
40a0588ef00e-7
//Add setting display $SugarpdfSettings['sugarpdf_pdf_new_setting'] = array( "label" => $mod_strings["LBL_PDF_NEW_SETTING_TITLE"], "info_label" => $mod_strings["LBL_PDF_NEW_SETTING_INFO"], "value" => PDF_NEW_SETTING, "class" => "basic", "type" => "text", ); You should note that the $SugarpdfSettings index should following the format sugarpdf_pdf_<setting name>. If your setting does not follow this format, it will not be saved or retrieved from the database correctly. Once the setting is defined, you will need to define the display text for the UI setting. ./custom/modules/Configurator/language/en_us.lang.php Once finished, navigate to Admin > Repair > Quick Repair and Rebuild. This will rebuild the language files for your display text. PDF Fonts The stock fonts for TCPDF are stored in the directory ./vendor/tcpdf/fonts/. If you would like to add additional fonts to the system, they should be added to the ./custom/vendor/tcpdf/fonts/ directory. Font Cache The font list is built by the font manager with the listFontFiles() or getSelectFontList() methods. The list is then saved in the cache as ./cache/Sugarpdf/cachedFontList.php. This caching process prevents unnecessary parsing of the fonts folder. The font cache is automatically cleared when the delete() or add() methods are used. When you create a module loader package to install fonts you will have to call the clearCachedFile() method in a post_execute and post_uninstall action in the manifest.php to clear the font cache. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarPDF/index.html
6a48f6d4687a-0
Elastic Search Overview The focus of this document is to guide developers on how Sugar integrates with Elastic Search. Resources We recommend the following resources to get started with Elasticsearch: Elasticsearch: The Definitive Guide Elasticsearch Reference Deployment The following figure shows a typical topology of Elasticsearch with a Sugar system. All the communication with Elasticsearch goes through Sugar via REST APIs. Framework The following figure shows the overall architecture with main components in the Elasticsearch framework and related components in Sugar framework. Main Components This section describes how to use each of the main components in detail. Mapping Manager This component builds the mappings for providers in the system. The mappings are used for Elastic to interpret data stored there, which is similar to a database schema. Define the full_text_search property in a module's vardef file for a given field: enabled : sets the field to be enabled for global search; searchable : sets the field to be searchable or not; boost : sets the boost value so that the field can be ranked differently at search time. type : overrides the sugar type originally defined; aggregations : sets the properties specific related to aggregations; Define what analyzers to use for a given sugar type: The analyzers for both indexing and searching are specified. They may be different for the same field. The index analyzer is used at indexing time, while the search analyzer is used at query time. Each of the providers generates its own mapping. Generates mappings for each field and sends it over to Elasticsearch. Example Mapping This section outlines how the mapping is created for Account module's name field. The Account module's name field is defined as "searchable" in the "full_text_search" index of the vardefs. The Sugar type "name" uses the regular and ngram string analyzers for indexing and search.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Elastic_Search/index.html
6a48f6d4687a-1
./modules/Accounts/vardefs.php ... 'name' => array( 'name' => 'name', 'type' => 'name', 'dbType' => 'varchar', 'vname' => 'LBL_NAME', 'len' => 150, 'comment' => 'Name of the Company', 'unified_search' => true, 'full_text_search' => array( 'enabled' => true, 'searchable' => true, 'boost' => 1.9099999999999999, ), 'audited' => true, 'required' => true, 'importable' => 'required', 'duplicate_on_record_copy' => 'always', 'merge_filter' => 'selected', ), ... The field handler, located in ./src/Elasticsearch/Provider/GlobalSearch/Handler/Implement/MultiFieldHandler.php, defines the mappings used by Elasticsearch. The class property $typesMultiField in the MultiFieldHandler class defines the relationship between types and mappings. For the "name" type, we use the gs_string and gs_string_wildcard definitions to define our mappings and analyzers. ./src/Elasticsearch/Provider/GlobalSearch/Handler/Implement/MultiFieldHandler.php ... protected $typesMultiField = array( ... 'name' => array( 'gs_string', 'gs_string_wildcard', ), ... ); ... The class property $multiFieldDefs in the MultiFieldHandler class defines the actual Elasticsearch mapping to be used. ... protected $multiFieldDefs = [ ... /* * Default string analyzer with full word matching base ond
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Elastic_Search/index.html
6a48f6d4687a-2
... /* * Default string analyzer with full word matching base ond * the standard analyzer. This will generate hits on the full * words tokenized by the standard analyzer. */ 'gs_string' => [ 'type' => 'text', 'index' => true, 'analyzer' => 'gs_analyzer_string', 'store' => true, ], /* * String analyzer using ngrams for wildcard matching. The * weighting of the hits on this mapping are less than full * matches using the default string mapping. */ 'gs_string_wildcard' => [ 'type' => 'text', 'index' => true, 'analyzer' => 'gs_analyzer_string_ngram', 'search_analyzer' => 'gs_analyzer_string', 'store' => true, ], ... ]; ... The mapping is created from the definitions in Elasticsearch. A sample mapping is shown below: "Accounts__name": { "include_in_all": false, "index": "not_analyzed", "type": "string", "fields":{ "gs_string_wildcard":{ "index_analyzer": "gs_analyzer_string_ngram", "store": true, "search_analyzer": "gs_analyzer_string", "type": "string" }, "gs_string":{ "store": true, "analyzer": "gs_analyzer_string", "type": "string" } } } Index Manager
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Elastic_Search/index.html
6a48f6d4687a-3
"type": "string" } } } Index Manager An index includes types, similar to a database including tables. In our system, a type is based on a module consisting of mappings. As shown in the following figure, the Index Manager combines the analysis built from Analysis Builder and the mappings from Mapping Manager from different providers and organizes them by modules. Indexer & Queue Manager After creating the index, data needs to be moved from the Sugar system to Elasticsearch. The queue manager uses the  fts_queue and job_queue tables to queue the information. The indexer then processes data from Sugar bean into the format of Elasticsearch documents. The whole process is as follows: Each Sugar bean is added to fts_queue table. Elasticsearch queue scheduler is added to job_queue table. When the job starts, the scheduler generates an Elasticsearch queue consumer for each module. Each consumer queries the fts_queue table fo find the corresponding sugar beans. The indexer gets fields from each bean and processes them into individual documents. The indexer uses the bulk APIs to send documents to Elasticsearch in batches. Global Search Provider The provider supplies information to build analysis, mapping, query, etc. It is done by using handlers. Currently, there are two providers in the system: global search and visibility. To extend the functionalities, new providers and handlers may be added. The following figure shows the existing handler interfaces and some of the handlers implementing them. Query Builder The Query builder composes the query string for search. A structure of a typical multi-match query is shown as follows: { "query": { "filtered": { "query": { "bool": { "must": [{ "bool": { "should": [{ "multi_match": {
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Elastic_Search/index.html
6a48f6d4687a-4
"bool": { "should": [{ "multi_match": { "type": "cross_fields", "query": "test", "fields": [ "Cases__name.gs_string^1.53", "Cases__name.gs_string_wildcard^0.69", "Cases__description.gs_string^0.66", "Cases__description.gs_text_wildcard^0.23", "Bugs__name.gs_string^1.51", "Bugs__name.gs_string_wildcard^0.68", "Bugs__description.gs_string^0.68", "Bugs__description.gs_text_wildcard^0.24" ], "tie_breaker": 1 } }] } }, { "bool": { "should": [{ "multi_match": { "type": "cross_fields", "query": "query", "fields": [ "Cases__name.gs_string^1.53", "Cases__name.gs_string_wildcard^0.69", "Cases__description.gs_string^0.66", "Cases__description.gs_text_wildcard^0.23", "Bugs__name.gs_string^1.51", "Bugs__name.gs_string_wildcard^0.68", "Bugs__description.gs_string^0.68", "Bugs__description.gs_text_wildcard^0.24" ], "tie_breaker": 1 } }] } }] } }, "filter": { "bool": { "must": [{
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Elastic_Search/index.html
6a48f6d4687a-5
"filter": { "bool": { "must": [{ "bool": { "should": [{ "bool": { "must": [{ "term": { "_type": "Bugs" } }] } }, { "bool": { "must": [{ "term": { "_type": "Cases" } }] } }] } }] } } } }, "highlight": { "pre_tags": [ "<strong>" ], "post_tags": [ "<\/strong>" ], "require_field_match": 1, "number_of_fragments": 3, "fragment_size": 255, "encoder": "html", "order": "score", "fields": { "*.gs_string": { "type": "plain", "force_source": false }, "*.gs_string_exact": { "type": "plain", "force_source": false }, "*.gs_string_html": { "type": "plain", "force_source": false }, "*.gs_string_wildcard": { "type": "plain", "force_source": false }, "*.gs_text_wildcard": { "type": "plain", "force_source": false }, "*.gs_phone_wildcard": { "type": "plain", "force_source": false }, "*.gs_email": { "type": "plain",
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Elastic_Search/index.html
6a48f6d4687a-6
}, "*.gs_email": { "type": "plain", "force_source": false, "number_of_fragments": 0 }, "*.gs_email_wildcard": { "type": "plain", "force_source": false, "number_of_fragments": 0 } } } } Figure 7: Multi-match query with aggregations. A query may include multiple filters, post filters, queries, and settings, which can get complicated sometimes. To add new queries, we recommend adding new classes implementing QueryInterface, instead of modifying Query Builder or even calling Elastica APIs directly. ACL ACL control is done in the Query Builder. The search fields are filtered based on their ACL access levels when being added to the query string in a specific query. For instance, MultiMatchQuery used for global search may include the following filterings: If a field is owner read (i.e., SugarACL::ACL_OWNER_READ_WRITE), it will be added to a sub-query with a filter of ownerId. If a field is not owner read, its access level must not equal to SugarACL::ACL_NO_ACCESS, in order to be added as one of the search fields in the query. The corresponding function is MultiMatchQuery.php::isFieldAccessible(). Potentially this function can be shared by different queries that require ACL control. Visibility The visibility model is applied when building the query too. It is done by adding filters built by individual visibility strategies, defined in ./data/visibility/ directory. These strategies implement StrategyInterface including: building analysis, building mapping, processing document before being indexed, getting bean index fields, adding visibility filters.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Elastic_Search/index.html
6a48f6d4687a-7
processing document before being indexed, getting bean index fields, adding visibility filters. The functions are similar to the global search provider's handler interfaces. The query builder only uses adding the visibility filters, while others provide information to Analysis builder, Mapping Manager, Indexer, etc. Hence the visibility provider is separated as an independent provider in the framework. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Elastic_Search/index.html
ecd32c942174-0
Uploads Overview The upload directory is used to store files uploaded for imports, attachments, documents, and module loadable packages. Uploads The upload directory is used to store any files uploaded to Sugar. By default, anything uploaded to Sugar is stored in the ./upload/ directory. You can change this directory by updating the upload_dir configuration variable. Once uploaded, the file will be stored in this directory with a GUID name. There are several file-size limits that affect uploads to Sugar: Setting Name Location Description Default upload_max_filesize php.ini Maximum allowed size for uploaded files 2 MB post_max_size php.ini Maximum size of POST data that PHP will accept 8 MB  upload_maxsize config.php The maximum individual file size that users can upload to modules that support file uploads 30 MB max_aggregate_email_attachments_bytes config.php The maximum allowed size of all uploaded attachments added together for a single email message 10 MB The lowest of the first three values above will be respected when an oversized file is uploaded to Sugar. The first two settings are the PHP server's upload_max_filesize and post_max_size, which are configured in your system's php.ini file. The third setting is the Sugar configuration for upload_maxsize, which will restrict the upload limit from within Sugar without affecting any other applications that may be running on your server. This limit can be easily adjusted in Sugar via Admin > System Settings but is only useful if it is set to a size smaller than the php.ini limits. Finally, the max_aggregate_email_attachments_bytes setting will permit users to upload files as email attachments according to the previous size limits but restrict users from uploading more files to a single message than its configuration permits.Â
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Uploads/index.html
ecd32c942174-1
Note: PHP-defined file size settings and the upload directory cannot be modified for instances hosted on Sugar's cloud service. Upload Extensions By default, several extension types are restricted due to security issues. Any files uploaded with these extensions will have '.txt' appended to it. The restricted extensions are listed below: php php3 php4 php5 pl cgi py asp cfm js vbs html htm You can add or remove extensions to this list by modifying sugar configuration setting for upload_badext. You should note that this setting cannot be modified for instances hosted on Sugar's cloud service. How Files Are Stored Note Attachments When a file is uploaded to Sugar attached to a note, the file will be moved to the upload directory with a GUID name matching that of the notes id. The attributes of the file, such as filename and file_mime_type, will be stored in the note record. The SQL to fetch information about a notes attachment is shown below: SELECT filename, file_mime_type FROM notes; Email Attachments Email attachments are stored the same way as note attachments. When an email is imported to Sugar, the file will be moved to the upload directory with a GUID file name matching that of the notes id. The attributes of the file, such as filename and file_mime_type, will be stored in the note record and the note will have a parent_type of 'Emails'. This relates the attachment to the content of the email. The SQL to fetch information about an emails attachment is shown below: SELECT filename, file_mime_type FROM notes INNER JOIN emails ON notes.parent_type = 'Emails' AND notes.parent_id = emails.id INNER JOIN emails_text ON emails.id = emails_text.email_id; Picture Fields
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Uploads/index.html
ecd32c942174-2
Picture Fields Picture fields will upload the image to the upload directory with a GUID name and store the GUID in the database field on the record. An example of picture field can be found on the Contacts module. For a contact, the id of the picture attachment can be found with the SQL below: SELECT picture FROM contacts; Knowledge Base Attachments When working with the Knowledge Base, files and images attached to the form will be created as a record in the /#EmbeddedFiles module. These files will be stored as <GUID> of EmbbededFiles record in the upload folder.All other file enclosed to attachments field of KBContents will be also saved as Notes record in the upload folder. The SQL to fetch information about a knowledge base attachment is shown below: select kb.id, kb.name, kb.revision, n.filename, n.file_mime_type, n.file_ext from notes n, kbcontents kb where n.parent_type = "KBContents" and n.parent_id = kb.id order by kb.name, kb.revision; Module Loadable Packages Module Loader packages are stored in the system differently than other uploads. They are uploaded to the ./upgrades/module directory, each uploaded file is now stored in a subdirectory derived from the UUID filename. Existing files will be moved into subdirectories during upgrade. For example, the file 3657325a-bdd6-11eb-9a6c-08002723a3b8 will now be stored in the ./upload/25a/ subdirectory. These UID character locations were selected to ensure even distribution of files across the new subdirectories. The details of the package, such as installation status and description, are stored in the upgrade_history table. The SQL to fetch information about an installed package is shown below: SELECT * FROM upgrade_history; CSV Imports
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Uploads/index.html
ecd32c942174-3
SELECT * FROM upgrade_history; CSV Imports When importing records into Sugar, the most recent uploaded CSV file is stored in the upload directory as IMPORT_<module>_<user id>. Once the import has been run, the results of the import are stored in ./upload/import/ directory using a predefined format using the current user's id. The files created will be as follows: dupes_<user id>.csv : The list of duplicate records found during the import dupesdisplay_<user_id>.csv : The HTML formatted CSV for display to the user after import error_<user id>.csv : The list of errors encountered during the import errorrecords_<user_id>.csv : The HTML formatted CSV for display to the user after import errorrecordsonly_<user id>.csv : The list of records that encountered an error status_<user id>.csv : Determines the status of the users import TopicsWorking with File UploadsThe UploadFile class handles the various tasks when uploading a file. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Uploads/index.html
b990a25ed0f1-0
Working with File Uploads Overview The UploadFile class handles the various tasks when uploading a file. Retrieving a Files Upload Location To retrieve a files upload path, you can use the get_upload_path method and pass in the file's GUID id. require_once 'include/upload_file.php'; UploadFile::get_upload_path($file_id); This method will normally return the path as: upload://1d0fd9cc-02e5-f6cd-1426-51a509a63334 Retrieving a Files Full File System Location To retrieve a files full system path, you can use the get_upload_path and real_path methods as shown below: require_once 'include/upload_file.php'; UploadFile::realpath(UploadFile::get_upload_path($file_id)); This method will normally return the path where they are uploaded to. Each uploaded file is now stored in a subdirectory derived from the UUID filename. Existing files will be moved into subdirectories during upgrade. For example, the file 3657325a-bdd6-11eb-9a6c-08002723a3b8 will now be stored in the ./upload/25a/ subdirectory. These UID character locations were selected to ensure even distribution of files across the new subdirectories. Retrieving a Files Contents As an alternative to using file_get_contents or sugar_file_get_contents, you can retrieve the contents of a file using the get_file_contents method as shown below: require_once 'include/upload_file.php'; $file = new UploadFile(); //get the file location $file->temp_file_location = UploadFile::get_upload_path($file_id); $file_contents = $file->get_file_contents(); Duplicating a File
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Uploads/UploadFile/index.html
b990a25ed0f1-1
$file_contents = $file->get_file_contents(); Duplicating a File To duplicate an uploaded file, you can use the duplicate_file method by passing in the files current id and the id you would like it copied to as shown below: require_once 'include/upload_file.php'; $uploadFile = new UploadFile(); $result = $uploadFile->duplicate_file($oldFileId, $newFileId); Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Uploads/UploadFile/index.html
3178a93c1057-0
This page refers to beta functionality. Please be advised that the content of this page is subject to change. CLI Overview Sugar on-premise deployments include a command line interface tool built using the Symfony Console Framework. Sugar's CLI is intended to be an administrator or developer level power tool to execute PHP code in the context of Sugar's code base. These commands are version specific and can be executed on a preinstalled Sugar instance or on an installed Sugar instance. Sugar's CLI is not intended to be used as a tool to interact remotely with an instance nor is it designed to interact with multiple instances.  Commands Sugar Commands are an implementation of Console Commands. They extend the base console classes to execute Sugar specific actions. Each instance of Sugar is shipped with a list of predefined commands. The current list of commands is shown below. Command Description help Displays help for a command list Lists commands aclcache:dump Dumps ACL cache contents into cache/acldumps folder elastic:explain Execute global search explain queries for debugging purposes. As this will generate a lot of output in JSON format, it is recommended to redirect the output to a file for later processing elastic:indices Show Elasticsearch index statistics elastic:queue Show Elasticsearch queue statistics elastic:queue_cleanup Cleanup records from Elasticsearch queue elastic:refresh_enable Enable refresh on all indices elastic:refresh_status Show Elasticsearch index refresh status elastic:refresh_trigger Perform a manual refresh on all indices elastic:replicas_enable Enable replicas on all indices elastic:replicas_status Show Elasticsearch index refresh status elastic:routing Show Elasticsearch index routing idm-mode:manage enable, disable IDM mode, or move config data to DB password:config Show password hash configuration password:reset Reset user password for local user authentication password:weak
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/CLI/index.html
3178a93c1057-1
password:reset Reset user password for local user authentication password:weak Show users having weak or non-compliant password hashes search:fields Show search engine enabled fields search:module Enable/disable given module for search search:reindex Schedule SearchEngine reindex search:silent_reindex Create mappings and index the data search:silent_reindex_mp Create mappings and index the data using multi-processing search:status Show search engine availability and enabled modules team-security:rebuild Rebuild denormalized team security data team-security:status Display the status of the denormalized data teamset:backup Backs up the team_sets related tables teamset:prune Prune all team set tables of unused team sets. Original tables will be backed up automatically. DO NOT USE while users are logged into the system teamset:restore_from_backup Restores all team set tables from backups. DO NOT USE while users are logged into the system teamset:scan Scan all module tables for unused team sets and report the number found teamset:sql Print the sql query used to search for unused teamsets Note : For advanced users, a bash autocompletion script for CLI is located at ./src/Console/Resources/sugarcrm-bash-completion for inclusion in  ~/.bashrc. More details on using the script can be found in the file's header comments. Usage The command executable, located at ./bin/sugarcrm, is executed from the root of the Sugar instance. The command signature is shown below: php bin/sugarcrm <command> [options] [arguments] Help The command console has built-in help documentation. If you pass in a command that isn't found, you will be shown the default help documentation.  SugarCRM Console version <version> Usage:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/CLI/index.html
3178a93c1057-2
SugarCRM Console version <version> Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug Available commands: help Displays help for a command list Lists commands aclcache aclcache:dump Dumps ACL cache contents into cache/acldumps folder. elastic elastic:explain Execute global search explain queries for debugging purposes. As this will generate a lot of output in JSON format, it is recommended to redirect the output to a file for later processing. elastic:indices Show Elasticsearch index statistics elastic:queue Show Elasticsearch queue statistics elastic:queue_cleanup Cleanup records from Elasticsearch queue. elastic:refresh_enable Enable refresh on all indices elastic:refresh_status Show Elasticsearch index refresh status elastic:refresh_trigger Perform a manual refresh on all indices elastic:replicas_enable Enable replicas on all indices elastic:replicas_status Show Elasticsearch index refresh status elastic:routing Show Elasticsearch index routing idm-mode idm-mode:manage enable, disable IDM mode, or move config data to DB password password:config Show password hash configuration password:reset Reset user password for local user authentication. password:weak Show users having weak or non-compliant password hashes search
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/CLI/index.html
3178a93c1057-3
password:weak Show users having weak or non-compliant password hashes search search:fields Show search engine enabled fields search:module Enable/disable given module for search search:reindex Create mappings and schedule a reindex search:silent_reindex Create mappings and index the data search:silent_reindex_mp Create mappings and index the data using multi-processing search:status Show search engine availability and enabled modules team-security team-security:rebuild Rebuild denormalized team security data team-security:status Display the status of the denormalized data teamset teamset:backup Backs up the team_sets related tables. teamset:prune Prune all team set tables of unused team sets. Original tables will be backed up automatically. DO NOT USE while users are logged into the system! teamset:restore_from_backup Restores all team set tables from backups. DO NOT USE while users are logged into the system! teamset:scan Scan all module tables for unused team sets and report the number found. teamset:sql Print the sql query used to search for unused teamsets  Additional help documentation is also available for individual commands. Some examples of accessing the help are shown below.  Passing the word "help" before a command name: php bin/sugarcrm help <command> Passing the "-h" option: php bin/sugarcrm <command> -h An example of the list help documentation is shown below. Usage: list [options] [--] [] Arguments: namespace The namespace name Options: --xml To output list as XML --raw To output raw command list
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/CLI/index.html
3178a93c1057-4
--xml To output list as XML --raw To output raw command list --format=FORMAT The output format (txt, xml, json, or md) [default: "txt"] Help: The list command lists all commands: php bin/sugarcrm list You can also display the commands for a specific namespace: php bin/sugarcrm list test You can also output the information in other formats by using the --format option: php bin/sugarcrm list --format=xml It's also possible to get raw list of commands (useful for embedding command runner): php bin/sugarcrm list --raw Custom Commands Sugar allows developers the ability to create custom commands. These commands are registered using the Extension Framework. Each custom command will extend the stock Command class and implement a specific mode interface. The file system location of the command code can exist anywhere in the instance's file system including a separate composer loaded repository.  Best Practices The following are some common best practices developers should keep in mind when adding new commands : Do not extend from existing commands Do not duplicate an already existing command Pick the correct mode for the command Limit the logic in the command Do not put reusable components in the command itself Each command requires specific sections of code in order to properly create the command. These requirements are listed in the sections below. Command Namespace It is recommended to name any custom commands using a proper "command namespace". These namespaces are different than PHP namespaces and reduce the chances of collisions occurring between vendors. An example of this would be to prefix any commands with a namespace format of vendor:category:command E.g. MyDevShop:repairs:fixMyModule Note : The CLI framework does not allow overriding of existing commands. PHP Namespace
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/CLI/index.html
3178a93c1057-5
Note : The CLI framework does not allow overriding of existing commands. PHP Namespace The header of the PHP command file will need to define the following namespace: namespace Sugarcrm\Sugarcrm\custom\Console\Command; In addition to the namespace, the following use commands are required for different operations : Name Description Example Command Every command will extend the Command class use Symfony\Component\Console\Command\Command; Mode Whether the command is an Instance or Standalone Mode command use Sugarcrm\Sugarcrm\Console\CommandRegistry\Mode\InstanceModeInterface; use Sugarcrm\Sugarcrm\Console\CommandRegistry\Mode\StandaloneModeInterface; Input Accepts Input from the command use Symfony\Component\Console\Input\InputInterface; Output Sends Output from the command use Symfony\Component\Console\Output\OutputInterface; Mode When creating Sugar commands, developers will need to specify the mode or set of modes for the command. These modes help prepare the appropriate resources for execution of the command.  Mode Description Instance Mode  Commands that require an installed Sugar instance. Standalone Mode  Commands that do not require an installed Sugar instance. Note : Multiple modes can be selected. Class Definition The custom command class definition should extend the stock command class as well as implement a mode's interface.  // Instance Mode Class Definition class <classname> extends Command implements InstanceModeInterface { //protected methods } // Standalone Mode Class Definition class <classname> extends Command implements StandaloneModeInterface { //protected methods } // Implementing both Modes class <classname> extends Command implements InstanceModeInterface, StandaloneModeInterface { //protected methods } Methods Each command class implements two protected methods : Method Description configure()
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/CLI/index.html
3178a93c1057-6
Methods Each command class implements two protected methods : Method Description configure()  Runs on the creation of the command. Useful to set the name, description, and help on the command. execute(InputInterface $input, OutputInterface $output)  The code to run for executing the command. Accepts an input and output parameter.  An example of implementing the protected methods is shown below: protected function configure() { $this->setName('sugardev:helloworld') ->setDescription('Hello World') ->setHelp('This command accepts no paramters and returns "Hello World".') ; } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln("Hello world -> " . $this->getApplication()->getMode()); } Registering Command After creating the custom command file, register it with the Extension Framework. This file will be located in ./custom/Extension/application/Ext/Console/. An example of registering a command is below: <?php Sugarcrm\Sugarcrm\Console\CommandRegistry\CommandRegistry::getInstance() ->addCommand(new Sugarcrm\Sugarcrm\custom\Console\Command\<Command Class Name>()); Next, navigate to Admin > Repair > Quick Repair and Rebuild. The custom command will now be available. Example The following sections demonstrate how to create a "Hello World" example. This command does not alter the Sugar system and will only output display text. First, create the command class under the appropriate namespace. ./custom/src/Console/Command/HelloWorldCommand.php <?php namespace Sugarcrm\Sugarcrm\custom\Console\Command; use Sugarcrm\Sugarcrm\Console\CommandRegistry\Mode\InstanceModeInterface; use Symfony\Component\Console\Command\Command;
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/CLI/index.html
3178a93c1057-7
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * * Hello World Example * */ class HelloWorldCommand extends Command implements InstanceModeInterface { protected function configure() { $this ->setName('sugardev:helloworld') ->setDescription('Hello World') ->setHelp('This command accepts no paramters and returns "Hello World".') ; } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln("Hello world -> " . $this->getApplication()->getMode()); } } Next, register the new command: ./custom/Extension/application/Ext/Console/RegisterHelloWorldCommand.php <?php // Register HelloWorldCommand Sugarcrm\Sugarcrm\Console\CommandRegistry\CommandRegistry::getInstance() ->addCommand(new Sugarcrm\Sugarcrm\custom\Console\Command\HelloWorldCommand()); Navigate to Admin > Repair > Quick Repair and Rebuild. The new command will be executable from the root of the Sugar instance. It can be executed by running the following command: php bin/sugarcrm sugardev:helloworld  Result: Hello world -> InstanceMode Help text can be displayed by executing the following command:  php bin/sugarcrm help sugardev:helloworld  Result: Usage: sugardev:helloworld Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/CLI/index.html
3178a93c1057-8
-n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug Help: This command accepts no paramters and returns "Hello World". Download the module loadable example package here. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/CLI/index.html
928f09927ca8-0
SugarBPM Introduction SugarBPM™ automation suite is the next-generation workflow management tool for Sugar. Introduced in 7.6, SugarBPM is loosely based on BPMN process notation standards and provides a simple drag-and-drop user interface along with an intelligent flow designer to allow for the creation of easy yet powerful process definitions. Note: SugarBPM™ is not available for Sugar Professional. SugarBPM enables administrators to streamline common business processes by managing approvals, sales processes, call triaging, and more. The easy-to-use workflow tool adds advanced BPM functionality to the core Sugar software stack. A business process is a set of logically related tasks that are performed in order to achieve a specific organizational goal. It presents all of the tasks that must be completed in a simplified and streamlined format. SugarBPM empowers Sugar administrators, allowing for the automation of vital business processes for their organization. The SugarBPM automation suite features an extensive toolbox of modules that provide the ability to easily create digital forms and map out fully functioning workflows. SugarBPM Modules SugarBPM is broken down into four distinct modules, each with its own area of responsibility. Three of the four SugarBPM modules have access control settings that restrict its visibility to System Administrators, Module Administrators, and Module Developers. Process Definitions A process definition defines the steps in an overall business process. Process definitions are created by either a Sugar administrator, a module Administrator or a module Developer. The process definition consists of a collection of activities and their relationships, criteria to indicate the start and end of the process, and information about the individual activities (e.g., participants) contained within the business process. Business Rules
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/index.html
928f09927ca8-1
Business Rules A business rule is a reusable set of conditions and outcomes that can be embedded in a process definition. The set of rules may enforce business policy, make a decision, or infer new data from existing data. For example, if Sally manages all business opportunities of $10,000 or more, and Chris manages all business opportunities under $10,000, a business rule can be created and used by all relevant process definitions based on the same target module to ensure that the assignment policy is respected. In the case of an eventual personnel change, only the business rule will need to be edited to affect all related processes. Email Templates A process email template is required in order to include a Send Message event in a process definition. The SugarCRM core product includes several places where email templates can be created for different purposes, but SugarBPM requires all sent messages to be created via the Process Email Templates module. Processes A process is a running instance of a process definition. A single process begins every time a process definition meeting certain criteria is executed. For example, a single process definition could be created to automate quote approvals, but because users may engage in several quote approvals per day, each approval will be represented by a separate process instance, all governed by the single process definition. Database Tables Information surrounding various portions of SugarBPM can be found in the following SugarBPM database tables: Table name Description pmse_bpm_access_management This table is not used. pmse_bpm_activity_definition Holds definition data for an activity. Maps directly to the pmse_bpmn_activity table and may, in the future, be merged with the pmse_bpmn_activity table to prevent forked data backends. pmse_bpm_activity_step This table is not used. pmse_bpm_activity_user This table is not used. pmse_bpm_config This table is not used.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/index.html
928f09927ca8-2
This table is not used. pmse_bpm_config This table is not used. pmse_bpm_dynamic_forms Holds module specific form information - basically viewdefs for a module - for a process. pmse_bpm_event_definition Holds definition data for an event. Maps directly to the pmse_bpmn_event table and may, in the future, be merged with the pmse_bpmn_event table to prevent forked data backends. pmse_bpm_flow Holds information about triggered process flows as well as state of any process that is currently running. pmse_bpm_form_action Holds information about a process that has been acted upon. pmse_bpm_gateway_definition Holds definition data for a gateway. Maps directly to the pmse_bpmn_event table and may, in the future, be merged with the pmse_bpmn_gateway table to prevent forked data backends. pmse_bpm_group This table is not used. pmse_bpm_group_user This table is not used. pmse_bpm_notes Holds notes saved for a process record. pmse_bpm_process_definition Holds definition data for a process definition. Maps directly to the pmse_bpmn_process table and may, in the future, be merged with the pmse_bpmn_process table to prevent forked data backends. pmse_bpm_related_dependency Holds information about dependencies related to an event pmse_bpm_thread Holds information related to process threads for running processes. pmse_bpmn_activity Please see pmse_bpm_activity_definition pmse_bpmn_artifact Holds BPM artifact information, like Comments on a process diagram. At present, SugarBPM only supports the text annotation artifact. pmse_bpmn_bound
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/index.html
928f09927ca8-3
pmse_bpmn_bound Data related to element boundaries on the diagram.  pmse_bpmn_data This table is not used. pmse_bpmn_diagram Data related to a process definition's diagram.  pmse_bpmn_documentation This table is not used. pmse_bpmn_event Please see pmse_bpm_event_definition pmse_bpmn_extension This table is not used. pmse_bpmn_flow Holds information about the connecting flows of a diagram. pmse_bpmn_gateway Please see pmse_bpm_gateway_definition pmse_bpmn_lane This table is not used. pmse_bpmn_laneset This table is not used. pmse_bpmn_participant This table is not used. pmse_bpmn_process Please see pmse_bpm_process_definition pmse_business_rules Holds business rule record data. pmse_emails_templates Holds email template record data. pmse_inbox Holds information about processes that are currently running or that have completed. pmse_project Holds process definition record information. Relationships The following Entity Relationship Diagram highlights the relationships between the various SugarBPM tables. -Relationships" width="1654" recordid="e3710de4-b5b1-11e6-a3de-005056bc231a" style="width: nullpx; height: NaNpx;" /> Flows When a process definition is created the following 5 tables get populated: pmse_bpm_dynamic_forms contains dyn_view_defs which is the JSON encoded string of module-specific form information pmse_bpm_process_definition contains the module associated with and the status of a process definition
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/index.html
928f09927ca8-4
pmse_bpmn_diagram contains process definition name as well and a diagram uid pmse_bpmn_process contains process definition name. The same Id is shared between pmse_bpm_process_definition and pmse_bpmn_process dia_id is a foreign key related to pmse_bpmn_diagram pmse_project contains process definition name, project id, module, status. Other tables have a foreign key of prj_id in them. Upon adding a start/end/send message event: pmse_bpmn_event contains event name pmse_bpm_event_definition Shares id with pmse_bpmn_event pmse_bpmn_bound When Settings is changed to "New Records Only" pmse_bpm_related_dependency Upon adding an action or activity: pmse_bpm_activity_definition contains the action name The act_fields column contains the JSON encoded list of fields which will be changed pmse_bpm_activity contains action name. Shares id with pmse_bpm_activity_definition. act_script_type contains the type of action e.g. CHANGE_FIELD pmse_bpmn_bound Upon adding a connector between start event and action: pmse_bpmn_flow contains origin and destination info Upon adding a Gateway: pmse_bpm_gateway_definition pmse_bpm_gateway shares id with pmse_bpm_gateway_definition pmse_bpmn_flow flo_condition contains JSON encoded string of conditions required to proceed ahead with an action or activity pmse_bpmn_bound When a process runs: pmse_inbox cas_status indicates the status of a process pmse_bpm_thread pmse_bpm_flow Stores the entire flow that the process elements went through (so if 3 elements and 2 connectors are in the process definition then 5 records will exist) After Process has run and appears in Process Management:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/index.html
928f09927ca8-5
After Process has run and appears in Process Management: pmse_bpm_case_data pmse_bpm_form_action contains frm_action,  cas_pre_data , and cas_data Add a comment: pmse_bpmn_artifact contains the comment pmse_bpm_bound Add a business rule to a process definition: pmse_business_rules rst_source_definition contains the conditions of the business rule pmse_bpm_activity_definition act_fields contains the business rule id Add an email template to a process definition: pmse_email_templates pmse_bpm_event_definition evn_criteria contains the email template id Extension and Customization In Sugar 7.8, Sugar introduced the Process Manager library to support extending SugarBPM in an upgrade-safe way. For more information on extending SugarBPM, or on using the Process Manager library, please read the Process Manager documentation. Caveats In Sugar 7.8, the Process Manager library brought Registry Object to maintain the state of SugarBPM processes during a PHP Process. This change introduced a limitation in SugarBPM that prevents the same process definition from running on multiple records inside the same PHP process. For certain customizations in Sugar, if you are updating multiple records in a module using SugarBean, you may want them to trigger the defined process definitions for each record. The following code can be added to your customization to allow for that functionality: use Sugarcrm\Sugarcrm\ProcessManager\Registry; //custom code Registry\Registry::getInstance()->drop('triggered_starts'); $bean->save(); The 'triggered_starts' registry contains the Start Event IDs that have been triggered previously in the PHP process, thus allowing the SugarBean::save() method to trigger SugarBPM and go through the same Start Event again.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/index.html
928f09927ca8-6
TopicsExtending SugarBPM (Process Manager)From its earliest version, Sugar has been a tool that allows for customizing and extending in a way that allows developers to shape and mold it to a specific business need. Most components of Sugar are customizable or extensible through the use of custom classes (for custom functionality) or extensions (for custom metadata). However, a recent addition to the product, the SugarBPM™ automation suite, did not fit this paradigm. In response, the Process Manager Library was introduced to give developers the ability to customize any portion of SugarBPM where object instantiation was previously handled using the 'new' operator. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/index.html
cc8f8fa74e39-0
Extending SugarBPM (Process Manager) Introduction From its earliest version, Sugar has been a tool that allows for customizing and extending in a way that allows developers to shape and mold it to a specific business need. Most components of Sugar are customizable or extensible through the use of custom classes (for custom functionality) or extensions (for custom metadata). However, a recent addition to the product, the SugarBPM™ automation suite, did not fit this paradigm. In response, the Process Manager Library was introduced to give developers the ability to customize any portion of SugarBPM where object instantiation was previously handled using the 'new' operator.  Note: SugarBPM™ is not available in Sugar Professional. For an introduction to the SugarBPM modules and architecture, please refer to the SugarBPM documentation in this guide. Process Manager By way of ProcessManager\Factory we can now develop custom versions of most any PMSE* class and have that class used in place of the core PMSE* class. Limitations The current implementation of the Process Manager Library only handles server-side customizations by way of the Factory class. These customizations can be applied to any instantiable pmse_* object, however, static classes and singleton classes, such as the following, are not affected by the library: PMSE PMSEEngineUtils PMSELogger While some effort has been made to allow for the creation of custom actions in the Process Definition designer, as of Sugar 7.8, that is the only client customization allowance that will be implemented. Library Structure The Process Manager Library is placed under the Sugarcrm\Sugarcrm\ProcessManager namespace and contains the following directories and classes: Factory Exception/ BaseException DateTimeException ExceptionInterface ExecutionException InvalidDataException NotAuthorizedException RuntimeException Field/ Evaluator/ AbstractEvaluator Base Currency
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/Extending_SugarBPM/index.html
cc8f8fa74e39-1
NotAuthorizedException RuntimeException Field/ Evaluator/ AbstractEvaluator Base Currency Datetime Decimal EvaluatorInterface Int Multienum Relate Registry/ Registry RegistryInterface Examples Getting a SugarBPM object Almost all objects in SugarBPM can be instantiated through the Process Manager Factory. When loading a class, the Factory getPMSEObject method will look in the following directories as well as the custom versions of these directories for files that match the object name being loaded: modules/pmse_Business_Rules/ modules/pmse_Business_Rules/clients/base/api/ modules/pmse_Emails_Templates/ modules/pmse_Emails_Templates/clients/base/api/ modules/pmse_Inbox/clients/base/api/ modules/pmse_Inbox/engine/ modules/pmse_Inbox/engine/parser/ modules/pmse_Inbox/engine/PMSEElements/ modules/pmse_Inbox/engine/PMSEHandlers/ modules/pmse_Inbox/engine/PMSEPreProcessor/ modules/pmse_Inbox/engine/wrappers/ modules/pmse_Project/clients/base/api/ modules/pmse_Project/clients/base/api/wrappers/ modules/pmse_Project/clients/base/api/wrappers/PMSEObservers/ What this means is that virtually any class that is found by name in these directories can be instantiated and returned via the getPMSEObject() method. This also means that customizations to any of these classes can be easily implemented by creating a Custom version of the class under the appropriate ./custom directory path.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/Extending_SugarBPM/index.html
cc8f8fa74e39-2
For example, to create a custom version of PMSEProjectWrapper, you would create a CustomPMSEProjectWrapper class at  ./custom/modules/pmse_Project/clients/base/api/wrappers/CustomPMSEProjectWrapper.php. This allows you to have full control of your instance of SugarBPM while giving you the flexibility to add any classes you want and consuming them through the factory. ./custom/modules/pmse_Project/clients/base/api/wrappers/CustomPMSEProjectWrapper.php <?php require_once 'modules/pmse_Project/clients/base/api/wrappers/PMSEProjectWrapper.php'; class CustomPMSEProjectWrapper extends PMSEProjectWrapper { } This can now be consumed by simply calling the getPMSEObject() method: <?php // Set the process manager library namespace use \Sugarcrm\Sugarcrm\ProcessManager\Factory; // Get our wrapper $wrapper = ProcessManager\Factory::getPMSEObject('PMSEProjectWrapper'); Getting a SugarBPM Element Object Element objects in SugarBPM generally represent some part of the Process engine, and often time map to design elements. All Element objects can be found in the modules/pmse_Inbox/engine/PMSEElements/ directory. Getting a SugarBPM Element object can be done easily by calling the getElement() method of the Process Manager Factory: <?php use \Sugarcrm\Sugarcrm\ProcessManager\Factory; // Get a default PMSEElement object $element = ProcessManager\Factory::getElement(); To get a specific object, you can pass the object name to the getElement() method: $activity = ProcessManager\Factory::getElement('PMSEActivity'); Alternatively, you can remove the PMSE prefix and call the method with just the element name: $gateway = ProcessManager\Factory::getElement('Gateway');
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/Extending_SugarBPM/index.html
cc8f8fa74e39-3
$gateway = ProcessManager\Factory::getElement('Gateway'); To create a custom SugarBPM Element, you can simply create a new file at ./custom/modules/pmse_Inbox/engine/PMSEElements/ where the file name is prefixed with Custom. ./custom/modules/pmse_Inbox/engine/PMSEElements/CustomPMSEScriptTask.php <?php require_once 'modules/pmse_Inbox/engine/PMSEElements/PMSEScriptTask.php'; use Sugarcrm\Sugarcrm\ProcessManager; class CustomPMSEScriptTask extends PMSEScriptTask { } Note: All SugarBPM Element classes must implement the PMSERunnable interface. Failure to implement this interface will result in an exception when using the Factory to get an Element object. To get a custom ScriptTask object via the Factory, just call getElement(): $obj = ProcessManager\Factory::getElement('ScriptTask'); To make your own custom widget element, you can implement the PMSERunnable interface: ./custom/modules/pmse_Inbox/engine/PMSEElements/CustomPMSEWidget.php <?php require_once 'modules/pmse_Inbox/engine/PMSEElements/PMSERunnable.php'; use Sugarcrm\Sugarcrm\ProcessManager; class CustomPMSEWidget implements PMSERunnable { } To get a Widget object via the Factory, just call getElement(): $obj = ProcessManager\Factory::getElement('Widget'); Getting and Using a Process Manager Field Evaluator Object Process Manager Field Evaluator objects determine if a field on a record has changed and if a field on a record is empty according to the field type. The purpose of these classes can grow to include more functionality in the future. Getting a field evaluator object is also done through the Factory: <?php use \Sugarcrm\Sugarcrm\ProcessManager\Factory;
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/Extending_SugarBPM/index.html
cc8f8fa74e39-4
<?php use \Sugarcrm\Sugarcrm\ProcessManager\Factory; // Get a Datetime Evaluator. Type can be date, time, datetime or datetimecombo $eval = ProcessManager\Factory::getFieldEvaluator(['type' => 'date']); A more common way of getting a field evaluator object is to pass the field definitions for a field on a SugarBean into the Factory: $eval = ProcessManager\Factory::getFieldEvaluator($bean ->field_defs[$field]); $eval = ProcessManager\Factory::getFieldEvaluator($bean ->field_defs[$field]); Once the evaluator object is fetched, you may initialize it with properties: /* This is commonly used for field change evaluations */ // $bean is a SugarBean object // $field is the name of the field being evaluated // $data is an array of data that is used in the evaluation $eval ->init($bean, $field, $data); // Has the field changed? $changed = $eval->hasChanged();   Or you can set properties onto the evaluator: /* This is commonly used for empty evaluations */ // Set the bean onto the evaluator $eval->setBean($bean); // And set the name onto the evaluator $eval->setName($field); // Are we empty? $isEmpty = $eval->isEmpty(); Creating and consuming a custom field evaluator is as easy as creating a custom class and extending the Base class: ./custom/src/ProcessManager/Field/Evaluator/CustomWidget.php <?php namespace Sugarcrm\Sugarcrm\ProcessManager\Field\Evaluator; /** * Custom widget field evaluator * @package ProcessManager */ class CustomWidget extends Base { } Â
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/Extending_SugarBPM/index.html
cc8f8fa74e39-5
*/ class CustomWidget extends Base { }   Alternatively, you can create a custom evaluator that extends the AbstractEvaluator parent class if you implement the EvaluatorInterface interface. ./custom/src/ProcessManager/Field/Evaluator/CustomWidget.php <?php namespace Sugarcrm\Sugarcrm\ProcessManager\Field\Evaluator; /** * Custom widget field evaluator * @package ProcessManager */ class CustomWidget extends AbstractEvaluator implements EvaluatorInterface { } And at this point, you can use the Factory to get your widget object: // Get a custom widget evaluator object $eval = ProcessManager\Factory::getFieldEvaluator(['type' => 'widget']); Getting an Exception Object with Logging Getting a SugarBPM exception with logging is as easy as calling a single Factory method. Currently, the Process Manager library supports the following exception types: DateTime Execution InvalidData NotAuthorized Runtime As a fallback, the Base exception can be used. All exceptions log their message to the PMSE log when created, and all exceptions implement ExceptionInterface. The most basic way to get a ProcessManager exception is to call the getException() method on the Factory with no arguments: <?php use \Sugarcrm\Sugarcrm\ProcessManager\Factory; // Get a BaseException object, with a default message // of 'An unknown Process Manager exception had occurred' $exception = ProcessManager\Factory::getException();   To get a particular type of exception, or to set your message, you can add the first two arguments: if ($error) { throw ProcessManager\Factory::getException('InvalidData', $error); } It is possible to set an exception code, as well as a previous exception, when creating an Exception object: // Assume $previous is an ExecutionException
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/Extending_SugarBPM/index.html
cc8f8fa74e39-6
// Assume $previous is an ExecutionException throw ProcessManager\Factory ::getException('Runtime', 'Cannot carry out the action', 255, $previous); Finally, to create your own custom exception classes, you must add a new custom file in the following path with the file named appropriately: ./custom/src/ProcessManager/Exception/CustomEvaluatorException.php <?php namespace Sugarcrm\Sugarcrm\ProcessManager\Exception; /** * Custom Evaluator exception * @package ProcessManager */ class CustomEvaluatorException extends BaseException implements ExceptionInterface { } And to consume this custom exception, call the Factory: $exception = ProcessManager\Factory::getException('Evaluator', 'Could not evaluate the expression'); Maintaining State Throughout a Process The Registry class implements the RegistryInterface which exposes the following public methods: set($key, $value, $override = false) get($key, $default = null) has($key) drop($key) getChanges($key) reset() To use the Registry class, simply use the namespace to get the singleton: <?php use \Sugarcrm\Sugarcrm\ProcessManager\Registry; $registry = Registry\Registry::getInstance(); To set a value into the registry, simply add it along with a key: $registry->set('reg_key', 'Hold on to this'); NOTE: To prevent named index collision, it is advisable to write indexes to contain a namespace indicator, such as a prefix. $registry->set('mykeyindex:reg_key', 'Hold on to this'); Once a value is set in the registry, it is immutable unless the set($key, $value, $override = false) method is called with the override argument set to true: // Sets the reg_key value
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/Extending_SugarBPM/index.html
cc8f8fa74e39-7
// Sets the reg_key value $registry->set('reg_key', 'Hold on to this'); // Since the registry key reg_key is already set, this will do nothing $registry->set('reg_key', 'No wait!'); // To forcefully set it, add a true for the third argument $registry->set('reg_key', 'No wait!', true); When a key is changed on the registry, these changes are logged and can be inspected using getChanges(): // Set and reset a value on the registry $registry->set('key', 'Foo'); $registry->set('key', 'Bar', true); $registry->set('key', 'Baz', true); // Get the changes for this key $changes = $registry ->getChanges('key'); /* $changes will be: array( 0 => array( 'from' => 'Foo', 'to' => 'Bar', ), 1 => array( 'from' => 'Bar', 'to' => 'Baz', ), */ To get the value of the key you just set, call the get() method: $value = $registry->get('reg_key'); To get a value of a key with a default, you can pass the default value as the second argument to get(): // Will return either the value for attendee_count or 0 $count = $registry->get('attendee_count', 0); To see if the registry currently holds a value, call the has() method: if ($registry->has('field_list')) { // Do something here } To remove a value from the registry, use the drop() method. This will add an entry to the changelog, provided the key was already set.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/Extending_SugarBPM/index.html
cc8f8fa74e39-8
$registry->drop('key'); Finally, to clear the entire registry of all values and changelog entries, use the reset() method. $registry->reset(); Note: This is very destructive. Please use with caution because you can purge settings that you didn't own. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/SugarBPM/Extending_SugarBPM/index.html
8c062500c5cb-0
Global Search Overview How to customize the global search results. Configuring Search Results The Search-List view, located in ./clients/base/views/search-list/, is responsible for the global search results page. By default, it contains the rowactions that are available for each result. The following sections will outline how to configure the primary and secondary fields. Primary and Secondary Fields Each row returned from the global search is split into two lines. The first line contains the primary fields and avatar. A primary field is a field considered to be important to the identification of a record and is usually composed of the records name value and a link to the record. The avatar is an icon specific to the module the results are coming from. The second line contains the highlighted matches and any secondary fields specified. A highlight is a hit returned by elastic search. Highlights are driven from elastic and no definition is needed in the metadata to define them. Both primary and secondary fields can be highlighted. A secondary field is a field that has regularly accessed data. It is important to note that the initial type-ahead drop-down will not show specified secondary fields unless the user hits enter and is taken to the search results page. Different modules have different secondary fields. For example, an account's secondary fields are email and phone number, while cases' secondary fields are case ID number and related account. To leverage the metadata manager, the global search view reuses the same metadata format as other views. You can add any indexed field in elastic search to the search list view. An example of the stock metadata is shown below. ./modules/{module}/clients/base/views/search-list/search-list.php <?php $viewdefs[$moduleName]['base']['view']['search-list'] = array( 'panels' => array( array(
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Global_Search/index.html
8c062500c5cb-1
'panels' => array( array( 'name' => 'primary', // This is mandatory and the word `primary` can not be changed. 'fields' => array( /* * Put here the list of primary fields. * You can either define a field as a string and the metadata * manager will load the field vardefs, or you can define as an * array if you want to add properties or override vardefs * properties just for the search results view. * * You most likely want to show the module icon on the left of the * view. For this, you need to add the following picture field as * a primary field. */ array( 'name' => 'picture', 'type' => 'avatar', 'size' => 'medium', 'css_class' => 'pull-left', ), array( 'name' => 'name', 'type' => 'name', 'link' => true, 'label' => 'LBL_SUBJECT', ), ), ), /* * If you don't want secondary fields, you can remove the following array. */ array( 'name' => 'secondary', // This is mandatory and the word `secondary` can not be changed. 'fields' => array( /* * Put here the list of secondary fields */ 'status', // This field is defined as a string for example. array( 'name' => 'description', 'label' => 'LBL_SEARCH_DESCRIPTION', ), ), ), ), );
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Global_Search/index.html
8c062500c5cb-2
), ), ), ), ); Note: You can technically override the row actions for the results of a module, however, the view currently only supports the preview action so it is not recommended to customizes these actions. Examples The following examples demonstrate how to modify the primary and secondary rows of the global search. Adding Fields to the Primary Row This example will demonstrate how to add "Mobile" into the search-list view's primary row for Contact module results. To accomplish this, you can duplicate ./modules/Contacts/clients/base/views/search-list/search-list.php to   ./custom/modules/Contacts/clients/base/views/search-list/search-list.php if it doesn't exist. Once in place, add your phone_mobile definition to the $viewdefs['Contacts']['base']['view']['search-list']['panels'] array definition with the name attribute equal to "primary'. An example is shown below: ./custom/modules/Contacts/clients/base/views/search-list/search-list.php <?php $viewdefs['Contacts']['base']['view']['search-list'] = array( 'panels' => array( array( 'name' => 'primary', 'fields' => array( array( 'name' => 'picture', 'type' => 'avatar', 'size' => 'medium', 'readonly' => true, 'css_class' => 'pull-left', ), array( 'name' => 'name', 'type' => 'name', 'link' => true, 'label' => 'LBL_SUBJECT', ), // Adding the mobile into first row of the results 'phone_mobile', ), ), array(
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Global_Search/index.html
8c062500c5cb-3
'phone_mobile', ), ), array( 'name' => 'secondary', 'fields' => array( array( 'name' => 'email', 'label' => 'LBL_PRIMARY_EMAIL', ), ), ), ), ); Once in place, navigate to Admin > Repair > Quick Repair and Rebuild. Your changes will then be reflected in the system. Adding Fields to the Secondary Row This example will demonstrate how to add "Mobile" into the search-list view's secondary row for Contact module results. It is important to note that the initial type-ahead drop-down will not show specified secondary fields unless the user hits enter and is taken to the search results page. In this example, we are going to add Portal Name into search-list for Contact module results. To accomplish this, you can duplicate ./modules/Contacts/clients/base/views/search-list/search-list.php to   ./custom/modules/Contacts/clients/base/views/search-list/search-list.php if it doesn't exist. Once in place, add your phone_mobile definition to the $viewdefs['Contacts']['base']['view']['search-list']['panels'] array definition with the name attribute equal to "secondary'. An example is shown below: <?php $viewdefs['Contacts']['base']['view']['search-list'] = array( 'panels' => array( array( 'name' => 'primary', 'fields' => array( array( 'name' => 'picture', 'type' => 'avatar', 'size' => 'medium', 'readonly' => true, 'css_class' => 'pull-left', ), array( 'name' => 'name', 'type' => 'name',
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Global_Search/index.html
8c062500c5cb-4
'name' => 'name', 'type' => 'name', 'link' => true, 'label' => 'LBL_SUBJECT', ), ), ), array( 'name' => 'secondary', 'fields' => array( array( 'name' => 'email', 'label' => 'LBL_PRIMARY_EMAIL', ), // Adding mobile to second row for search results in globalsearch 'phone_mobile' ), ), ), ); Once in place, navigate to Admin > Repair > Quick Repair and Rebuild. Your changes will then be reflected in the system. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Global_Search/index.html
c8955d1c10ee-0
Job Queue Overview The Job Queue executes automated tasks in Sugar through a scheduler, which integrates with external UNIX systems and Windows systems to run jobs that are scheduled through those systems. Jobs are the individual runs of the specified function from a scheduler.  The Job Queue is composed of the following parts: SugarJobQueue : Implements the queue functionality. The queue contains the various jobs. SchedulersJob : A single instance of a job. This represents a single executable task and is held in the SugarJobQueue. Scheduler : This is a periodically occurring job. SugarCronJobs : The cron process that uses SugarJobQueue to run jobs. It runs periodically and does not support parallel execution. Stages Schedule Stage On the scheduling stage (checkPendingJobs in Scheduler class), the queue checks if any schedules are qualified to run at this time and do not have job instance already in the queue. If such schedules exist, a job instance will immediately be created for each. Execution Stage The SQL queue table is checked for any jobs in the "Pending" status. These will be set to "Running"' and then executed in accordance to its target and settings. Cleanup Stage The queue is checked for jobs that are in the "Running" state longer than the defined timeout. Such jobs are considered "Failed" jobs (they may be re-queued if their definition includes re-queuing on failure).
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/index.html
c8955d1c10ee-1
TopicsSchedulersSugar provides a Scheduler service that can execute predefined functions asynchronously on a periodic basis. The Scheduler integrates with external UNIX systems and Windows systems to run jobs that are scheduled through those systems. The typical configuration is to have a UNIX cron job or a Windows scheduled job execute the Sugar Scheduler service every couple of minutes. The Scheduler service checks the list of Schedulers defined in the Scheduler Admin screen and executes any that are currently due.Scheduler JobsJobs are the individual runs of the specified function from a scheduler. This article will outline the various parts of a Scheduler Job. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/index.html
ddd23ca7d2cd-0
Scheduler Jobs Overview Jobs are the individual runs of the specified function from a scheduler. This article will outline the various parts of a Scheduler Job. Properties name : Name of the job scheduler_id : ID of the scheduler that created the job. This may be empty as schedulers are not required to create jobs execute_time : Time when job is ready to be executed status : Status of the job resolution : Notes whether or not the job was successful message : Contains messages produced by the job, including errors target : Function or URL called by the job data : Data attached to the job requeue : Boolean to determine whether the job will be replaced in the queue upon failure retry_count : Determines how many times the system will retry the job before failure failure_count : The number f times the job has failed job_delay : The delay (in seconds) between each job run assigned_user_id : User ID of which the job will be executed as client : The name of the client owning the job percent_complete : For postponed jobs, this can be used to determine how much of the job has been completed Creating a Job To create job, you must first create an instance of SchedulesJobs class and use submitJob in SugarJobQueue. An example is shown below: <?php $jq = new SugarJobQueue(); $job = new SchedulersJob(); $job->name = "My Job"; $job->target = "function::myjob"; $jobid = $jq->submitJob($job); echo "Created job $jobid!"; Job Targets Job target contains two components, type and name, separated by "::". Type can be: function : Name or static method name (using :: syntax). This function will be passed the job object as the first parameter and if data is not empty, it will be passed as the second parameter.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/Jobs/index.html
ddd23ca7d2cd-1
url : External URL to call when running the job Running the Job The job is run via the runJob() function in SchedulersJob. This function will return a boolean success value according to the value returned by the target function. For URL targets, the HTTP error code being less than 400 will return success. If the function updated the job status from 'running', the return value of a function is ignored. Currently, the postponing of a URL job is not supported. Job status Jobs can be in following statuses: queued : The job is waiting in the queue to be executed running : The job is currently being executed done : The job has executed and completed Job Resolution Job resolution is set when the job is finished and can be: queued : The job is still not finished success : The job has completed successfully failure : The job has failed partial : The job is partially done but needs to be completed Job Logic Hooks The scheduler jobs module has two additional logic hooks that can be used to monitor jobs. The additional hooks that can be used are shown below: job_failure_retry : Executed when a job fails but will be retried job_failure : Executed when the job fails for the final time You can find more information on these hooks in the Job Queue Hooks section. TopicsCreating Custom JobsHow to create and execute your own custom jobs.Queuing Logic Hook ActionsThis example will demonstrate how to pass tasks to the job queue. This enables you to send longer running jobs such as sending emails, calling web services, or doing other resource intensive jobs to be handled asynchronously by the cron in the background. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/Jobs/index.html
8cca2fd47493-0
Creating Custom Jobs Overview How to create and execute your own custom jobs. How it Works As of 6.3.0, custom job functions can be created using the extension framework. The function for the job will be defined in ./custom/Extension/modules/Schedulers/Ext/ScheduledTasks/. Files in this directory are compiled into ./custom/modules/Schedulers/Ext/ScheduledTasks/scheduledtasks.ext.php and then included for use in ./modules/Schedulers/_AddJobsHere.php. Creating the Job Use the section below to introduce the technology in relation to the product and describe its benefits. This first step is to create your jobs custom key. For this example we will be using 'custom_job' as our job key. ./custom/Extension/modules/Schedulers/Ext/ScheduledTasks/custom_job.php <?php //add the job key to the list of job strings array_push($job_strings, 'custom_job'); function custom_job() { //custom job code //return true for completed return true; } Next, we will need to define our jobs label string: ./custom/Extension/modules/Schedulers/Ext/Language/en_us.custom_job.php <?php $mod_strings['LBL_CUSTOM_JOB'] = 'Custom Job'; Finally, We will need to navigate to: Admin / Repair / Quick Repair and Rebuild Once a Quick Repair and Rebuild has been run, the new job will be available for use when creating new schedulers in: Admin / Scheduler Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/Jobs/Creating_Custom_Jobs/index.html
badaecf39b0d-0
Queuing Logic Hook Actions Overview This example will demonstrate how to pass tasks to the job queue. This enables you to send longer running jobs such as sending emails, calling web services, or doing other resource intensive jobs to be handled asynchronously by the cron in the background. Example This example will queue an email to be sent out by the cron when an account record is saved. First, we will create a before_save logic hook on accounts. ./custom/modules/Accounts/logic_hooks.php <?php $hook_version = 1; $hook_array = Array(); $hook_array['before_save'][] = Array(); $hook_array['before_save'][] = Array( 1, 'Queue Job Example', 'custom/modules/Accounts/Accounts_Save.php', 'Accounts_Save', 'QueueJob' ); ?> In our logic hook, we will create a new SchedulersJob and submit it to the SugarJobQueue targeting our custom AccountAlertJob that we will create next. ./custom/modules/Accounts/Accounts_Save.php <?php if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); require_once 'include/SugarQueue/SugarJobQueue.php'; class Accounts_Save { function QueueJob(&$bean, $event, $arguments) { //create the new job $job = new SchedulersJob(); //job name $job->name = "Account Alert Job - {$bean->name}"; //data we are passing to the job $job->data = $bean->id; //function to call $job->target = "function::AccountAlertJob"; global $current_user;
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/Jobs/Queuing_Logic_Hook_Actions/index.html
badaecf39b0d-1
global $current_user; //set the user the job runs as $job->assigned_user_id = $current_user->id; //push into the queue to run $jq = new SugarJobQueue(); $jobid = $jq->submitJob($job); } } ?> Next, we will need to define the Job. This will be done by creating a new function to execute our code. We will put this file in the ./custom/Extension/modules/Schedulers/Ext/ScheduledTasks/ directory with the name AccountAlertJob.php. ./custom/Extension/modules/Schedulers/Ext/ScheduledTasks/AccountAlertJob.php <?php function AccountAlertJob($job) { if (!empty($job->data)) { $bean = BeanFactory::getBean('Accounts', $job->data); $emailObj = new Email(); $defaults = $emailObj->getSystemDefaultEmail(); $mail = new SugarPHPMailer(); $mail->setMailerForSystem(); $mail->From = $defaults['email']; $mail->FromName = $defaults['name']; $mail->Subject = from_html($bean->name); $mail->Body = from_html("Email alert that '{$bean->name}' was saved"); $mail->prepForOutbound(); $mail->AddAddress('[email protected]'); if($mail->Send()) { //return true for completed return true; } } return false; }
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/Jobs/Queuing_Logic_Hook_Actions/index.html
badaecf39b0d-2
return true; } } return false; } Finally, navigate to Admin / Repair / Quick Repair and Rebuild. The system will then generate the file ./custom/modules/Schedulers/Ext/ScheduledTasks/scheduledtasks.ext.php containing our new function. We are now able to queue and run the scheduler job from a logic hook. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/Jobs/Queuing_Logic_Hook_Actions/index.html
50bbabd145a1-0
Schedulers Overview Sugar provides a Scheduler service that can execute predefined functions asynchronously on a periodic basis. The Scheduler integrates with external UNIX systems and Windows systems to run jobs that are scheduled through those systems. The typical configuration is to have a UNIX cron job or a Windows scheduled job execute the Sugar Scheduler service every couple of minutes. The Scheduler service checks the list of Schedulers defined in the Scheduler Admin screen and executes any that are currently due. A series of schedulers are defined by default with every Sugar installation. For detailed information on these stock schedulers, please refer to the Schedulers documentation. Config Settings cron.max_cron_jobs - Determines the maximum number of jobs executed per cron run cron.max_cron_runtime - Determines the maximum amount of time a job can run before forcing a failure cron.min_cron_interval - Specified the minimum amount of time between cron runs Considerations Schedulers execute the next time the cron runs after the interval of time has passed, which may not be at the exact time specified on the scheduler. If you see the message "Job runs too frequently, throttled to protect the system" in the Sugar log, the cron is running too frequently. If you would prefer the cron to run more frequently, set the cron.min_cron_interval setting to 0 and disable throttling completely. TopicsCreating Custom SchedulersIn addition to the default schedulers that are packaged with Sugar, developers can create custom scheduler jobs. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/Schedulers/index.html
99b7928bbdc8-0
Creating Custom Schedulers Overview In addition to the default schedulers that are packaged with Sugar, developers can create custom scheduler jobs. Defining the Job Label The first step to create a custom scheduler is creating a label extension file. This will add the display text for the scheduler job when creating a new scheduler in Admin > Scheduler. The file path of our file will be in the format of ./custom/Extension/modules/Schedulers/Ext/Language/<language key>.<name>.php. For our example, name the file en_us.custom_job.php. ./custom/Extension/modules/Schedulers/Ext/Language/en_us.custom_job.php <?php $mod_strings['LBL_CUSTOM_JOB'] = 'Custom Job'; Defining the Job Function Next, define the custom job's function using the extension framework. The file path of the file will be in the format of ./custom/Extension/modules/Schedulers/Ext/ScheduledTasks/<function_name>.php. For this example, name the file custom_job.php. Prior to 6.3.x, job functions were added by creating the file ./custom/modules/Schedulers/_AddJobsHere.php. This method of creating functions is still compatible but is not recommended from a best practices standpoint. ./custom/Extension/modules/Schedulers/Ext/ScheduledTasks/custom_job.php <?php array_push($job_strings, 'custom_job'); function custom_job() { //logic here //return true for completed return true; } Using the New Job Once the files are in place, navigate to Admin > Repair > Quick Repair and Rebuild. This will rebuild the extension directories with our additions. Next, navigate to Admin > Scheduler > Create Scheduler. In the Jobs dropdown, there will be a new custom job in the list.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/Schedulers/Creating_Custom_Schedulers/index.html
99b7928bbdc8-1
Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Job_Queue/Schedulers/Creating_Custom_Schedulers/index.html
7790482ec18a-0
Teams Overview Teams provide the ability to limit access at the record level, allowing sharing flexibility across functional groups. Developers can manipulate teams programmatically provided they understand Sugar's visibility framework. For more information on teams, please refer to the Team Management documentation. Database Tables Table Description teams Each record in this table represents a team in the system. team_sets Each record in this table represents a unique team combination. For example, each user's private team will have a corresponding team set entry in this table. A team set may also be comprised of one or more teams. team_sets_teams The team_sets_teams table maintains the relationships to determine which teams belong to a team set. Each table that previously used the team_id column to maintain team security now uses the team_set_id column's value to associate the record to team(s). team_sets_modules This table is used to manage team sets and keep track of which modules have records that are or were associated to a particular team set. Never modify these tables without going through the PHP object methods. Manipuating the team sets with direct SQL may cause undesired side effects in the system due to how the validations and security methods work. Module Team Fields In addition to the team tables, each module table also contains a team_id and team_set_id column. The team_set_id contains the id of a record in the team_sets table that contains the unique combination of teams associated with the record. The team_id will contain the id of the primary team designated for a record. Team Sets (team_set_id)
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/index.html
7790482ec18a-1
Team Sets (team_set_id) As mentioned above, Sugar implemented this feature not as a many-to-many relationship but as a one-to-many relationship. On each table that had a team_id field we added a 'team_set_id' field. We have also added a team_sets table, which maintains the team_set_id, and a team_sets_teams table, which relates a team set to the teams. When performing a team based query we use the 'team_set_id' field on the module table to join to team_sets_teams.team_set_id and then join all of the teams associated with that set. Given the list of teams from team_memberships we can then decide if the user has access to the record. Primary Team (team_id) The team_id is still being used, not only to support backwards compatibility with workflow and reports, but also to provide some additional features. When displaying a list, we use the team set to determine whether the user has access to the record. When displaying the data, we show the team from team id in the list. When the user performs a mouseover on that team, Sugar performs an Ajax call to display all of the teams associated with the record. This team_id field is designated as the Primary Team because it is the first team shown in the list, and for sales territory management purposes, can designate the team that actually owns the record and can report on it. Team Security The team_sets_teams table allows the system to check for permissions on multiple teams. The following diagram illustrates table relationships in SugarBean's add_team_security_where_clause method. Using the team_sets_teams table the system will determine which teams are associated with the team_set_id and then look in the team_memberships table for users that belong to the team(s). TeamSetLink
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/index.html
7790482ec18a-2
TeamSetLink Typically, any relationship in a class is handled by the data/Link2.php class. As a part of dynamic teams, we introduced the ability to provide your own custom Link class to handle some of the functionality related to managing relationships. The team_security parent vardefs in the Sugar objects contain the following in the 'teams' field definition: 'link_class' => 'TeamSetLink', 'link_file' => 'modules/Teams/TeamSetLink.php', The link_class entry defines the class name we are using, and the link_file tells us where that class file is located. This class extends the legacy Link.php and overrides some of the methods used to handle relationships such as 'add' and 'delete'. TopicsManipulating Teams ProgrammaticallyHow to manipulate team relationships.Visibility FrameworkThe visibility framework provides the capability to alter the queries Sugar uses to retrieve records from the database. This framework can allow for additional restrictions or specific logic to meet business requirements of hiding or showing only specific records. Visibility classes only apply to certain aspects of Sugar record retrieval, e.g. List Views, Dashlets, and Filter Lookups. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/index.html
0ce33ce2e5b9-0
Visibility Framework Overview The visibility framework provides the capability to alter the queries Sugar uses to retrieve records from the database. This framework can allow for additional restrictions or specific logic to meet business requirements of hiding or showing only specific records. Visibility classes only apply to certain aspects of Sugar record retrieval, e.g. List Views, Dashlets, and Filter Lookups. Custom Row Visibility Custom visibility class files are stored under ./custom/data/visibility/. The files in this directory can be enabled or disabled by modifying a module's visibility property located in ./custom/Extension/modules/<module>/Ext/Vardefs/. Every enabled visibility class is merged into the module's definition, allowing multiple layers of logic to be added to a module. Visibility Class To add custom row visibility, you must create a visibility class that will extend the core SugarVisibility class ./data/SugarVisibility.php . The visibility class has the ability to override the following methods: Name Description addVisibilityQuery Add visibility clauses to a SugarQuery object. addVisibilityFrom [Deprecated] Add visibility clauses to the FROM part of the query. This method should still be implemented, as not all objects have been switched over to use addVisibilityQuery() method. addVisibilityFromQuery [Deprecated] Add visibility clauses to the FROM part of SugarQuery. This method should still be implemented, as not all objects have been switched over to use addVisibilityQuery() method. addVisibilityWhere [Deprecated] Add visibility clauses to the WHERE part of the query. This method should still be implemented, as not all objects have been switched over to use addVisibilityQuery() method. addVisibilityWhereQuery [Deprecated] Add visibility clauses to the WHERE part of SugarQuery. This method should still be implemented, as not all objects have been switched over to use addVisibilityQuery() method.
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Custom_Record_Visibility/index.html
0ce33ce2e5b9-1
The visibility class should also implement Sugarcrm\Sugarcrm\Elasticsearch\Provider\Visibility\StrategyInterface so that the visibility rules are also applied to the global search.  StrategyInterface has the following functions that should be implemented: Name Description elasticBuildAnalysis Build Elasticsearch analysis settings.  This function can be empty if you do not need any special analyzers. elasticBuildMapping Build Elasticsearch mapping.  This function should contain a mapping of fields that should be analyzed. elasticProcessDocumentPreIndex Process document before it's being indexed. This function should perform any actions to the document that needs to be completed before it is indexed.  elasticGetBeanIndexFields Bean index fields to be indexed.  This function should return an array of the fields that need to be indexed as part of your custom visibility. elasticAddFilters Add visibility filters.  This function should apply the Elastic filters. Example The following example creates a custom visibility filter that determines whether Opportunity records should be displayed based on their Sales Stage.  Opportunity records with Sales Stage set to Closed Won or Closed Lost will not be displayed in the Opportunities module or global search for users with the Demo Visibility role.   /custom/data/visibility/FilterOpportunities.php: <?php use Sugarcrm\Sugarcrm\Elasticsearch\Provider\Visibility\StrategyInterface as ElasticStrategyInterface; use Sugarcrm\Sugarcrm\Elasticsearch\Provider\Visibility\Visibility; use Sugarcrm\Sugarcrm\Elasticsearch\Analysis\AnalysisBuilder; use Sugarcrm\Sugarcrm\Elasticsearch\Mapping\Mapping; use Sugarcrm\Sugarcrm\Elasticsearch\Adapter\Document; /** * * Custom visibility class for Opportunities module: * * This demo allows to restrict access to opportunity records based on the
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Custom_Record_Visibility/index.html
0ce33ce2e5b9-2
* * This demo allows to restrict access to opportunity records based on the * user's role and configured filtered sales stages. * * The following $sugar_config parameters are available: * * $sugar_config['custom']['visibility']['opportunities']['target_role'] * This parameter takes a string containing the role name for which * the filtering should apply. * * $sugar_config['custom']['visibility']['opportunities']['filter_sales_stages'] * This parameters takes an array of filtered sales stages. If current user is * member of the above configured role, then the opportunities with the sale * stages as configured in this array will be inaccessible. * * * Example configuration given that 'Demo Visibility' role exists (config_override.php): * * $sugar_config['custom']['visibility']['opportunities']['target_role'] = 'Demo Visibility'; * $sugar_config['custom']['visibility']['opportunities']['filter_sales_stages'] = array('Closed Won', 'Closed Lost'); * */ class FilterOpportunities extends SugarVisibility implements ElasticStrategyInterface { /** * The target role name * @var string */ protected $targetRole = ''; /** * Filtered sales stages * @var array */ protected $filterSalesStages = array(); /** * {@inheritdoc} */ public function __construct(SugarBean $bean, $params = null) { parent::__construct($bean, $params); $config = SugarConfig::getInstance(); $this->targetRole = $config->get( 'custom.visibility.opportunities.target_role', $this->targetRole ); $this->filterSalesStages = $config->get(
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Custom_Record_Visibility/index.html
0ce33ce2e5b9-3
); $this->filterSalesStages = $config->get( 'custom.visibility.opportunities.filter_sales_stages', $this->filterSalesStages ); } /** * {@inheritdoc} */ public function addVisibilityWhere(&$query) { if (!$this->isSecurityApplicable()) { return $query; } $whereClause = sprintf( "%s.sales_stage NOT IN (%s)", $this->getTableAlias(), implode(',', array_map(array($this->bean->db, 'quoted'), $this->filterSalesStages)) ); if (!empty($query)) { $query .= " AND $whereClause "; } else { $query = $whereClause; } return $query; } /** * {@inheritdoc} */ public function addVisibilityWhereQuery(SugarQuery $sugarQuery, $options = array()) { $where = null; $this->addVisibilityWhere($where, $options); if (!empty($where)) { $sugarQuery->where()->addRaw($where); } return $sugarQuery; } /** * Check if we can apply our security model * @param User $user * @return false|User */ protected function isSecurityApplicable(User $user = null) { $user = $user ?: $this->getCurrentUser(); if (!$user) { return false; } if (empty($this->targetRole) || empty($this->filterSalesStages)) { return false; }
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Custom_Record_Visibility/index.html
0ce33ce2e5b9-4
return false; } if (!is_string($this->targetRole) || !is_array($this->filterSalesStages)) { return false; } if (!$this->isUserMemberOfRole($this->targetRole, $user)) { return false; } if ($user->isAdminForModule("Opportunities")) { return false; } return $user; } /** * Get current user * @return false|User */ protected function getCurrentUser() { return empty($GLOBALS['current_user']) ? false : $GLOBALS['current_user']; } /** * Check if given user has a given role assigned * @param string $targetRole Name of the role * @param User $user * @return boolean */ protected function isUserMemberOfRole($targetRole, User $user) { $roles = ACLRole::getUserRoleNames($user->id); return in_array($targetRole, $roles) ? true : false; } /** * Get table alias * @return string */ protected function getTableAlias() { $tableAlias = $this->getOption('table_alias'); if (empty($tableAlias)) { $tableAlias = $this->bean->table_name; } return $tableAlias; } /** * {@inheritdoc} */ public function elasticBuildAnalysis(AnalysisBuilder $analysisBuilder, Visibility $provider) { // no special analyzers needed } /** * {@inheritdoc} */
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Custom_Record_Visibility/index.html
0ce33ce2e5b9-5
} /** * {@inheritdoc} */ public function elasticBuildMapping(Mapping $mapping, Visibility $provider) { $mapping->addNotAnalyzedField('visibility_sales_stage'); } /** * {@inheritdoc} */ public function elasticProcessDocumentPreIndex(Document $document, \SugarBean $bean, Visibility $provider) { // populate the sales_stage into our explicit filter field $sales_stage = isset($bean->sales_stage) ? $bean->sales_stage : ''; $document->setDataField('visibility_sales_stage', $sales_stage); } /** * {@inheritdoc} */ public function elasticGetBeanIndexFields($module, Visibility $provider) { // make sure to pull sales_stage regardless of search return array('sales_stage'); } /** * {@inheritdoc} */ public function elasticAddFilters(User $user, Elastica\Query\BoolQuery $filter, Sugarcrm\Sugarcrm\Elasticsearch\Provider\Visibility\Visibility $provider) { if (!$this->isSecurityApplicable($user)) { return; } // apply elastic filter to exclude the given sales stages $filter->addMustNot($provider->createFilter( 'OpportunitySalesStages', array( 'filter_sales_stages' => $this->filterSalesStages, ) )); } } ./custom/Extension/modules/Opportunities/Ext/Vardefs/opp_visibility.php <?php if (!defined('sugarEntry') || !sugarEntry) { die('Not A Valid Entry Point'); }
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Custom_Record_Visibility/index.html
0ce33ce2e5b9-6
die('Not A Valid Entry Point'); } $dictionary['Opportunity']['visibility']['FilterOpportunities'] = true; ./custom/src/Elasticsearch/Provider/Visibility/Filter/OpportunitySalesStagesFilter.php <?php namespace Sugarcrm\Sugarcrm\custom\Elasticsearch\Provider\Visibility\Filter; use Sugarcrm\Sugarcrm\Elasticsearch\Provider\Visibility\Filter\FilterInterface; use Sugarcrm\Sugarcrm\Elasticsearch\Provider\Visibility\Visibility; /** * * Custom opportunity filter by sales_stage * * This logic can exist directly in the FilterOpportunities visibility class. * However by abstracting the (custom) filters makes it possible to re-use * them in other places as well. */ class OpportunitySalesStagesFilter implements FilterInterface { /** * @var Visibility */ protected $provider; /** * {@inheritdoc} */ public function setProvider(Visibility $provider) { $this->provider = $provider; } /** * {@inheritdoc} */ public function buildFilter(array $options = array()) { return new \Elastica\Query\Terms( 'visibility_sales_stage', $options['filter_sales_stages'] ); } } After creating the above files, log in to your Sugar instance as an administrator and navigate to Administration > Repair > Quick Repair and Rebuild.   Next, perform a full reindex by navigating to Administration > Search and selecting the "delete existing data" option.  Execute a cron to process all of the queued records into Elasticsearch by doing the following:Â
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Custom_Record_Visibility/index.html
0ce33ce2e5b9-7
Open a command line client and navigate to your Sugar directory. Execute chmod +x bin/sugarcrm to ensure bin/sugarcrm is executable. Execute php cron.php to consume the queue. Execute bin/sugarcrm elastic:queue to see if the queue has finished. Repeat steps 3 and 4 until the queue has 0 records. This example requires the Sales Stage field to be part of the Opportunities module.  Navigate to Administration > Opportunities and ensure the Opportunities radio button is selected. Create a new role named "Demo Visibility" and assign a user to this role.  Note: if you are using the sample data, do NOT use Jim as he has admin permission on the Opportunities module and will be able to view all records. We recommend using Max. Configure your instance to filter opportunities for a given sales stages for this role by adding the following to ./config_override.php: <?php $sugar_config['custom']['visibility']['opportunities']['target_role'] = 'Demo Visibility'; $sugar_config['custom']['visibility']['opportunities']['filter_sales_stages'] = array('Closed Won', 'Closed Lost'); Log in as the user to whom you assigned the Demo Visibility role. Observe that opportunity records in the sales stages "Closed Won" and "Closed Lost" are no longer accessible. You can download a module loadable package of this example here. Last modified: 2023-02-03 21:04:03
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Custom_Record_Visibility/index.html
e690aa0ef188-0
Manipulating Teams Programmatically Overview How to manipulate team relationships. Fetching Teams To fetch teams related to a bean, you will need to retrieve an instance of a TeamSet object and use the getTeams() method to retrieve the teams using the team_set_id. An example is shown below: //Create a TeamSet bean - no BeanFactory require_once 'modules/Teams/TeamSet.php'; $teamSetBean = new TeamSet(); //Retrieve the bean $bean = BeanFactory::getBean($module, $record_id); //Retrieve the teams from the team_set_id $teams = $teamSetBean->getTeams($bean->team_set_id); Adding Teams To add a team to a bean, you will need to load the team's relationship and use the add() method. This method accepts an array of team ids to add. An example is shown below: //Retrieve the bean $bean = BeanFactory::getBean($module, $record_id); //Load the team relationship $bean->load_relationship('teams'); //Add the teams $bean->teams->add( array( $team_id_1, $team_id_2 ) ); Considerations If adding 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. Removing Teams To remove a team from a bean, you will need to load the team's relationship and use the remove() method. This method accepts an array of team ids to remove. An example is shown below: //Retrieve the bean $bean = BeanFactory::getBean($module, $record_id); //Load the team relationship $bean->load_relationship('teams'); //Remove the teams $bean->teams->remove(
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_13.0/Architecture/Teams/Manipulating_Teams_Programmatically/index.html