Let the platform do the work

SugarBean

  //Retrieve bean
$bean = BeanFactory::retrieveBean($module, $id);

//Set deleted to true
$bean->mark_deleted($bean->id);

//Save
$bean->save();

Overview

The SugarBean class supports all the model operations to and from the database. Any module that interacts with the database utilizes the SugarBean class, which contains methods to create, read/retrieve, update, and delete records in the database (CRUD), as well as fetch related records.

CRUD Handling

The SugarBean handles the most basic functions of the Sugar database, allowing you to create, retrieve, update, and delete data. 

Creating and Retrieving Records

The BeanFactory class is used for bean loading. The class should be used whenever you are creating or retrieving bean objects. It will automatically handle any classes required for the bean. More information on this can be found in the BeanFactory section.

Obtaining the Id of a Recently Saved Bean

For new records, a GUID is generated and assigned to the record id field. Saving new or existing records returns a single value to the calling routine, which is the id attribute of the saved record. The id has the following format:

aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee

You can retrieve a newly created record's id with the following:

  //Create bean
$bean = BeanFactory::newBean($module);

//Populate bean fields
$bean->name = 'Example Record';

//Save
$bean->save();

//Retrieve the bean id
$record_id = $bean->id;

Saving a Bean with a Specific ID

Saving a record with a specific id requires the id and new_with_id attribute of the bean to be set. When doing so, it is important that you use a globally unique identifier. Failing to do so may result in unexpected behavior in the system. An example setting an id is shown below:

  //Create bean
$bean = BeanFactory::newBean($module);

//set the new flag
$bean->new_with_id = true;

//Set the record id with a static id
$id = '38c90c70-7788-13a2-668d-513e2b8df5e1';
$bean->id = $id;

//or have the system generate an id for you
//$id = Sugarcrm\Sugarcrm\Util\Uuid::uuid1()
//$bean->id = $id;

//Populate bean fields
$bean->name = 'Example Record';

//Save
$bean->save();

Setting new_with_id to true prevents the save method from creating a new id value and uses the assigned id attribute. If the id attribute is empty and the new_with_id attribute is set to true, the save will fail. If you would like for the system to generate an id for you, you can use Sugarcrm\Sugarcrm\Util\Uuid::uuid1().

Distinguishing New from Existing Records

To identify whether or not a record is new or existing, you can check the fetched_rows property. If the $bean has a fetched_row, it was loaded from the database. An example is shown below:

  if (!isset($bean->fetched_row['id'])) {
    //new record
} else {
    //existing record
}

If you are working with a logic hook such as before_save or after_save, you should check the arguments.isUpdate property to determine this as shown below:

  <?php

if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

class logic_hooks_class
{
    function hook_method($bean, $event, $arguments)
    {
        if (isset($arguments['isUpdate']) && $arguments['isUpdate'] == false) {
            //new record
        } else {
            //existing record
        }
    }
}

?>

Retrieving a Bean by Unique Field

Sometimes developers have a need to fetch a record based on a unique field other than the id. In previous versions you were able to use the retrieve_by_string_fields() method to accomplish this, however, that has now been deprecated. To search and fetch records, you should use the SugarQuery builder. An example of this is shown below:

  require_once('include/SugarQuery/SugarQuery.php');
$sugarQuery = new SugarQuery();

//fetch the bean of the module to query
$bean = BeanFactory::newBean('<modules>');

//create first query
$sql = new SugarQuery();
$sql->select('id');
$sql->from($bean);
$sql->Where()->equals('<field>', '<unique value>');

$result = $sql->execute();

$count = count($result);

if ($count == 0) {
    //no results were found
} elseif ($count == 1) {
    //one result was found
    $bean = BeanFactory::getBean('<module>', $result[0]['id']);
} else {
    //multiple results were found
}

Updating a Bean

You can update a bean by fetching a record and then updating the property:

  //Retrieve bean
$bean = BeanFactory::retrieveBean($module, $id);

//Fields to update
$bean->name = 'Updated Name';

//Save
$bean->save();

Note: Disabling row-level security when accessing a bean should be set to true only when it is absolutely necessary to bypass security, for example, when updating a Lead record from a custom Entry Point. An example of accessing the bean while bypassing row security is:

  $bean = BeanFactory::retrieveBean($module, $record_id, array('disable_row_level_security' => true));

Updating a Bean Without Changing the Date Modified

The SugarBean class contains an attribute called update_date_modified, which is set to true when the class is instantiated and means that the date_modified attribute is updated to the current database date timestamp. Setting update_date_modified to false would result in the date_modified attribute not being set with the current database date timestamp.

  //Retrieve bean
$bean = BeanFactory::retrieveBean($module, $id);

//Set modified flag
$bean->update_date_modified = false;

//Fields to update
$bean->name = 'Updated Name';

//Save
$bean->save();

Note: Disabling row-level security when accessing a bean should be set to true only when it is absolutely necessary to bypass security, for example, when updating a Lead record from a custom Entry Point. An example of accessing the bean while bypassing row security is:

  $bean = BeanFactory::retrieveBean($module, $record_id, array('disable_row_level_security' => true));

Deleting a Bean

Deleting a bean can be done by fetching it then calling the mark_deleted() method which makes sure any relationships with related records are removed as well:

  //Retrieve bean
$bean = BeanFactory::retrieveBean($module, $id);

//Set deleted to true
$bean->mark_deleted($id);

//Save
$bean->save();

Note: Disabling row-level security when accessing a bean should be set to true only when it is absolutely necessary to bypass security, for example, when updating a Lead record from a custom Entry Point. An example of accessing the bean while bypassing row security is:

  $bean = BeanFactory::retrieveBean($module, $record_id, array('disable_row_level_security' => true));

Fetching Relationships

This section explains how the SugarBean class can be used to fetch related information from the database.

To fetch related records, load the relationship using the link:

  //If relationship is loaded
if ($bean->load_relationship($link)) {
    //Fetch related beans
    $relatedBeans = $bean->$link->getBeans();
}

An example of this is to load the contacts related to an account:

  //Load Account
$bean = BeanFactory::getBean('Accounts', $id);

//If relationship is loaded
if ($bean->load_relationship('contacts')) {
    //Fetch related beans
    $relatedBeans = $bean->contacts->getBeans();
}

To fetch only related record IDs, load the relationship using the link:

  //If relationship is loaded
if ($bean->load_relationship($link)) {
    //Fetch related record IDs
    $relatedBeans = $bean->$link->get();
}

An example of this is to load the record IDs of contacts related to an account:

  //Load Account
$bean = BeanFactory::getBean('Accounts', $id);

//If relationship is loaded
if ($bean->load_relationship('contacts')) {
    //Fetch related beans
    $relatedBeans = $bean->contacts->get();
}

Fetching a Parent Record

Fetching a parent record is similar to fetching child records in that you will still need to load the relationship using the link:

  //If relationship is loaded
if ($bean->load_relationship($link)) {
    //Fetch related beans
    $relatedBeans = $bean->$link->getBeans();

    $parentBean = false;
    if (!empty($relatedBeans)) {
        //order the results
        reset($relatedBeans);

        //first record in the list is the parent
        $parentBean = current($relatedBeans);
    }
}

An example of this is to load a contact and fetch its parent account:

  //Load Contact
$bean = BeanFactory::getBean('Contacts', $id);

//If relationship is loaded
if ($bean->load_relationship('accounts')) {
    //Fetch related beans
    $relatedBeans = $bean->accounts->getBeans();

    $parentBean = false;
    if (!empty($relatedBeans)) {
        //order the results
        reset($relatedBeans);

        //first record in the list is the parent
        $parentBean = current($relatedBeans);
    }
}