SugarBean

From SugarCRM Wiki

Jump to: navigation, search

Contents

SugarBean Overview

SugarBean is the base class for all business objects in Sugar. It implements the primary functionality needed for manipulating business objects: create, retrieve, update, delete. It allows for searching and retrieving list of records. It allows for retrieving related objects (e.g. contacts related to a specific account).

In the current implementation, there can only be one bean per folder. Naming convention has the bean name be the same as the module and folder name. All bean names should be singular (e.g. Contact). The primary table name for a bean should be plural (e.g. contacts).

The SugarBean handles everything based on the Module Definitions.

SugarBean Properties (Class Variables)

$db

A pointer to the database helper object DBHelper

Do not use this pointer in it's GLOBAL state like $db->query, alway go through the instance like $focus->db->query.

$new_schema

Does this bean participate in the new schema. All modules should be new schema at this point. New schema means that you have a GUID in the id field. This is a boolean value of true or false.


Default Value = false


$new_with_id

When creating a bean, you can specify a value in the id column as long as that value is unique. During save, if the system finds an id, it assumes it is an update. Setting new_with_id to true will make sure the system performs an insert instead of an update. This is a boolean value of true or false.


Default Value = false

$new_assigned_user_name

This holds the full name of the user that an item is assigned to. Only used if notifications are turned on and are going to be sent out. This value is a String.


$processed_dates_times

An array of booleans. This array is cleared out when data is loaded. As date/times are converted, a 1 is placed under the key, the field is converted. This is an Array of Booleans.


Default Value = false for during inital data load from database.


$process_save_dates

Whether to process date/time fields for storage in the database in GMT. This is a boolean of true or false.


Default Value = true


$save_from_post

This signals to the bean that it is being saved in a mass mode. Examples of this kind of save are import and mass update. We turn off notifications of this value in the case of an import or mass update in order to make things more efficient. This is a boolean value of true or false.


Default Value = true

$duplicates_found

When running a query on related items using the method: retrieve_by_string_fields this value will be set to true if more than one item matches the search criteria. This is a boolean value of true or false.


Default Value = false

$dbManager

The DBManager instance that was used to load this bean and should be used for future database interactions.


$deleted

This is true if this bean has been deleted, false otherwise. This is a Boolean value where 0 = false and 1 = true.


Default Value = 0 (false)


$update_date_modified

Should the date modified column of the bean be updated during save? This is used for admin level functionality that should not be updating the date modified. This is only used by sync to allow for updates to be replicated in a way that will not cause them to be replicated back. This is a boolean value of true or false.


Default Value = true


$update_modified_by

Should the modified by column of the bean be updated during save? This is used for admin level functionality that should not be updating the modified by column. This is only used by sync to allow for updates to be replicated in a way that will not cause them to be replicated back. This is a boolean value of true or false.


Default Value = true


$update_date_entered

Setting this to true allows for updates to overwrite the date_entered. This is a boolean value of true or false.


Default Value = false


$set_created_by

This allows for seed data to be created without using the current user to set the id. This should be replaced by altering the current user before the call to save. This is a boolean value of true or false.


Default Value = true

$table_name

This is the database table where records of this Bean are stored. This is fetched automatically from Vardefs. If this bean is extended and is defined in the extended bean, this will make the Vardef table name to be ignored. This is a String value.


Default Value = '' (empty String)

$object_name

This is the singular name of the bean. (i.e. Contact). This needs to be defined in the module bean. This is a String.


Default Value = '' (empty String)


$module_dir

The name of the module folder for this type of bean. (i.e. Contacts - This is the plural form) This is a String that should be defined in the module bean extension.


Default Value = '' (empty String)


To Document Yet

  • $field_name_map;
  • $field_defs;
  • $custom_fields;
  • $column_fields = array();
  • $list_fields = array();
  • $additional_column_fields = array();
  • $current_notify_user;
  • $fetched_row=false;
  • $layout_def;
  • $force_load_details = false;
  • $optimistic_lock = false;
  • $disable_custom_fields = false;
  • $number_formatting_done = false;

SugarBean Methods

SugarBean()

Constructor for the bean, it performs following tasks.


  1. Intializied as database connections
  2. load the vardefs for the module implemeting the class. cache the entries if needed.
  3. Setup row-level security preference.


All implementing classes must call this constructor usig the parent::SugarBean() class.


param: none

return: nothing


getObjectName()

Returns the object name. If object_name is not set table_name is returned.


All implemeting clases must set a value for the object_name variable.


param: none

return: nothing


getAuditEnabledFieldDefinitions()

Returns a list of fields with their definition that have the audited property set to true. Before calling this function check whether audit has been enabled for the table/module or not. You would set the audit flag in the implemting module's vardef file.


param: none

return: an array of


is_AuditEnabled()

Return true if auditing is enabled for this object. You would set the audit flag in the implemting module's vardef file.


param: none

return: boolean


get_audit_table_name()

Return's name of the audit table. Audit table's name is based on implemeting class' table name.


param: none

return: String Audit table name.


create_audit_table()

If auditing is enabled create the audit table.


Function is used by the install scripts and a repair utility in the admin panel


Internal function, do not override.


getTableName()

Return's the implementing class' table name.


All implemetning classes set a value for the table_name variable. This value is returned as the table name. If not set table name is extracted from the implementing module's vardef.


return: String Table name.


getFieldDefinitions()

Return's field definitions for the implementing module.

The definitions were loaded in the constructor.


return: Array Field definitions.


getIndices()

Return's index definitions for the implementing module.


The definitions were loaded in the constructor.


return: Array Index definitions.


getFieldDefinition($name)

Return's field definition for the requested field name.


The definitions were loaded in the constructor.


param: string field name,

return: Array Field properties.


getPrimaryFieldDefinition()

Return's definition for the id field name.


The definitions were loaded in the constructor.


return: Array Field properties.


getFieldValue($name)

Return's value for the requested field.


When a row of data is fetched using the bean, all fields are created as variables in the context of the bean and then fetched values are set in these variables.


param: string field name,

return: varies Field value.


removeRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir)

Remove relationship metadata cache.


Every module that has relationships defined with other modules, has this meta data cached. The cache is stores in 2 locatios,relationships table and file system. This method clears the cache from both locations.


param: string $key module whose meta cache is to be cleared.

param: string $db database handle.

param: string $tablename table name

param: string $dictionary vardef for the module

param: string $module_dir name of subdirectory where module is installed.

return: Nothing


remove_relationship_meta($key,$db,$log,$tablename,$dictionary,$module_dir)

This method has been deprecated.


createRelationshipMeta($key,$db,$tablename,$dictionary,$module_dir,$iscustom=false)

This method populates the relationship meta for a module.


It is called during setup/install. It is used statically to create relationship meta data for many-to-many tables.


param: string $key name of the object.

param: object $db database handle.

param: string $tablename table, meta data is being populated for.

param: array dictionary vardef dictionary for the object. *

param: string module_dir name of subdirectory where module is installed.

param: boolean $iscustom Optional,set to true if module is installed in a custom directory. default value is false.


create_relationship_meta($key,&$db,&$log,$tablename,$dictionary,$module_dir)

This method has been deprecated.


load_relationship($rel_name)

Loads the request relationship. This method should be called before perfoming any operations on the related data.


This method searches the vardef array for the requested attribute's definition. If the attribute is of type link then create's a similary named variable and loads the relationship definition.


param: string $rel_name relationship/attribute name.

return: nothing.


load_relationships()

Loads all attributes of type link.


Method searches the implmenting modules vardef file for attributes of type link, and for each attribute create a similary named variable and load the relationship definition.


return: Nothing


get_linked_beans($field_name,$bean_name, $sort_array = array(), $begin_index = 0, $end_index = -1, $deleted=0, $optional_where="")

Returns an array of beans of related data.


For instance, an account is related to 10 contacts , this function will return an array of contacts beans (10) with each bean representing a contact record. Method will load the relationship if not done so already.


param: string $field_name relationship to be loaded.

param: string $bean name class name of the related bean.

param: array $sort_array optional, unused

param: int $begin_index Optional, default 0, unused.

param: int $end_index Optional, default -1

param: int $deleted Optional, Default 0, 0 adds deleted=0 filter, 1 adds deleted=1 filter.

param: string $optional_where, Optional, default empty.

optional_where is an array like this one :

array("lhs_field"=>"myfield",
 "operator"=>"=",
"rhs_value"=>'johndoe')

get_linked_fields()

Returns an array of fields that are of type link.


return: array List of fields.


delete_linked($id)

Iterates through all the relationships and deletes all records for each relationship.


param: string $id Primary key value of the parent record

create_tables()

Create tables for the module implementing the class. If you override this function make sure that your code handles the table creation.


drop_tables()

Delete the primary table for the module implementing the class. If custom fields were added to this table/module, the custom table will be removed too, along with the cache entries that define the custom fields.


setupCustomFields($module_name, $clean_load=true)

Loads the definition of custom fields defined for the module. Local file system cache is created as needed.


param: string $module_name setting up custom fields for this module.

param: boolean $clean_load Optional, default true, rebuilds the cache if set to true.


save($check_notify = FALSE)

This method implements a generic insert and update logic for any SugarBean. This method only works for subclasses that implement the same variable names. This method uses the presence of an id field that is not null to signify and update. The id field should not be set otherwise.


param: boolean $check_notify Optional, default false, if set to true assignee of the record is notified via email.


has_been_modified_since($date, $modified_user_id)

Performs a check if the record has been modified since the specified date


param: date $date Datetime for verification

param: string $modified_user_id User modified by.


get_notification_recipients()

This function determines which users receive a notification.


return: Array( ) of User Class


send_assignment_notifications($notify_user, $admin)

This function handles sending out email notifications when items are first assigned to users.


create_notification_email($notify_user)

This function handles create the email notifications email.


save_relationship_changes($is_update)

This function is a good location to save changes that have been made to a relationship. This should be overriden in subclasses that have something to save.


param: $is_update true if this save is an update.


check_date_relationships_load()

This function retrieves a record of the appropriate type from the DB. It fills in all of the fields from the DB into the object it was called on.


param: $id - If ID is specified, it overrides the current value of $this->id. If not specified the current value of $this->id will be used.

return: this - The object that it was called apon or null if exactly 1 record was not found.


check_date_relationships_save()

This function processes the date and time fields.


Interal function, do not override.


unformat_all_fields()

This function removes formatting from values posted from the user interface. It only unformats numbers. Function relies on user/system preference for format strings.

Internal Function, do not override.

format_all_fields()

This functions adds formatting to all number fields before presenting them to user interface.

Internal function, do not override.


retrieve($id = -1, $encode=true)

Function fetches a single row of data given the primary key value.

The fetched data is then set into the bean. The function also processes the fetched data by formattig datetime and numeric values.


param: string $id Optional, default -1, is set to -1 id value from the bean is used, else, passed value is used

param: boolean $encode Optional, default true, encodes the values fetched from the database.


populateFromRow($row)

Sets value from fetched row into the bean.


param: array $row Fetched row


add_list_count_joins(&$query, $where)

Add any required joins to the list count query. The joins are required if there is a field in the $where clause that needs to be joined.


param: string $query

param: string $where


create_list_count_query($query)

Changes the select expression of the given query to be 'count(*)' so you can get the number of items the query will return. This is used to populate the upper limit on ListViews.


param: string $query Select query string

return: string count query


get_list($order_by = "", $where = "", $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)

This function returns a paged list of the current object type. It is intended to allow for hopping back and forth through pages of data. It only retrieves what is on the current page.


param: string $order_by

param: string $where Additional where clause

param: int $row_offset Optaional,default 0, starting row number

param: init $limit Optional, default -1

param: int $max Optional, default -1

param: boolean $show_deleted Optioanl, default 0, if set to 1 system will show deleted records.

return: array Fetched data.


process_order_by($order_by, $submodule)

This function prefixes column names with this bean's table name. This call can be ignored for mysql since it does a better job than Oracle in resolving ambiguity.


param: string $order_by Order by clause to be processed

param: string $submodule name of the module this order by clause is for

return: string Processed order by clause


get_detail($order_by = "", $where = "", $offset = 0, $row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)

This function returns a detail object just like retrieve of the current object type.

It is intended for use in navigation buttons on the DetailView. It will pass an offset and limit argument to the sql query.


param: string $order_by

param: string $where Additional where clause

param: int $row_offset Optaional,default 0, starting row number

param: init $limit Optional, default -1

param: int $max Optional, default -1

param: boolean $show_deleted Optioanl, default 0, if set to 1 system will show deleted records.

return: array Fetched data.


get_related_list($child_seed,$related_field_name, $order_by = "", $where = "",$row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0)

This function fetches data from all related tables.


param: object $child_seed

param: string $related_field_name relation to fetch data for. (ie accounts)

param: string $order_by Optional, default empty

param: string $where Optional, additional where clause

return: array Fetched data.

get_union_related_list($parentbean, $order_by = "", $sort_order=, $where = "",$row_offset = 0, $limit=-1, $max=-1, $show_deleted = 0, $subpanel_def)

Function constructs a query to fetch data for supanels and list views.


It constructs union queries for activities subpanel.


Internal Function, do not overide.


param: Object $parentbean constructing queries for link attributes in this bean.

param: string $order_by Optional, order by clause

param: string $sort_order Optional, sort order

param: string $where Optional, additional where clause


get_full_list($order_by = "", $where = "", $check_dates=false, $show_deleted = 0)

This function returns a full (ie non-paged) list of the current object type.


create_list_query($order_by, $where, $show_deleted = 0)

Function return the list query used by the list views and export button.


If you override this function do not forget to apply the teamsecurity filter.


param: string $order_by Optional, custom order by clause

param: string $where Optional, custom where clause

param: int $show_deleted Optional, default 0, show deleted records is set to 1.

return: string select query string


create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type=, $return_array = false,$parentbean, $singleSelect = false)

Function return the list query used by the list views and export button. Next generation of create_list_query function.


Override this function to return a custom query.


param: string $order_by custom order by clause

param: string $where custom where clause

param: array $filter Optioanal

param: array $params Optional

param: int $show_deleted Optional, default 0, show deleted records is set to 1.

param: string $join_type

param: boolean $return_array Optional, default false, response as array

param: object $parentbean creating a subquery for this bean.

param: boolean $singleSelect Optional, default false.

return: String select query string, optionally an array value will be returned if $return_array= true.


retrieve_parent_fields($type_info)

Return parent record data for objects that store relatioship information.


Interal function, do not override.


param: array $type_info

process_list_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = )

Process the list query and return fetched row.


Internal function, do not override.


param: string $query select query to be processed.

param: int $row_offset starting position

param: int $limit Optioanl, default -1

param: int $max_per_page Optional, default -1

param: string $where Optional, additional filter criteria.

return: array Fetched data


_get_num_rows_in_query($query, $is_count_query=false)

This will return the number of rows that the given SQL query should produce.


Internal function, do not override.


param: string $query valid select query

param: boolean $is_count_query Optional, Default false, set to true if passed query is a count query.

return: int count of rows found


process_union_list_query($parent_bean, $query,$row_offset, $limit= -1, $max_per_page = -1, $where = , $subpanel_def, $query_row_count=, $secondary_queries = array())

Applies pagination window to union queries used by list view and subpanels, executes the query and returns fetched data.


Internal function, do not override.


param: object $parent_bean

param: string $query query to be processed.

param: int $row_offset

param: int $limit optional, default -1

param: int $max_per_page Optional, default -1

param: string $where Custom where clause.

param: array $subpanel_def definition of sub-panel to be processed

param: string $query_row_count

param: array $seconday_queries

return: array Fetched data.


process_detail_query($query, $row_offset, $limit= -1, $max_per_page = -1, $where = , $offset = 0)

Applies pagination window to select queries used by detail view, executes the query and returns fetched data.


Internal function, do not override.

param: string $query query to be processed.

param: int $row_offset

param: int $limit optional, default -1

param: int $max_per_page Optional, default -1

param: string $where Custom where clause.

param: int $offset Optional, default 0

return: array Fetched data.


process_full_list_query($query, $check_date=false)

Processes fetched list view data.


Internal function, do not override.


param: string $query query to be processed.

param: boolean $check_date Optional, default false. if set to true date time values are processed.

return: array Fetched data.


track_view($user_id, $current_module)

Track the viewing of a detail record. This leverages get_summary_text() which is object specific


Internal function, do not override.


param: string $user_id The user that is viewing the record.

param: string $current_module module being processed.


get_summary_text()

Return the summary text that should show up in the recent history list for this object.


Internal function, do not override.


fill_in_additional_list_fields()

This is designed to be overridden and add specific fields to each record. This allows the generic query to fill in the major fields, and then targetted queries to get related fields and add them to the record. The contact's account for instance. This method is only used for populating extra fields in lists


fill_in_additional_detail_fields()

This is designed to be overridden and add specific fields to each record. This allows the generic query to fill in the major fields, and then targetted queries to get related fields and add them to the record. The contact's account for instance. This method is only used for populating extra fields in the detail form.


create_index($query)

This is a helper class that is used to quickly created indexes when creating tables.


mark_deleted($id)

This function should be overridden in each module. It marks an item as deleted.


If it is not overridden, then marking this type of item is not allowed.


mark_undeleted($id)

Restores data deleted by call to mark_deleted() function.


Internal Function, do not override.


mark_relationships_deleted($id)

This function deletes relationships to this object. It should be overridden to handle the relationships of the specific object. This function is called when the item itself is being deleted.

build_related_list($query, &$template, $row_offset = 0, $limit = -1)

This function is used to execute the query and create an array template objects from the resulting ids from the query. It is currently used for building sub-panel arrays.


param: string $query - the query that should be executed to build the list

param: object $template - The object that should be used to copy the records.

param: int $row_offset Optional, default 0

param: int $limit Optional, default -1

return: array


build_related_list_where($query, &$template, $where=, $in=, $order_by, $limit=, $row_offset = 0)

This function is used to execute the query and create an array template objects from the resulting ids from the query. It is currently used for building sub-panel arrays. It supports an additional where clause that is executed as a filter on the results


param: string $query - the query that should be executed to build the list

param: object $template - The object that should be used to copy the records.


build_related_in($query)

Constructs an comma seperated list of ids from passed query results.


param: string @query query to be executed.


build_related_list2($query, &$template, &$field_list)

Optionally copy values from fetched row into the bean.


Internal function, do not override.


param: string $query - the query that should be executed to build the list

param: object $template - The object that should be used to copy the records.

param: array $field_list List of fields.

return: array

list_view_parse_additional_sections(&$list_form)

This is to allow implemetning classes to fill in row specific columns of a list view form.


get_list_view_array()

This function assigns all of the values into the template for the list view.


get_list_view_data()

Override this function to set values in the array used to render list view data.


get_where(&$fields_array)

Construct where clause from a list of name-value pairs.


retrieve_by_string_fields($fields_array, $encode=true)

Construct a select query and fetch 1 row using this query ,and then process the row.


Internal function, do not override.


param: array @fields_array array of name value pairs used to construct query.

param: boolean $encode Optional, default true, encode fetched data.

return: object Instance of this bean with fetched data.


process_special_fields()

This method is called during an import before inserting a bean Define an associative array called $special_fields the keys are user defined, and don't directly map to the bean's fields the value is the method name within that bean that will do extra processing for that field. example: 'full_name'=>'get_names_from_full_name'


build_generic_where_clause($value)

Override this function to build a where clause based on the serach criteria set into bean .


parse_additional_headers(&$list_form, $xTemplateSection)

No description --- to do


assign_display_fields($currentModule)

No description --- to do


add_created_modified_dates()

called as a special_function from an Import when saving


set_relationship($table, $relate_values, $check_duplicates = true,$do_update=false,$data_values=null)

No description --- to do


retrieve_relationships($table, $values, $select_id)

No description --- to do


loadLayoutDefs()

No description --- to do


call_vardef_handler($meta_array_type=null)

No description --- to do


call_relationship_handler($target_base="module_dir", $return_handler=false)

No description -- todo


call_custom_logic($event, $arguments = null)

Trigger custom logic for this module that is defined for the provided hook


The custom logic file is located under custom/modules/[CURRENT_MODULE]/logic_hooks.php.


That file should define the $hook_version that should be used.


It should also define the $hook_array. The $hook_array will be a two dimensional array the first dimension is the name of the event, the second dimension is the information needed to fire the hook. Each entry in the top level array should be defined on a single line to make it easier to automatically replace this file. There should be no contents of this file that are not replaceable. $hook_array['before_save'][] = Array(1, testtype, 'custom/modules/Leads/test12.php', 'TestClass', 'lead_before_save_1'); This sample line creates a before_save hook. The hooks are procesed in the order in which they are added to the array. The second dimension is an array of:

  • processing index (for sorting before exporting the array)
  • A logic type hook
  • label/type
  • php file to include
  • php class the method is in
  • php method to call


The method signature for version 1 hooks is:

function NAME(&$bean, $event, $arguments)

  • $bean - $this bean passed in by reference.
  • $event - The string for the current event (i.e. before_save)
  • $arguments - An array of arguments that are specific to the event.


process_hooks($hook_array, $event, $arguments)

This is a helper method that actually loops through the hooks and calls each of the hooks in turn

  • $hook_array - The array of hooks to call
  • $event - The string for the current event (i.e. before_save)
  • $arguments - An array of arguments that are specific to the event.


getRealKeyFromCustomFieldAssignedKey($name)

When creating a custom field of type Dropdown, it creates an enum row in the DB. A typical get_list_view_array() result will have the *KEY* value from that drop-down. Since custom _dom objects are flat-files included in the $app_list_strings variable,

We need to generate a key-key pair to get the true value like so:

([module]_cstm->fields_meta_data->$app_list_strings->*VALUE*)


bean_implements($interface)

No description -- todo


ACLAccess($view,$is_owner='not_set')

No description -- todo


isOwner($user_id)

function isOwner($user_id)


returns true of false if the user_id passed is the owner


param: GUID $user_id

return: boolean


getOwnerWhere($user_id)

gets there where statement for checking if a user is an owner


param: GUID $user_id

return: STRING


listviewACLHelper()

This function is used in order to manage ListView links and if they should links or not based on the ACL permissions of the user


return: ARRAY of STRINGS


toArray($dbOnly = false, $stringOnly = false, $upperKeys=false)

returns this bean as an array


return: array of fields with id, name, access and category


fromArray($arr)

No description -- todo


loadFromRow($arr)

No description -- todo


create_qualified_order_by( $order_by, $qualify)

No description -- todo

Personal tools