Code Type
From dispage wiki
Overview
Once installed Enhanced Studio, Administrator finds a new field type (“Code”) in the SugarCRM Studio field list. This is the basic element from which to start to customize SugarCRM. The first step is to create a Code-type field in any SugarCRM module, then the field is available to be added to any View.
WARNING : From 3.1 release, Code Fields have the same functionalities in SugarCRM Studio and Module Builder.
How to create a “Hello World !” Code Field
Step 1
In the “Admin” → “Studio” tool, click the “Fields” link of the module to customize (“Cases” in the example in Figure 1).
Step 2
Select “Code” in the “Data Type” dropdown at the top of the field page. A mask like the one in Figure 1 will appear.
The mask contains all the standard SugarCRM type options, plus the followings:
- Logic Hook selector (FULL)
- Default Value input field
- Max Size input field
- Precision input field
- DB Type selector
- Code Edit Area Tool
(FULL) The Logic Hook selector has been added to specify a Logic Hook to assign the code to, as explained in paragraph Logic Hook Programming Interface. To have a Code field PHP-eval()’d each time it is accessed to (as in the old Enhanced Studio releases), “Default” option must be selected.
The DB Type selector allows to choose whether the Code field must be created in the DB or not and its type. To create a static Code field (with no DB value to store, as explained in the Overview section), the DB Type input field must be set to “Non-DB”.
If DB Type has a value different from “Non-DB” a dynamic Code field with the selected type will be created in SugarCRM Database.
The Default Value, Max Size and Precision fields come in use to further customize the field as it is created in the DB.
The Code EditArea Tool allows to enter the PHP code that is run-time eval()’d as the field is accessed for being viewed or edited, or when the related logic hooks is triggered.
In this “Hello world !” example a static Code field named “helloworld” (which will be automatically renamed into “helloworld_c” by SugarCRM Studio) is being creating with the simple Code
echo "HELLO !";
No change involves the Database, the only action performed as the field is viewed, listed or edited (depending on the Layout it is put into) is to write the string “HELLO !”.
PHP Code can be developed directly from inside the SugarCRM application thanks to the EditArea tool.
(FULL) Additionally, a PHP Online Syntax Checking is performed on the PHP code before saving the Code field.
Step 3
Save the field
Step 4
Add the new Code field to any View or Subpanel.
Available Layouts are “EditView”, “DetailView”, “ListView”, “QuickCreate”, “Search”, “Sugar Dashlet” and “Popup View” (the last is supported from SugarCRM ver. 6).
WARNING : Only dynamic fields should be added to the Search Layouts since static fields are not created in the Database and so they cannot be searched for.
If the “helloworld” field of this example is added, for instance, to the “ListView” Layout, the Cases Module looks like the one in the Figure 2.
EditArea tool
The EditArea Tool includes some features very useful to developers such as :
- PHP specific syntax highlight
- Parenthesis highlighting.
- Line numbers
- Search & Replace Tool
- Undo & Redo
- Resizable Editor Panel
- Extra Javascript, CSS and HTML syntax-highlighting support
- Graphic HTML Symbol tool
- Word-wrap line option
EditArea Tool is released under © 2008-2010 Christophe Dolivet. Licensed under LGPL, Apache and BSD licenses.
Website: http://www.cdolivet.com/index.php?page=editArea
PHP Online Syntax Checking (New in 3.1.04)
(FULL) Before saving Code Type fields (as well as AJAX Callback fields (New in 3.1.04)) an online checking is automatically performed on PHP syntax of the Default code and all the Logic Hooks in the field.
If any syntax error/warning occurs, the field is not saved and the error text is reported in both an alert popup (Figure 4) and an error mark placed on the left of the code (Figure 5).
Notes:
- If multiple errors occur, only the first error of the first Logic Hook encountered is returned.
- PHP code is submitted to dispage server with the sole purpose of validating the PHP syntax, then the result is sent back to client. Dispage do not keep any copy of the PHP code.
- Total size of PHP code must be less than 64 Kbytes for each submission.
- Only Compile-time parse errors and warnings are detected. Run-time errors and warnings depend on the execution context and are excluded from syntax checking.
- Online Syntax Checking can be disabled from Enhanced Studio Configuration (New in 3.1.04).
WARNING: Dispage does not warrant that the PHP Online Syntax Checking Service will be error-free, uninterrupted or will meet any particular criteria of accuracy, completeness or reliability of information, performance or quality.
Advanced Code-type field management
As explained in the previous paragraph, when a Code field type is selected in SugarCRM Studio a Code specific mask appears. The mask has the standard input fields in common with other SugarCRM field types, and in addition it has the specific fields listed below:
Logic Hook selector (FULL)
The logic Hook Selector is the switch to access the new Logic Hook Programming Interface (LHPI). Postponing this topic to the next Paragraph, “Default” option causes the Code field to be PHP-eval()’d each time it is accessed to.
This means that the PHP Code entered in the “Code” entry while Logic Hook is set to “Default” is run-time executed when a record containing that field is edited or viewed from any SugarCRM Layout.
WARNINGS:
- Default Logic Hook option is the basic Code option and grants the backward compatibility with the Code fields developed with Enhanced Studio rel. < 3.1.
- The Logic Hook is a switch that allows to view/edit the code of all the Logic Hooks: if changed it simply switches the entries of the Panel from one selection to the other.Each entry value is kept in memory and retrieved automatically when the Logic Hook selection changes.
DB Type selector
The “DB Type” value switches the kind of Code field generated:
Static (Non-DB) field
To select a static field just leave the “Non-DB” option selected.
This kind of field is executed only at run-time and does not need to be stored/retrieved to/from DB, so when a static field is created no field is physically added to the Database.
It can be used for many kinds of elements that do not need to store a value to the Database, for example buttons that do any action or fields containing operations on the content of other fields, that need to be executed each time they are viewed.
All the Code fields of the Enhanced Studio releases prior to 2.0 belong to this category.
An example a bit more useful than the “Helloworld” is the Opportunities warning on amount reported in the Samples Section.
Dynamic field
From the Enhanced Studio 2.0 release, Code fields can store/retrieve values of any type to/from Database, exactly like other SugarCRM fields.
The PHP code assigned to these fields is also eval()’d at run-time and the field values retrieved from the DB can be used from inside the PHP code itself (a standard SugarCRM Text field is reproduced in the SugarCRM standard text field sample for teaching purposes).
Dynamic fields are created in the Database according to the DB type selected and the DB Engine in use, as detailed in Table 3.
| | | |
Non-DB | - | - | - |
Int | Int | Int | number |
Double | Double | Float | number(30,10) |
Float | Float | Float | number(30,6) |
Uint | int unsigned | Int | number(15) |
Ulong | bigint unsigned | Int | number(38) |
Long | Bigint | bigint | number(38) |
Short | smallint | smallint | number(3) |
Varchar | varchar | varchar | varchar2 |
Text | text | text | clob |
Longtext | longtext | text | clob |
Date | date | datetime | date |
Enum | varchar | varchar | varchar2(255) |
Relate | varchar | varchar | varchar2 |
Multienum | text | text | clob |
Html | text | text | clob |
Datetime | datetime | datetime | date |
Time | time | datetime | date |
Bool | bool | bit | number(1) |
Tinyint | tinyint | tinyint | number(3) |
Char | char | char | char |
Blob | blob | image | varchar2(36) |
Longblob | longblob | Image | blob |
Currency | decimal(26,6) | Decimal | blob |
Decimal | decimal | Decimal | number(26,6) |
Decimal2 | decimal | Decimal | number(20,2) |
Id | char(36) | varchar(36) | number(30,6) |
Table 3
Default Value entry
A default value can be entered for each Dynamic field, according to the “DB Type” selected (the Default Value is ignored for Static fields).
This entry is disabled for “text”, “longtext”, “multienum” , “blob” and “longblob” DB-Types to follow a constraint of the DB Engines.
WARNING: If “Varchar” DB Type is selected the default value is automatically set to 255.
This value can be changed if needed but in no case must left blank or the Varchar field will not be created correctly in the DB.
Max Size entry
A max character length can be assigned to the Dynamic fields to optimize Database disk space usage. The Max Size is ignored for Static fields and for those fields having a fixed conversion Size by default (see the conversion “DB Type” table above).
Precision entry
This entry is used to specify the 2nd parameter in the SQL creation string of the field (it indicates the precision for the “Double”, “Float” and “Decimal” types).
WARNING: Precision is automatically set to 4 for “Float” DB-Types. This value can be changed if needed but should not left blank or the Float field might not be created correctly when using the MySQL DB Engine.
Code entry
The content of the "Code" entry is a PHP code which is run-time eval()’d as the field is viewed or edited.
Any operation can be performed from PHP code, for example adding any HTML or any JavaScript Code (even using AJAX functions or jQuery, which is natively supported from 3.1) anywhere in any SugarCRM view.
Dynamic field value can be referred to as
$bean-><field_name>
in the PHP code. For example the first name of a contact can be easily displayed through a Code field in Contacts Module with this simple PHP code:
echo $bean->first_name;
The code to refer to a custom “try” field is (note that the “_c” prefix is automatically added to the custom field name by SugarCRM Studio):
echo $bean->try_c;
Here’s a complete list of the variables that can be accessed from inside the PHP Code :
- & $bean(the bean object of the specific record)
- $event (containing useful info about the specific view)
- $args
- $GLOBALS
The exact content of the variables should need an in-depth examination that involves SugarCRM application structure and would go beyond the aim of this Manual. However, the following is a useful suggestion to explore the content of these variables while they are run-time eval()’d, and for more general Debug purposes.
Simply add the following debugging line to the Code:
error_log ( print_r ( <variable>, true ), 3, "<log_file>");
Where:
- <variable> is a variable to watch, chosen among the previous list
- <log_file> is the path to a writable log file (for example “/tmp/watch.txt”)
Then, once accessed to any page from which the Code field is called, the content of the variables can be found in the specified log file.
WARNING: Please remember to delete the error_log line from the code after finished, or it will carry on appending data to the log file every time the field is accessed.
This Guide cannot go into the specific code language syntax and the SugarCRM application structure. However, it provides an exhaustive Samples / Scenarios section with a great wealth of scenarios.
After created, fields can be added to almost any Layout and almost any action can be performed on them (depending on their types) as described in Table 4.
Action Field DB-Type
| | | |
Quick Create | | | |
Detail View | | | |
Edit | | | |
List View | | | |
Basic/Advanced Search | | | |
Dashlet View | | | |
Subpanel View | | | |
Popup View (SugarCRM 6) | | | |
Import | | | |
Order By (List View) | | | |
Reported (in Sugar PRO / ENT Report Module) | | | |
Table 4
Numeric Code DB fields are also recognized by the Enhanced Search plugin (http://www.dispage.com/products/enhanced-search ) and can be searched using the Enhanced Search numeric operators.
How to modify an existing Code-type field
Both static and dynamic Code fields can be modified after they have been deployed from the SugarCRM Studio tool according to requirements. The only important limitation comes from the Database constraints and is resumed in the following warnings.
WARNINGS
- DB Type of a Code field must not be changed from static to dynamic in any case.
- DB Type must not be modified to an incompatible Db Type (i.e. from “text” to “integer”) when the related Database field contains any not-empty value (that might also happen when no row is shown in SugarCRM, as rows are logically but not physically deleted).
This obviously leads to an error if such DB values cannot be automatically converted by the DB Engines. Thus, it is allowed to change dynamic fields even after they have been created, but the related field in the Database must be manually emptied if the specific DB type conversion is not supported by the DB Engine.
Moreover, if a Dynamic Code field is changed to a Static field after it has been created in SugarCRM Studio, the related DB field is not automatically removed from the Sugar tables, and should be manually deleted in order to save Database space.
Enhanced Studio is a very powerful tool that allows deep after-deployment changes: this feature fully balances the precautions expressed in this paragraph.
Logic Hook Programming Interface
(FULL) From Enhanced Studio 3.1, Code fields have become a powerful tool to program the SugarCRM Logic Hooks. The main advantages in using Enhanced Studio’s Logic Hooks Programming instead of manually modifying custom files are
- Ease of managing: Logic Hooks are logically linked to a Code field and can be managed from inside the SugarCRM Studio or Module Builder thanks to the Logic Hook Programming Interface (LHPI).
- Ease of programming: PHP code of AJAX callbacks can be entered from the PHP EditArea tool SugarCRM Studio or Module Builder and debugged with the PHP Online Syntax Checking
- Logic Hooks seamlessly exported / imported: Logic Hooks made with LHPI are automatically included in any published / exported package they belong to, and they are seamlessly rebuilt in any SugarCRM installation in which the packages are installed.
The key element to pilot the LHPI is the “Logic Hook” selector. Actually it is not a common selector, it is rather a switch giving an additional info on which logic hooks are currently valued (as in Figure 6). Each Code field can perform 16 distinct actions (with 16 different PHP codes), one for each Logic Hook.
Figure 6
Plus, the “Default” abstract Logic Hook, that is the PHP executed each time the field is accessed from any View (technically the PHP Code of “Default” abstract Logic Hook is linked to “process_record” and “after_retrieve” basic Logic Hooks) is available. This is the option with the entries of the Code fields generated with Enhanced Studio Versions prior to 3.1 .
Thus, to enter the Code for a specific Logic Hook it is enough to select it and enter the PHP script in the Code entry.
Figure 7
All the SugarCRM logic hooks are supported by LHPI as reported in Table 5.
Since more than one Logic Hook of the same type can exists (taking into consideration that Logic Hooks can be also programmed directly from the SugarCRM code), the LHPI allows to assign directly an order of execution to each Logic Hook (Figure 7) .
| | |
after_ui_frame | | |
after_ui_footer | | |
server_round_trip | | |
before_delete | | |
after_delete | | |
before_restore | | |
after_restore | | |
before_retrieve | | |
after_retrieve | | |
before_save | | |
after_save | | |
process_record | | |
after_login | | |
before_logout | | |
after_logout | | |
login_failed | | |
Table 5
When the Logic Hook selection changes, all the entries of that Logic Hook are kept in browser’s memory (and retrieved as the Logic Hook option is re-selected) until they are permanently saved as the Code field is saved.
To help the Administrator to keep under control all the Logic Hooks at a time, Logic Hooks with a non-empty Code entry are green-highlighted in the dropdown menu of the Logic Hook selector.
Even though Logic Hooks are programmed from inside a Code field, they are not necessary bound to the field itself and can be triggered even by events not directly related to the field.
There are three Trigger Levels of Logic Hooks, related to the context in which they are fired (see Table 5):
- Field: Logic Hook is fired by an event in which the Code field is involved.
- Module: Logic Hook is fired by an event in which is involved the Module that the Code field belongs to.
- Application: Logic Hook is fired by an event not related to the Code field.
Logic Hooks are discussed in detail at the following SugarCRM wiki page:
http://www.sugarcrm.com/wiki/index.php?title=Logic_Hooks
LHPI: A working Example
If a Code field is created in the Accounts Module with the code
echo "<div>This Appears after the Frame!!!!</div>";
in the “after_ui_frame” Logic Hook like in Figure 6, the result is the one in Figure 8.
Figure 8
Code Fields and Dispage Extension Manager Framework
Since Enhanced Studio is a managed through Dispage Extension Manager (DEM), the Javascript Framework included in DEM is available from the PHP code of Code fields.
The following libraries are included in DEM ver. 1.0.09 (info on copyright and licenses can be found at http://www.sugarforge.org/frs/download.php/6328/LICENSE.txt):
- JQuery-1.4.2 ( http://jquery.com/ )
- JQuery-UI-1.8.4 ( http://jqueryui.com/ )
- Boxy-0.1.4 ( http://onehackoranother.com/projects/jquery/boxy/ )
- JGrid-3.7.2 ( http://www.trirand.com/blog/ )
If used in conjunctions with Logic Hooks, the range of Enhanced Studio customizations widens even further.
The sample “Multiple File Upload” is, among the others, a working example of jQuery usage in a Code field: examples of usage of jQuery ID Selector, “$.attr” and “$.remove” APIs can be found in it.
Another jQuery sample is “Generic AJAX Call (using jQuery)” with an example of the jQuery “$.ajax” API usage.
An AJAX working example is Autocomplete AJAX country field (New in 3.1.04). Some useful jQuery and AJAX snippets are shown in it:
- How AJAX Callback can be programmed from SugarCRM web application thanks to the AJAX Callback fields (New in 3.1.04)
- The usage of the UI Autocomplete Widget (included in jQuery-UI)
- The usage of jQuery “.ready” API, to execute a javascript code after the DOM is completely loaded