Sugar Community Edition 6.3 Documentation

Sugar Developer Guide

Table of Contents Previous

Version 6.3.0



The Sugar Developer Guide is designed for developers who are new to Sugar, or to CRM and Web-based applications. This guide introduces you to some basic CRM concepts and helps you get familiar with the Sugar system. It describes how to install and upgrade Sugar and access it through a personal computer and a Web browser to perform a broad range of customer relationship management tasks.
Sugar Ultimate Application Guide, Sugar Enterprise Application Guide, Sugar Corporate Application Guide, Sugar Professional Application Guide, and Sugar Community Edition Application Guide: Describe how to install, upgrade, set up, configure, manage, and use Sugar Ultimate, Sugar Enterprise, Sugar Corporate, Sugar Professional, and Sugar Community Edition.
SugarCRM was originally written on the LAMP stack (Linux, Apache, MySQL and PHP). Since version 1.0, the SugarCRM development team has added support for every operating system (including Windows, Unix and Mac OSX) on which the PHP programming language runs for the Microsoft IIS Web server, the Microsoft SQL Server, and Oracle databases. Designed as the most modern web-based CRM platform available today, SugarCRM has quickly become the business application standard for companies around the world. See the Supported Platforms page for detailed information on supported software versions and recommended stacks.
The Sugar application code is based on a modular framework with secure entry points into the application (e.g. index.php or soap.php). All modules, core or custom, must exist in the <sugar root>/modules/ folder. Modules represent business entities or objects in Sugar such as Contacts, and the object has fields or attributes that are stored in the database, as well as a user interface (UI) for the user to create and modify records. A module encompasses definitions for the data schema, user interface, and application functionality.
cache: Various cache files written to the file system to minimize database accesses and store user interface templates created from metadata. Files uploaded into the application such as Note Attachments or Documents reside in this directory (refer to upload_dir parameter in the config.php file). This is an active cache directory and not all files can be deleted.
custom: Stores upgrade-safe customizations such as custom field definitions, user interface layouts, and business logic hooks.
data: Key system files are located here, most notably the SugarBean base class which controls the default application logic for all business objects in Sugar.
include: Many Sugar utility functions are located here, as well as other libraries that Sugar utilizes as part of its operations. Most notable in this directory is the utils.php file that contains the most widely used utility functions.
metadata: Contains relationship metadata for all many-to-many data relationships between the business objects.
modules: Contains all modules in the system. Custom modules installed through the Module Loader exist here as well.
Controller: Directs all incoming page requests. This can be overridden in each module to change the default behavior and relies on Entry point parameters (described below) to serve the appropriate page.
Views: A set of user interface actions managed by the Controller, the default views in Sugar include the Detail View, Edit View, and List View.
Display strings: Sugar is fully internationalized and localizable. Every language pack has its own set of display strings which is the basis of language localization. There are two types of display strings in the Sugar application: application strings and module strings. Application strings contain the user interface labels displayed globally throughout the application. The $GLOBALS[‘app_strings’] array contains these labels. The $GLOBALS[‘app_list_strings’] array contains the system-wide drop-down list values. Each language has its own application strings variables. The $GLOBALS[‘mod_strings’] array contains strings specific to the current, or in-focus, module.
Drop-down lists: Drop-down lists are represented as name => value array pairs located in the application strings mentioned above. The name value is stored in the database where the value is displayed in the Sugar User Interface (UI). Sugar enables you to create and edit drop-down lists and their values through the UI in Studio. Use the handy get_select_options_with_id() utility function to help render the <select> input options to work with drop-down lists in Edit Views. Use the translate() utility function to translate the string key you are working with into the user’s currently selected display language.
SugarBean.php: This file located under the <sugar root>/data folder contains the SugarBean base class used by all business entity or module objects. Any module that reads, writes, or displays data will extend this class. The SugarBean performs all of the heavy lifting for data interactions, relationship handling, etc.
modules.php: The modules.php file contains several variables that define which modules are active and usable in the application.
$dictionary: The $dictionary array contains all module field variable definitions (vardefs), as well as the relationship metadata for all tables in the database. This array is dynamically built based upon the vardefs.php definitions.
The primary user interface entry point for Sugar is through index.php located in the root Sugar folder. The main parameters for most calls are:
module: The module to be accessed as part of the call
action: The action within the module
record: The record ID
Other commonly used parameters are return_module , return_action, and return_id. This group of request parameters is used when a user cancels an action such as creating or editing a record.
Note: As of Sugar 5.1, most entry points were consolidated into index.php. Previous versions had other files as entry points into the application.
All modules, out of the box (OOTB) or custom, are placed in the <sugar root>/modules/ folder. Modules are created to represent an object (such as Contacts) in Sugar, store the object’s data points in the database, and provide a UI to create, edit, and delete object records.
List View: This Controller action enables the search form and search results for a module. Users can perform actions such as delete, export, update multiple records (mass update), and drill into a specific record to view and edit the details. Users can see this view by default when they click one of the module tabs at the top of the page. Files in each module describe the contents of the list and search view.
Detail View: A Detail View displays a read-only view of a particular record. Usually, this is accessed via the List View. The Detail View displays the details of the object itself and related items (sub-panels).
Sub-panels are mini List Views of items that are related to the parent object. For example, Tasks assigned to a Project, or Contacts for an Opportunity will appear in sub-panels in the Project or Opportunity Detail View.
<module>/metadata/detailviewdefs.php defines a module's Detail View page layout. <module>/metadata/subpaneldefs.php defines the subpanels that are displayed in the module's Detail View page.
Edit View: The Edit View page is accessed when a user creates a new record or edits details of an existing one. Edit View can also be accessed directly from the List View. <module>/metadata/editviewdefs.php defines a module's Edit View page layout.
Save: This Controller action is processed when the user clicks Save in the record’s Edit View.
Delete: This action is processed when the user clicks Delete in the Detail View of a record or in the Detail View of a record listed in a sub-panel.
<module>/metadata/detailviewdefs.php describes the layout of the Detail View.
forms.php: This file contains two functions to render specific JavaScript for validation or other actions during edits/saves. By default you can leave these empty and have them return ‘’;
Menu.php: This file is responsible for rendering the Shortcuts menu, which was renamed as Actions menu as of Sugar 6.0. In Community Edition, the Actions menu displays below the module tabs and the Last Viewed bar. In Sugar Ultimate, Enterprise, Corporate, and Professional editions, the Actions menu displays on every module tab. By default, you usually add a link to create a new record, and a link to the List View to search.
Popup.php: This file acts as a wrapper to the central Popup class located under the utils folder. It is called when a module wants to get a popup list of records from a related module. The central Popup class uses the Popup_picker.html and <MODULE_NAME>/metadata/popupdefs.php file to render the popup.
Popup_picker.html: This is used by the central Popup class to display a module’s pop-ups.
vardefs.php: The vardefs.php metadata file defines db and non-db fields for Sugar objects as well as relationships between objects.
field_arrays.php: This file is deprecated as of Sugar version 5.1. It has been phased out over time with the addition of metadata structures in the application, most notably the vardefs metadata.
Sugar Dashlets: These are drag-and-drop forms displayed on the Sugar Home and Dashboard tabs. Sugar Dashlets display any data (including data from external connectors), and List View and Chart data for the modules. As a developer of a custom module, you can create a Sugar Dashlet for your new module. For each Sugar Dashlet you create, you will place the necessary files in the <MODULE_NAME>/Dashlets folder.
language: This folder holds the strings files for the module. By default you will have an en_us.lang.php file containing ALL strings used by your module. These strings are represented by the $mod_strings variable accessed at any time after a global $mod_string call. The .html files located in this folder are used by the Help subsystem. Sugar provides the capabilities for multi-language support and dynamic loading via the admin panel of new language packs.
metadata: Module-specific metadata files have been added to this folder with the addition of more metadata and extensibility into the Sugar Platform. Files in this directory include: additionaldetails.php which defines the content of the pop-up displayed in the List Views; listviewdefs.php which defines the columns displayed on the List View page;
popupdefs.php, which defines the search fields and list columns for a module’s popup; SearchFields.php, which defines the Basic Search and Advanced Search forms seen in the List View page; and
studio.php, which defines how the Studio tool interacts with a module's metadata files.
subpanels: This folder stores the definitions of a module’s sub-panels when the module is related in a one-to-many or many-to-many fashion. You can add any number of versions in the default.php file. You can also create custom versions of sub-panels of other modules to be displayed by your custom module.
For example, you can relate a custom module with the Contacts module and have a Contacts subpanel under the Detail View. You could build and place a ForWidgets.php file under the <sugar root>/modules/Contacts/subpanels/ folder. The file name is referenced by the subpanel_name parameter called from a layout_defs.php definition.
tpls: This folder holds Smarty template files used for Quick Create forms.
views: This folder contains files that can override the default Model-View-Controller (MVC) framework view files. View files can perform multiple actions on the Smarty template or outputted HTML, allowing developers to modify and extend the default UI display classes and take full control of the user interface.
Modules: Create new modules and add them to Sugar
Vardefs: Add custom fields to existing modules with the addition of your custom module
Relationships: Create new relationships between your custom module(s) and existing modules
SubPanels: Create/add new sub-panel definitions to existing modules
Strings: Override or add to module and application strings
Menus: Override or add to Actions menus
Layout Defs: Specify the displayed subpanels and the order in which they are displayed. Create the layout definition for a custom module and add it as a sub-panel to the layout definition of an existing module.
For Community Edition, Sugar supports LinkedIn©’s Company Insider widget and InsideView. Use this as an example connector to learn the framework and create your own. Sugar Ultimate, Sugar Enterprise, Sugar Corporate, and Sugar Professional support additional connectors, such as Hoovers© , Zoominfo, Google Docs, Twitter, Facebook, GoToMeeting, LotusLive, and WebEx, and have the ability to merge the data into existing Sugar records.
campaign_trackerv2.php – used by the Campaign Management module for tracking campaign responses
cron.php – used by the Windows Scheduler Service or the cron service on Linux and Unix for executing the Sugar Scheduler periodically
index.php – default entry point into the Sugar application
install.php – used for initial install
maintenance.php – invoked when the application is down for maintenance
silentUpgrade.php – Used for silent installer
soap.php – entry point for all SOAP calls
rest.php – entry point for all REST calls
vcal_server.php – used for syncing information to Outlook
1.
Locate the entry point file name in the include/MVC/Controller/entry_point_registry.php. This is in the file key in the sub-array. Make note of the key of that array
2.
For the pdf.php entry point, the array appears in include/MVC/Controller/entry_point_registry.php as:
Use the pdf part in the next step.
For the above pdf.php example, we would change our references from:
The only remaining entry point that does not use this new index.php URL pattern (and, therefore, continues to be a valid entry point) is:
campaign_tracker.php – used by the Campaign Management module for tracking campaign responses (deprecated as of Sugar 5.1.0)
cron.php – used by the Windows Scheduler Service or the cron service on Linux and Unix for executing the Sugar Scheduler periodically
index.php – default entry point into the Sugar application
install.php – used for initial install
maintenance.php – invoked when the application is down for maintenance
metagen.php – Deprecated as of Sugar 5.1.0
silentUpgrade.php – used for silent installer
soap.php – entry point for all SOAP calls
rest.php – entry point for all REST calls
vcal_server.php – used for syncing information to Outlook
Activate the Developer Mode (Admin->System Settings->Advanced->Developer Mode) to ignore these cached files during development activities in Sugar. This is especially helpful when you are directly altering templates, metadata, or language files. The system automatically refreshes the file cache in Module Builder and Studio. Deactivate the Developer Mode after completing customizations because this mode degrades system performance.
Sugar Dashlets use the abstract factory design pattern. Individual dashlets extend the base abstract class Dashlet.php, List View Dashlets extend the base abstract class DashletGeneric.php, and Chart Dashlets extend the base abstract class DashletGenericChart.php.
Sugar Dashlet developers use the custom/ directory to upgrade-safe their Sugar Dashlets. Sugar Dashlets offered in base Sugar releases are located in the standard modules/ directory.
The file name containing the main Sugar Dashlet code must match the Sugar Dashlet’s class name. For example, the Sugar Dashlet class JotPadDashlet is located in the file /Home/Dashlets/JotPadDashlet/JotPadDashlet.php. The JotPadDashlet is a sample Sugar Dashlet released originally in Sugar 4.5. It serves as a useful example from which to begin your development efforts.

The naming convention for the metadata file is
className.meta.php, where className is the name of the Sugar Dashlet. The metadata file must reside in the same directory as the Sugar Dashlet code. For JotPad Dashlet, the meta file is stored in modules/Home/Dashlets/JotPadDashlet/JotPadDashlet.meta.php.
Language files have a similar naming convention: className.locale.lang.php (for example /Dashletsmodules/Home/Dashlets/JotPadDashlet/JotpadDashlet.en_us.lang.php )
Icon files can either be defined in the .metadata file or included in the Sugar Dashlet Directory (for example /Dashletsmodules/Home/Dashlets/JotPadDashlet/JotPadDashlet.icon.png).
Module Views – Generic views of data in modules
Portal – Sugar Dashlets that allow access to outside data (RSS, Web services, etc)
Charts – Data charts
Tools – Various tools such as notepad, calculator, or world clock
Miscellaneous - Any other Sugar Dashlet
The main Sugar Dashlet base class is include/Dashlets/Dashlet.php and all Sugar Dashlets should extend this class.
Sugar Dashlets are stored in the table user_preferences under the Dashlets name and home category.
The options element stores the options for the Sugar dashlet. This element is loaded/stored by storeOptions /loadOptions functions in the base Dashlet class.
Sugar Dashlet utility functions are located in include/JavaScript/Dashlets.js and contains the following:
postForm is used to post the configuration form through AJAX. The callback to remove the configuration dialog is SUGAR.sugarHome.uncoverPage.
callMethod is a generic way to call a method in a Dashlet class. Use this function to generically call a method within your Dashlet class (php side). Refresh your Dashlet after a call and utilize a callback function (optional). This method can also be used to proxy AJAX calls to Web services that do not exist in the Sugar installation, for example, Google Maps Mash-up.
Sugar's production JavaScript files are compressed with the JSMin library to improve performance. This process reduces JavaScript file sizes and download times. The originally formatted JavaScript files are located in the /jssource directory. Make JavaScript code changes in the /jssource/src_files folders and use the Rebuild JS Compressed Files option in Admin->Repair.
As of version 5.1, Sugar uses a type-ahead combo box system called QuickSearch that utilizes components from the YUI framework. The Sugar QuickSearch (SQS) code resides in the file <sugar_root>/include/javascript/quicksearch.js. This file, along with the YUI dependencies are grouped into <sugar_root>/include/javascript/sugar_grp1_yui.js which is loaded in all the main pages of SugarCRM. A custom YUI AutoComplete widget is used to pull data through an AJAX call to http://yourserver/SugarCRM/index.php. This then accesses the file <sugar_root>/modules/Home/quicksearchQuery.php.
Field is not set to disabled or readOnly
JS array sqs_objects is defined and contains the field name
sugar_grp1_yui.js must be loaded on the page
sqsNoAutofill: Add this string to the field class to disable automatic filling of the field on Blur.
When developing upgrade safe Smarty template files, you can now add Smarty functions and modifiers in the custom directory /custom/include/Smarty/plugins instead of adding them in the base directory /include/Smarty/plugins. Use a proper naming convention for the custom functions/modifiers to avoid duplicates. Also, prefix the custom files to ensure that they will not interfere with future development of the base product.
$category – Corresponds to the module directory where the bean resides. For example: Accounts.
$action – The action you want to check against. For example, Edit. These actions correspond to actions in the acl_actions table as well as actions performed by the user within the application.
$is_owner – verifies if the owner of the record is attempting an action. Defaults to false. This is relevant when the access level = ALLOW_OWNER.
See the Roles section in the Sugar Application Guide for a list of actions and their possible values.
A series of Schedulers are defined by default with every Sugar installation such as Process Workflow Tasks and Run Report Generation Scheduled Tasks.
The name of the index must start with idx_ and must be unique across the database. Possible values for type include primary for a primary key or index for a normal index. The fields list matches the column names used in the database.
By default, Sugar uses globally unique identification values (GUIDs) for primary keys for all database records. Sugar provides a create_guid() utility function for creating these GUIDs in the following format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee. The primary key column length is 36 characters.
The GUID format and value has no special meaning (relevance) in Sugar other than the ability to match records in the database. Sugar links two records (such as an Accounts record with a Contacts record) with a specified ID in the record type relationship table (e.g. accounts_contacts).
Case-sensitivity: IDs abc and ABC are treated the same in MySQL but represent different values in Oracle. When migrating data to Sugar, some CRM systems may use case sensitive strings as their IDs on export. If this is the case, and you are running MySQL, you need to run an algorithm on the data to make sure all of the IDs are unique. One simple algorithm is to MD5 the ids that they provide. A quick check will let you know if there is a problem. If you imported 80,000 leads and there are only 60,000 in the system, some may have been lost due to non-unique primary keys, as a result of case sensitivity.
Valid values are 'debug', 'info', 'error', 'fatal', 'security', and 'off'. The logger will log information for the specified and higher logging levels. For example if you set the log level to 'error' then you would see logs for 'error', 'fatal', and 'security'. You also may define your own log levels on the fly. For example if you set the value to 'test' then only values logged to $GLOBALS['log']->test('This is my test log message'); would be logged. You should avoid using the logging level of ‘off’. The default value is 'fatal'.
You may concatenate static strings, variables, and function calls to set this value. For example if you wish to have monthly logs set this to 'sugarcrm' . date('Y_m') and every day it will generate a new log file. The default value is 'sugarcrm'.
Note: If the Sugar config.php variables site_url is wrong, SugarSoap will not work. Be sure to verify this value before continuing.
SOAP, a standard Web Services protocol implementation, is a way of exchanging structured information of application functionality. The URL to SOAP is http://localhost/service/v2/soap.php, and the URL for WSDL is http://localhost/service/v2/soap.php?wsdl. The WSDL file contains the descriptions for all methods with input/output datatype.
See examples/SugarFullTest_Version2.php for more examples on usage.
Sugar uses the REST protocol to exchange application information. The URL for REST is http://localhost/service/v2/rest.php. The input/output datatype for REST is JSON/PHP serialize. These datatype files, SugarRestJSON.php and SugarRestSerialize.php, are in service/core/REST directory.
You can also define you own datatype. To do this, you need to create a corresponding SugarRestCustomDataType.php file in the service/core/REST directory and override generateResponse() and serve() functions.
The Serve function decodes or unserializes the appropriate datatype based on the input type; the generateResponse function encodes or serializes it based on the output type. See service/test.html for more examples on usage. In this file, the getRequestData function, which generates URL with json, is both the input_type and the response_type. That is, the request data from the javascript to the server is json and response data from server is also json. You can mix and match any datatype as input and output. For example, you can have json as the input_type and serialize as the response_type based on your application’s requirements.
Sugar also provides an example on how to use REST protocol to retrive data from other Sugar instances. In the example, service/example.html uses the SugarRest.server_url variable to make a request to Rest_Proxy.ph, which redirects this request to the appropriate Sugar instance and sends the response back to service/example.html . This server_url variable is a REST URL to other Sugar instances from which you want to retrieve data.
All API classes are located in the Service directory. The URL for the Service directory is http://localhost/service/vX/soap.php, where X is the version of the API that you wish to reference. The following chart indicates which versions of the API are available along with the corresponding Sugar version it was released with. If you are using a particular version of the API, note that we will not modify the API signatures for existing versions. This ensures that you can safely upgrade your SugarCRM instance without worrying about any potential impact to your existing API calls. New calls and features will be released in a newer version of the API when they are made available.
require_once('include/nusoap/nusoap.php');
$soapClient = new
nusoapclient('http://YOURSUGARINSTANCE/service/v2/soap.php?wsdl',true);
$userAuth = $soapClient->call('login',
    array('user_auth' =>
        array('user_name' => '
jim',
              'password' => md5('jim'),
              'version' => '.01'),
              'application_name' => 'SoapTest'));
$sessionId = $userAuth['id'];
$reportIds = array('id'=>'c42c1789-c8a6-5876-93a3-4c1ff15d17f6');
$myReportData = $soapClient->call('get_report_entries',
    array('session'=>$sessionId,
          '
ids'=>$reportIds));
Note: it is also possible to create a NuSOAP client as follows without requiring the WSDL:
This speeds up processing because downloading the WSDL before invoking the method is time intensive. This type of URL (http://www.example.com/sugar/soap.php) without havin ?wsdl at the end work fine with NUSOAP client. But with clients like .net, java you need to generate all the client side classes for all the complex type data types by giving appropriate WSDL (rpc or document and literal and encoded) and make a service call by coding it to those generated classes.
Image:Factories_Class_Diagram.jpgImage:Factories_Class_Diagram.jpg
Image:FormatterFactory_Class_Diagram.jpgImage:FormatterFactory_Class_Diagram.jpg
Image:Hoovers_datasource_UML.jpgImage:Hoovers_datasource_UML.jpg
Model - This is the data object built by the business/application logic needed to present in the user interface. For Sugar, it is represented by the SugarBean and all subclasses of the SugarBean.
View - This is the display layer which is responsible for rendering data from the Model to the end-user.
Controller - This is the layer that handles user events such as "Save" and determines what business logic actions to take to build the model, and which view to load for rendering the data to end users.
We can take this a step further and add assignable to the mix. An assignable module would be one that can be assigned to users. Although this is not used by every module, many modules do let you assign records to users. SugarObject interfaces allow us to add “assignable” to modules in which we want to enable users to assign records.
action_save - this is the broadest specification and gives the user full control over the Save process.
pre_save - a user could override the population of parameters from the form
post_save - this is where the view is being setup. At this point the developer could set a redirect url, do some post save processing, or set a different view
You can choose not to provide a custom action method as defined above, and instead specify your mappings of actions to files in $action_file_map. Take a look at include/MVC/Controller/action_file_map.php as an example:
As a developer, to create a custom view you would place a view.<view_name>.php file in a views/ subdirectory within the module. For example, for the DetailView, you would create a file name view.detail.php and place this within the views/ subdirectory within the module. If a views subdirectory does not exist, you must create one.
In the file, create a class named: <Module>View<ViewName>. For example, for a list view within the Contacts module the class would be ContactsViewList. Note the first letter of each word is uppercase and all other letters are lowercase.
You can extend the class from SugarView, the parent class of all views, or you can extend from an existing view. For example, extending from the out-of-the-box list view can leverage a lot of the logic that has already been created for displaying a list view.
preDisplay() - This performs pre-processing within a view. This method is relevant only for extending existing views. For example, the include/MVC/View/views/view.edit.php file uses it, and enables developers who wishes to extend this view to leverage all of the logic done in preDisplay() and either override the display() method completely or within your own display() method call parent::display().
display() - This method displays the data to the screen. Place the logic to display output to the screen here.
The ViewFactory class tries to load the view for view in this sequence, and will use the first one it finds:
The Sugar MVC provides developers with granular control over how the screen looks when a view is rendered. Each view can have a config file associated with it. So, in the example above, the developer would place a view.edit.config.php within the views/ subdirectory . When the EditView is rendered, this config file will be picked up. When loading the view, ViewFactory class will merge the view config files from the following possible locations with precedence order (high to low):

To illustrate this process, let us take a look at how the ‘popup’ action is processed. In this case, the system will go to the actions entry within the view_config and determine the proper configuration. If the request contains the parameter
to_pdf, and is set to be true then it will automatically cause the show_all configuration parameter to be set false, which means none of the options will be displayed.
The file is located under the ‘<sugar root>/include’ folder. It contains the $moduleList() array variable which contains the reference to the array key to look up the string to be used to display the module in the tabs at the top of the application, the coding standard is for the value to be in the plural of the module name; for example, Contacts, Accounts, Widgets, and so on.
The $beanList() array stores a list of all active beans (modules) in the application. The $beanList entries are stored in a ‘name’ => ‘value fashion with the ‘name’ value being in the plural and the ‘value’ being in the singular of the module name. The ‘value’ of a $beanList() entry is used to lookup values in our next modules.php variable, the $beanFiles() array.
The $beanFiles variable is also stored in a ‘name’ => ‘value’ fashion. The ‘name’, typically in singular, is a reference to the class name of the object, which is looked up from the $beanList ‘value’, and the ‘value’ is a reference to the class file. From these three arrays you can include the class, instantiate an instance, and execute module functionality.

The remaining relevant variables in the modules.php file are the $modInvisList variable which makes modules invisible in the regular user interface (i.e., no tab appears for these modules), and the $adminOnlyList which is an extra level of security for modules that are can be accessed only by administrators through the Admin page.
Used to override the location of the metadata definition file to be used. The EditView, DetailView, List View, and Popup code check for the presence of these files.
The contents of the searchdefs.php file contains the Array variable $searchDefs with one entry. The key is the name of the module as defined in $moduleList array defined in include/modules.php. The value of the $searchDefs array is another array that describes the search form layout and fields.
The searchdefs.php file is invoked from the MVC framework whenever a module's list view is rendered (see include/MVC/View/views/view.list.php). Within view.list.php checks are made to see if the module has defined a SearchForm.html file. If this file exists, the MVC will run in classic mode and use the aforementioned include/SearchForm/SearchForm.php file to process the search form. Otherwise, the new search form processing is invoked using include/SearchForm/SearchForm2.php and the searchdefs.php file is scanned for first under the custom/modules/[module]/metadata directory and then in modules/[module]/metadata.
The process() method is invoked on the generic DetailView.php instance:
)

This specifies a default panel under the panels section with three rows. The first row has two fields (name and amount). The amount field has some special formatting using the label override option. The second row contains the account_name field and the third row contains the opportunity_type column.
The display() method is then invoked on the generic DetailView instance for the final step.
When the display() method is invoked, variables to the DetailView.tpl Smarty template are assigned and the module's HTML code is sent to the output buffer.

Note also the presence of file
include/SugarFields/Fields/Address/SugarFieldAddress.js. This file is responsible for handling the logic of copying address values (from billing to shipping, primary to alternative, etc.). The JavaScript code makes assumptions using the key value of the grouped fields.
To customize various address formats for different locales, you may provide a locale specific implementation in the folder include/SugarFields/Fields/Address. There is a default English implementation provided. Locale implementations are system wide specific (you cannot render an address format for one user with an English locale and another format for another with a Japanese locale). SugarCRM locale settings are system-wide and the SugarField implementation reflects this. To modify based on a user's locale preferences is possible, but will require some customization.
The Base field is the default parent field. It simply renders the value as is for DetailViews, and an HTML text field <input type="text"> for EditViews. All SugarFields that have a corresponding PHP file extend from SugarFieldBase.php or from one of the other SugarFields.
The Bool field is responsible for rendering a checkbox to reflect the state of the value. All boolean fields are stored as integer values. The Bool field will render a disabled checkbox for DetailViews. If the field value is "1" then the checkbox field will be checked. There is no special parameter to pass into this field from the metadata definition. As with any of the fields you have the option to override the label key string.
The parent field combines a blend of a dropdown for the parent module type, and a text field with code to allow Quicksearch for quicksearch-enabled modules (see include/SugarFields/Fields/Parent/EditView.tpl file contents and JavaScript code for more information on enabling Quicksearch). There are also buttons to invoke popups and a button to clear the value. Because the parent field assumes proper relationships within the SugarCRM modules, it is not a field you can add through Studio or attempt to type override in the metadata files.
The Username field is a helper field that assumes a salutation, first_name and last_name field exists for the vardefs of the module. It displays the three fields in the format:
'audited' = Set to True if this module has auditing turned on
In the ./metadata directory, all the many-to-many relationships are defined and included in the $dictionary array. The files are stored in ./metadata/<relation_table_name>MetaData.php. Tables are generated based on these definitions. These files are included through the ./modules/TableDictionary.php. If you create a custom many-to-many relationship, you will need to add the reference to the new relationship by adding the new reference in the file custom/application/Ext/TableDictionary/tabledictionary.php. You may need to create this file if it does not exist. These changes will take effect after you clear the Sugar Cache by running the “Quick Repair and Rebuild” option from the Admin Repair screen.
The following are the definitions for $dictionary[<relation_table>]. They are similar to the Vardefs. If necessary use that page as a reference as well.
<relation_table> - the index for this relationship in the $dictionary array
table - the name of the table that is created in the database
fields - array containing arrays for each column definition. The join table must have a field for the primary key of each table to be linked, a primary key for the join table itself, a deleted field for relationship unlinking, and a date_modified field to track when the relationship changes. Additional fields can be added to track the role played by the relationship,
indices - the database indices. Note see the example for indices below for necessary values.
relationships - definitions of the relationships between the two tables
o
lhs_module - the left hand module. Should match $beanList index
o
lhs_table - the left hand table name
o
lhs_key - the key to use from the left table
o
rhs_module - the right hand module. Should match $beanList index
o
rhs_table - the right hand table name
o
rhs_key - the key to use from the right table
o
relationship_type - relationship type
o
join_table - join table used to join items
o
join_key_lhs - left table key. Should exist in table field definitions above
o
join_key_rhs - right table key. Should exist in table field definitions above
In the ./metadata directory, the relationship must exist and included in the $dictionary array. To keep consistent with the above accounts_bugs example, here is the content of the accounts_bugsMetaData.php
'subpanel_name' => 'default', // in this case, it will use ./modules/Contacts/subpanels/default.php
In the example, it would be $mod_strings['LBL_CONTACTS_SUBPANEL_TITLE'] = 'Contacts';
In the example, it would be $mod_strings['LBL_CASES'] = 'Cases';
Menu shortcuts for modules are easy to implement.. There is a ./modules/MODULE_NAME/Menu.php in all applicable modules. Shortcuts are generated through:
IMAGEFILENAME - the filename in the themes image directory
Note: A .gif extension is required for the image file and assumed in the definition.
Studio - Edit Dropdowns, Custom Fields, Layouts and Labels
Module Builder - Build new modules to expand the functionality of SugarCRM
Module Loader - Add or remove Sugar modules, themes, and language packs
Dropdown Editor - Add, delete, or change the dropdown lists in the application
Rename Tabs - Change the label of the module tabs
Configure Module Tabs and Subpanels - Choose which module tabs and sub-panels to display within the application
Configure Shortcut Bar – Select which modules are available in the Shortcuts bar.
Configure Grouped Modules - Create and edit groupings of tabs
For further information on how to use these tools, please refer to the Sugar Application Guide. This guide will go into more detail on how to use the Module Builder and the Module Loader, as well as how to extend the Sugar system at the code-level beyond what these tools provide.
When developing in Sugar, we suggest that you turn on the Developer Mode (Admin->System Settings->Advanced->Developer Mode) to get the system to ignore the cached metadata files. This is especially helpful when you are directly altering templates, metadata, or language files. When using Module Builder or Studio, the system will automatically refresh the file cache. Be sure to turn off Developer Mode when you have completed your customizations since this mode does degrade system performance.
/custom/include/language/ (for $app_strings or $app_list_strings)
If you added a $module_menu=array(); to the top of this file, you would effectively clear out any of the standard menu items. You could then replace them all with new definitions.
If the custom file is in the /custom/Extension/application/Ext/Menus/ directory, then your menu changes will affect shortcut menus in every module.
For{$modulename}.php
where modulename is the name of the module to which you are adding the sub-panel.
Fields can be edited and created using the field editor. Fields inherited from the custom module's templates can be relabeled while new fields are fully editable. New fields are added using the Add Field button. This displays a tab where you can select the type of field to add as well as any properties that field-type requires.
First, create the file AddTimeStamp.php with the following contents.
The following section outlines the parameters specified in the $manifest array contained in the manifest file (manifest.php). An example manifest file is included later for your reference.
$manifest array elements provide the Module Loader with descriptive information about the extension.
o
acceptable_sugar_flavors - Specifies which Sugar Editions the package can be installed on. Accepted values are any combination of: OS (valid prior to Sugar 5.0.0), CE (valid after Sugar 5.0.0), PRO, and ENT.
o
acceptable_sugar_versions - This directive contains two arrays:
o
author - Contains the author of the package, i.e. “SugarCRM Inc.”
o
copy_files - An array detailing the source and destination of files that should be copied during installation of the package. See the example manifest file below for details.
o
dependencies - A set of dependencies that must be satisfied to install the module. This contains two arrays:
o
description - A description of the package. Displayed during installation.

Note: Apostrophes (') are not supported in your description and will cause a Module Loader error.
o
icon - A path (within the package ZIP file) to an icon image that will be displayed during installation. Examples include: “./patch_directory/icon.gif” and “./patch_directory/images/theme.gif”
o
is_uninstallable - Setting this directive to TRUE allows the Sugar administrator to uninstall the package. Setting this directive to FALSE disables the uninstall feature.
o
name - The name of the package. Displayed during installation. Note: Apostrophes (') are not supported in your description and will cause a Module Loader error.
o
published_date - The date the package was published. Displayed during installation.
o
type - The package type. Accepted values are:
o
langpack - Packages of type langpack will be automatically added to the “Language” dropdown on the Sugar Login screen. They are installed using the Upgrade Wizard.
o
module - Packages of type module are installed using the Module Loader.
o
patch - Packages of type patch are installed using the Upgrade Wizard.
o
theme - Packages of type theme will be automatically added to the “Theme” dropdown on the Sugar Login screen. They are installed using the Upgrade Wizard.
o
version - The version of the patch, i.e. “1.0” or “0.96-pre1” .
The following section outlines the parameters specified in the $installdef array contained in the manifest file (manifest.php). An example manifest file is included later for your reference.
$installdef array elements are used by the Module Loader to determine the actual installation steps that need to be taken to install the extension.
id - A unique name for your module; for example, “Songs”
copy - An array detailing files to be copied to the Sugar directory. A source path and destination path must be specified for each file or directory. See the example manifest file below for details.
language - An array detailing individual language files for your module. The source path, destination file, and language pack name must be specified for each language file. See the example manifest file below for details.
layoutdefs - An array detailing individual layoutdef files, which are used primarily for setting up subpanels in other modules. The source path and destination module must be specified for each layoutdef file. See the example manifest file below for details.
layoutfields - An array detailing custom fields to be added to existing layouts. The fields will be added to the edit and detail views of target modules. See the example manifest file below for details.
vardefs - An array detailing individual vardef files, which are used primarily for defining fields and non many-to-many relationships in other modules. The source path and destination module must be specified for each vardef file. See the example manifest file below for details.
menu - An array detailing the menu file for your new module. A source path and destination module must be specified for each menu file. See the example manifest file below for details.
beans - An array specifying the bean files for your new module. The following sub-directives must be specified for each bean:
relationships - An array detailing relationship files, used to link your new modules to existing modules. A metadata path must be specified for each relationship. See the example manifest file below for details.
custom_fields - An array detailing custom fields to be installed for your new module. The following sub-directives must be specified for each custom field:
This array definition describes the release(s) leading to the "version" element defined in $manifest. In the sample manifest below it defines the Songs module versions 1.0 and 1.5 as preceding the current version 2.0.

To add additional function calls to the black list, add the function calls to the
blackList array. The example below blocks the strlen() and strtolower() functions from being included in the package:
To override the black list and allow a specific function to be included in packages, add the function call to the blackListExempt array. The example below removes the restriction for the file_put_contents() function, allowing it to be included in the package:
The following sample manifest file defines the $manifest and $installdef array elements for a new module (Songs) which depends on two other modules: "Whale Pod" and "Maps". In addition to defining the $manifest and $installdef array elements, it also defines the $upgrade_manifest array.
Custom Logic (or "Business Logic Hooks") allows you to add functionality to certain actions, such as before saving a bean, in an upgrade-safe manner. This is accomplished by defining hooks, which are placed in the custom/ directory, which will be called in the SugarBean in response to events at runtime. Because the code is located separate from the core SugarCRM code, it is upgrade-safe.
See this SugarForge project for a complete example of a useful business hook.
The code that declares your custom logic is located in: custom/modules/<CURRENT_MODULE>/logic_hooks.php. The format of the declaration follows.
All logic hooks should define the $hook_version that should be used. Currently, the only supported $hook_version is 1.
Your logic hook will also define the $hook_array. $hook_array is a two dimensional array:
o
name: the name of the event that you are hooking your custom logic to
o
array: an array containing the parameters needed to fire the hook
The method signature for version 1 hooks is:
o
$bean - $this bean passed in by reference.
o
$event - The string for the current event (i.e. before_save)
o
$arguments - An array of arguments that are specific to the event.
The section above shows how to create a custom_logic_hook that runs the function updateDescription() from the class updateDescription (those do not have to be the same as they are in this example) in the PHP file updateDescription.php. Below is the actual script from that PHP file.
You see that the $bean is fed into the function and allows access to all of the fields for the currently selected record. Any changes you make to the array will be reflected in the actual data. For example, in this script we are changing the description field. As shown above, there is
$event is set to whatever event is currently running like after_retrieve or before_delete.
o
In order to compare new values with previous values to see whether a change has happened, use $bean->fetched_row['<field>'] (old value) and $bean-><field> (new value) in the before_save logic hook.
o
Make sure that the permissions on your logic_hooks.php file and the class file that it references are readable by the web server. If this is not done, Sugar will not read the files and your business logic extensions will not work.
For example, *nix developers who are extending the Tasks logic should use the following command for the logic_hooks file and the same command for the class file that will be called.
o
Make sure that the entire custom/ directory is writable by the web server, or else the logic hooks code will not work properly.
By default, the metadata framework provides default implementations for Cancel, Delete, Duplicate, Edit, Find Duplicates, and Save buttons. However, you may wish to use some of the default buttons or add additional buttons. Here is an example:

Here we are adding a custom button with the label defined in the Smarty variable
{$APP.LBL_QUOTE_TO_OPPORTUNITY_LABEL}. The EDIT, DUPLICATE and DELETE buttons are rendered and then the snippet of code in this 'customCode' block is added.

Note: You do not have to necessarily create a view.edit.php file, but usually at this point of customization, you will want to add variables to your customized template that are not assigned by the generic EditView handling from the MVC framework. See the next example, Overriding the View, for more information about sub-classing the EditView and assigning Smarty variables to the resulting templates.
Here the $JSON_CONFIG_JAVASCRIPT Smarty variable was the result of a complex operation and not available via the vardefs.php file (i.e. there is no JSON_CONFIG_JAVASCRIPT declaration in the vardefs.php file).
4)
Create a directory include/SugarFields/Fields/YouTube. The name of the directory (YouTube) corresponds to the name of the field type you are creating.
5)
In include/SugarFields/Fields/YouTube directory, create the file DetailView.tpl. For the DetailView we will use the "embed" tag to display the video. In order to do this, you need to add the following to the template file:
Notes on structure of config - replace the default parameters if they are different for the page.
o
method: Unless you make a new method on the JSON server, keep this as query.
o
populate_list: This defines the id's of the fields to be populated after a selection is made.
QuickSearch will map the first item of field_list to the first item of populate_list. ie. field_list[0] = populate_list[0], field_list[1] = populate_list[1].... until the end of populate list.
o
limit: reduce from 30 if query is large hit, but never less than 12.
o
conditions: options are like_custom, contains, or default of starts with
if using 'like_custom' also define 'begin'/'end' for strings to prepend or append to the user input
o
disable: set this to true to disable SQS (optional, useful for disabling SQS on parent types in calls for example)
o
post_onblur_function: this is an optional function to be called after the user has made a selection. It will be passed in an array with the items in field_list as keys and their corresponding values for the selection as values.
4.
Assign your config array to sqs_objects (important!)
Having trouble? Take a look at the file module/Contacts/BusinessCard.php.
http://developers.sugarcrm.com/wordpress/wp-content/uploads/2011/03/Screen-shot-2011-03-22-at-4.39.10-PM.pnghttp://developers.sugarcrm.com/wordpress/wp-content/uploads/2011/03/Screen-shot-2011-03-22-at-4.39.10-PM.png
The drop-down list of operators for date range searches should now have a First Quarter choice. Selecting First Quarter creates a macro field. In this example, actual value submitted to the SearchForm code is [first_quarter]. This is because the key is defined as first_quarter.
2.
Alter the include/MVC/View/views/view.list.php.
This step is not upgrade safe, but necessary since there are a lot of files that reference this file. The code to change is in the prepareSearchForm function.
Load your custom SearchForm2.php implementation (say custom/include/SearchForm/SearchForm2.php) instead of include/SearchForm/SearchForm2.php,

function prepareSearchForm() {
...
$this->use_old_search = false;
require_once('custom/include/SearchForm/SearchForm2.php');
...}
3.
Write the code to handle your custom operator in the generateSearchWhere method of SearchForm2.php.
b.
Insert the custom operator for first_quarter handling here.
In this example, assume first_quarter to be the dates between January 1 and March 31, inclusive. Also, for brevity, this example covers mysql queries only.
The *number column is prefixed by the package and module name (ex: custom Issue module named MyIssue in package abc will have column named abc_myissue_number)
2.
Add the unified_search attributes to the fields you wish to run global search on:
$dictionary['YOUR_CUSTOM_MODULE']['unified_search'] = true;
$dictionary['YOUR_CUSTOM_MODULE']['unified_search_default_enabled'] = true;
$dictionary['YOUR_CUSTOM_MODULE']['fields']['NAME_OF_FIELD_TO_SEARCH']['unified_search'] = true;
7.
Run a global search and if the module still does not appear in the results, click on the Show All button to verify if the module’s search results have been configured for display. If not, drag the module into the Enabled Modules list and click the Search button to save your settings and run the global search again.
NOTE: It is important to separate your JavaScript into a separate JavaScript file. This is because Sugar Dashlets are dynamically added to a page through AJAX. The HTML included into JavaScript is not evaluated when dynamically included.
Creating a custom chart dashlet is very similar to creating the MyAccountsDashlet described above. The main difference is that you will need to override the display() method in your class to build the chart, using the SugarChartFactory class included with SugarCRM. Beginning in SugarCRM 6.2, we have switched the charts to be rendered through JavaScript. The SugarChartFactory returns a subclass of SugarChart. See below for an example of display() method as used in the Outcome by Month dashlet..
o
acceptable_sugar_flavors Contains which Sugar editions the package can be installed on. Accepted values are any combination of: CE, PRO, CORP, ENT, and ULT.
o
acceptable_sugar_versions This directive contains two arrays:
o
author Contains the author of the package; for example, “SugarCRM Inc.”
o
copy_files An array detailing the source and destination of files that should be copied during installation of the package. See the example manifest file below for details.
o
description A description of the package. Displayed during installation.
o
icon A path (within the package ZIP file) to an icon image that will be displayed during installation. Examples include “./patch_directory/icon.gif” and “./patch_directory/images/theme.gif”
o
is_uninstallable Setting this directive to TRUE allows the Sugar administrator to uninstall the package. Setting this directive to FALSE disables the uninstall feature.
o
name The name of the package. Displayed during installation.
o
published_date The date the package was published. Displayed during installation.
o
type The package type. This should be set to “theme”
o
version The version of the patch, i.e. “1.0” or “0.96-pre1”
Note: You can also set the default language in the config.php. This value is used if a user does not specify a language while logging into the application.
Note: Some language files that ship with Sugar are not named “en_us.lang.php” but are “.html” or “.tpl” files. These files are used for the inline help system. A complete language pack will include the translated versions of these files as well.
Note: In the include/language/<new>.lang.php file, you will see that there are two global arrays defined. The $app_list_strings array is actually an array of arrays. The key values in this array must not be changed. There are comments and examples in the code that should keep you on track.
Note: Be careful to choose a language pack that is up to date and is working.
o
Optionally, include localized Help files for each view in each module. For example, for the Portugese (Brazilian) language pack, you would include pt_br.help.index.html (for List View), pt_br.help.DetailView.html (for Detail View), and pt_br.help.EditView.html (for Edit View).
team_security_diagrm
SugarpdfDiag
ViewSugarpdf (include/MVC/View/views/view.sugarpdf.php)
module=<mymodule>&action=sugarpdf&sugarpdf=<XXX>
Header - This method override the regular Header() method to enable the custom image directory in addition to the OOB image directory.
SetFont - This method override the regular SetFont() method to enable the custom font directory in addition to the OOB font directory.
Cell - Handle HTML entity decode.
getNumLines - This method is a fix for a better handling of the count. It handles the line break between words.
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 - 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
This file is included by Sugarpdf.php. This php file is a utils file. It contains many functions that can be used to generate PDFs.
The font list build by the font manager with the listFontFiles() or getSelectFontList() is saved in a cached php file cache/Sugarpdf/cachedFontList.php to prevent to parse the fonts folder every time (if the cached file don't already exist). This file is automatically cleared when the delete() or add() methods are used. When you create a Font loadable module you will have to call the clearCachedFile() method in a post_execute and post_uninstall actions to clear the cache. Like that, the cache will be rebuild with the last infos.
include/Sugarpdf/sugarpdf_default.php is used to store the default value of the PDF settings (system and user).
You can overwrite any default value using custom/include/Sugarpdf/sugarpdf_default.php.
1.
1.
Add the file custom/modules/<myModule>/sugarpdf/sugarpdf.<mySugarpdf>.php
a)
require include/Sugarpdf/Sugarpdf.php
Warning: HTML and CSS support in writeHTML() is limited. For more details, read the TCPDF documentation
Add custom/modules/Contacts/sugarpdf/sugarpdf.test.php with this content :
Add custom/modules/Contacts/tpls/test.tpl with this content :
Generate the PDF file using this URL : module=Contacts&action=sugarpdf&sugarpdf=test
Create the directory custom/include/tcpdf/fonts if it is not created
Copy these files into the directory custom/include/tcpdf/fonts
Create the directory custom/include/tcpdf/fonts if it is not created
Create custom/modules/Configurator/metadata/SugarpdfSettingsdefs.php
Note: You can view all the available settings in modules/Configurator/metadata/SugarpdfSettingsdefs.php (commented and not commented).
1.
For example, to enable the POP3 protocol, the config_override.php file would have the following entry set:
Formula: An expression that conforms to the Formula Engine syntax consisting of nested functions and field variables.
Function: A method which can be called in a formula.
Trigger: A Formula which evaluates to either true or false. Triggers are evaluated whenever a field in the equation is updated or when a record is retrieved/saved.
Action: A method which modifies the current record or layout in some way.
Dependency: A complete logical unit which includes a trigger and one or more actions.
Basic addition: add(1, 2)
Boolean values: not(equal($billing_state, "CA"))
Calculation: multiply(number($employees), $seat_cost, 0.0833)
Sugar Logic has several fundamental types. They are: number, string, boolean, and enum (lists). Functions may take in any of these type or combinations thereof and return as output one of these types. Fields may also often have their value set to only a certain type.
A string type is very much like a string in most programming languages. However, it can only be declared within double quotes. For example, consider this function which returns the length of the input string:
A boolean type is simple. It can be one of two values: true or false. This type mainly acts as a flag, as in whether a condition is met or not. For example, the function contains takes in as input two strings and returns true if the first string contains the second string or false otherwise.
Alternatively, the createList function (an alias to enum) can be used to create enums in a formula.
This function would appropriately return an enum type containing "hello world!", false, and 25 as its elements.
A link represents one side of a relationship and is used to access related records. For example, the accounts link field of Contacts is used to access the account_type field of the Account related to a Contact:
A Dependency describes a set of rules based on a trigger and a set of actions. Examples include a field whose properties must be updated dynamically or a panel which must be hidden when a drop down value is not selected. When a Dependency is triggered it will appropriately carry out the action it is designed to. A basic Dependency is when a field's value is dependent on the result of evaluating a Expression. For example, consider a page with five fields with It’s "a", "b", "c", "d", and "sum". A generic Dependency can be created between "sum" and the other four fields by using an Expression that links them together, in this case an add Expression. So we can define the Expression in this manner: 'add($a, $b, $c, $d)' where each field id is prefixed with a dollar ($) sign so that the value of the field is dynamically replaced at the time of the execution of the Expression.
An example of a more customized Dependency is when the field's style must be somehow updated to a certain value. For example, the DIV with id "temp" must be colored blue. In this case we need to change the background-color property of "temp". So we define a StyleAction in this case and pass it the field id and the style change that needs to be performed and when the StyleAction is triggered, it will change the style of the object as we have specified.
A dependent field will only appear on a layout when the associated formula evaluates to the Boolean value true. Currently these cannot be created through Studio and must be enabled manually with a custom vardef or vardef extension. The “dependency” property contains the expression that defines when this field should be visible. An example field that only appears when an account has an annual revenue greater than one million.
Starting in 6.2, we now have the ability to define custom dependencies via metadata. The files should be located in custom/Extension/modules/{module_name}/Ext/Dependencies/{dependency_name}.php and be rebuilt with a quick repair after modification.
hooks: Defines when the dependency should be evaluated. Possible values are edit (on edit/quickCreate views), view (Detail/Wireless views), save (during a save action), and all (any time the record is accessed/saved).
trigger: A boolean formula that defines if the actions should be fired. (optional, defaults to ‘true’)
triggerFields: An array of field names that when when modified should trigger re-evaluation of this dependency on edit views. (optional, defaults to the set of fields found in the trigger formula)
onload: If true, the dependency will be fired when an edit view loads (optional, defaults to true)
actions: An array of action definitions to fire when the trigger formula is true.
notActions: An array of action definitions to fire when the trigger formula is false. (optional)
Custom functions will be stored in "custom/include/Expressions/Expression/{Type}/{Function_Name}.php". The first step in writing a custom function is to decide what category the function falls under. Take for example a function for calculating the factorial of a number. In this case we will be returning a number so we will create a file in "custom/include/Expressions/Expression/Numeric/" called "FactorialExpression.php". In the new PHP file we just created, we will define a class called FactorialExpression that will extend NumericExpression. All formula functions must follow the format "{functionName}Expression.php" and the class name must match the file name. Next we need to decide what parameters the function will accept. In this case, we need take in a single parameter, the number to return the factorial of. Since this class will be a sub-class of NumericExpression, it by default accepts only numeric types, we need not worry about specifying the type requirement.
Next, we must define the logic behind evaluating this expression. So we must override the abstract evaluate() function. The parameters can be accessed by calling an internal function getParameters() which returns the parameters passed in to this object. So with all this information we can go ahead and write the code for the function.
One of the key features of Sugar Logic is that the functions should be defined in both php and javascript, and have the same functionality under both circumstances. As you can see above, the getJSEvaluate() method should return the JavaScript equivalent of your evaluate() method. The JavaScript code is compiled and assembled for you after you run the “Rebuild Sugar Logic Functions” script through the admin panel.
Using custom actions, you can easily create reusable custom logic or integrations that can include user-editable logic using the Sugar Formula Engine. Custom actions will be stored in "custom/include/Expressions/Actions/{ActionName}.php". Actions files must end in "Action.php" and the class defined in the file must match the file name and extend the "AbstractAction" class. The basic functions that must be defined are "fire", "getDefinition", "getActionName", "getJavascriptClass", and "getJavscriptFire". Unlike functions, there is no requirement that an action works exactly the same both server and client side as this is not always sensible or feasible.
A simple action could be a "WarningAction" that shows an alert warning the user that something may be wrong, and logs a message to the sugarcrm.log file if triggered on the server side. It will take in a message as a formula so that the message can be customized at run time. We would do this by creating a php file in "custom/include/Expressions/Actions/WarningAction.php". containing the following code:
* @return string javascript.
* @return string javascript.
* @param SugarBean $target
Let us say we were building a new Action called "SetZipCodeAction" that uses the yahoo geocode API to get the zip code for a given street + city + state address.
First, we should add a new action that acts as the proxy for retrieving data from the Yahoo API. The easiest place to add that would be a custom action in the "Home" module. The file that will act as the proxy will be "custom/modules/Home/geocode.php". It will take in the parameters via a REST call, make the call to the Yahoo API, and return the result in JSON format.
We are now ready to write our Action. Start by creating the file custom/include/Expressions/Actions/SetZipCodeAction.php. This file will use the proxy function directly from the php side and make an asynchronous call on the javascript side to the proxy.
Make a REST call to oauth_request_token method (supported in REST API version 4) to create a Request Token. Example using PHP OAuth extension:
The PHP OAuth extension method getRequestToken automatically parses the string and returns it as an array, other clients parse the string manually.
Again, the PHP OAuth extension method getAccessToken automatically parses the string and returns it as an array; other clients parse the string manually.
You will receive a JSON response which will have session ID as id value. Use this ID as session parameter to other calls.

User Contributed Comments

No user comments found.

Add a Comment
E-mail:
Comment:
Have feedback for us? Drop us a line.
Terms & Conditions | Privacy | Trademark Info | Contact Info | FAQs | SugarCRM Inc.© 2004 - 2009 All rights reserved.