Leveraging Smarty Templates for Advanced Customization in SuiteCRM

Home » Mississauga Digital Agency Blog » Leveraging Smarty Templates for Advanced Customization in SuiteCRM
Using Smarty templates in SuiteCRM

SuiteCRM offers a robust platform for managing customer relationships, but its true power lies in its customization capabilities. One of the most versatile tools for customizing SuiteCRM is the Smarty templating engine. With Smarty, you can manipulate and format data in various ways to tailor your CRM to your specific needs.

I’ve collected a bunch of examples over the years of how to use Smarty Templates and the CustomCode feature in the editview and detailveiw to solve business logic problems in SuiteCRM. The documentation for this particular feature is kind of sparse and there are bits and pieces of information I’ve collected from the SuiteCRM forum over the years, plus examples I’ve developed on my own. In this article, we’ll explore a compendium of examples showcasing how Smarty templates can be used to enhance and fine-tune your SuiteCRM experience.

Applying Customization in SuiteCRM

Before diving into specific examples, let’s first understand how to apply customizations within SuiteCRM. Customizations are typically applied through the Vardefs files, which define the structure and behavior of fields within modules.

Example: Adding Custom Code to Vardefs

To add custom code to a field in SuiteCRM, you’ll want to locate the editviewdefs.php or detailviewdefs.php file corresponding to the module where the field resides. These files define the layout and structure of the Edit View and Detail View respectively. They are typically found in the following directory:

custom/modules/<module_name>/metadata

Once you’ve located the appropriate editviewdefs.php or detailviewdefs.php file, find the definition of the field you want to customize. Within the field definition array, you can include the ‘customCode’ attribute to specify the custom Smarty code you wish to apply.

Here’s an example of how to add custom code to in SuiteCRM:

'<field_name>' => array(
    'name' => '<field_name>',
    'type' => '<field_type>',
    'label' => '<field_label>',
    'customCode' => '<custom_Smarty_code>',
),

Replace <field_name>, <field_type>, <field_label>, and <custom_Smarty_code> with the appropriate values for your field.

Now that we understand how to apply customizations in SuiteCRM, let’s explore some practical examples of using Smarty templates for advanced customization.


Customizing Field Output

Customizing the display of fields is a common requirement in SuiteCRM, and Smarty templates offer an elegant solution. By editing the viedefs.php file in the module’s metadata, you can apply custom Smarty code to modify field output.

Example: Formatting Phone Number

To format a phone number field (phone_work) and make it clickable, add the following code snippet to the appropriate viedefs.php file:

'customCode' => '<a href="tel:{$fields.phone_work.value}">{$fields.phone_work.value}</a>',

This code converts the phone number field into a clickable link, allowing users to initiate a call directly from SuiteCRM.

Visual Enhancements

Smarty templates not only allow for data manipulation but also enable visual enhancements to improve user experience.

Example: Changing Text Color

'customCode' => '<span style="color:red;">{$fields.custom_message_c.value}</span>',

By applying inline styles, you can dynamically change the text color based on field values.

Example: Conditional Text Color

'customCode' => '{if $fields.sales_stage.value == "Closed Won"}<span style="color: gray;">{$fields.custom_message_c.value}</span>{else}{$fields.custom_message_c.value}{/if}',

This example demonstrates conditional formatting based on the value of another field, or you could change the color of the current field, whatever your needs are.

Another use case might be if close won change color to green, if closed lost, change color to red.

Example: Formatting Output

in custom/modules/<the module>/metadata/viedefs.php

You can add custom code to the array to modify the output using smarty templates like this:

In the above example, it limits the field to 2 decimals.

Below, we’ll remove the comma:

'customCode'=> <span>{$fields.stock_code_c.value|replace:",":""}</span>

In Smarty templating, the replace modifier is used to replace occurrences of one string with another string within a given variable. The general syntax for using the replace modifier is:

{$variable|replace:"search_string":"replace_with"}

In this case, we want to remove commas from the value of the stock_code_c field. Here’s how the code works step by step:

  1. {$fields.stock_code_c.value}: This part retrieves the value of the stock_code_c field.
  2. |replace:“,”:“”: This uses the replace modifier to replace all occurrences of the comma , in the retrieved value with an empty string “”.

For example, if the original value of stock_code_c is 1,000,000, applying the replace modifier will result in 1000000, effectively removing all the commas.

So, the complete code:

<span>{$fields.stock_code_c.value|replace:",":""}</span>

Example: Add $ in Front of Currency

'customCode' => '<span>{$fields.amount.value|replace:",":""|number_format:2:".":","|regex_replace:"/^/":"$ "}</span>',

Replace ‘your_currency_field_name’ with the actual name of the currency field you want to modify. The prepend modifier will add the $ symbol in front of the currency field’s value.

Note: this also removes the commas, not sure how to add them back.

Conditional Field Behavior

Smarty templates can also be used to control field behavior based on certain conditions, providing a more dynamic user experience.

Example: Conditional Read-Only Fields

Often clients want the value of an Opportunity not to be editable after it is changed to closed won. This keeps historical reporting accurate.

'customCode' => '{if $fields.sales_stage.value eq "Closed Won"}<span>{$fields.amount.value|number_format:2:".":","|regex_replace:"/^/":"$ "}</span>{else}<input type="text" name="amount" value="{$fields.amount.value}" id="amount" name="amount"  />{/if}',

Here, the amount field becomes read-only when the sales stage is “Closed Won,” simplifying data entry workflows.

In this code:

  • name="amount" assigns the field name, ensuring that the data entered into this field is submitted with the appropriate key when the record is saved.
  • id="amount" provides a unique identifier for the input field, which is useful for targeting the field with JavaScript or CSS, but it’s not required for data submission.

By including both name and id attributes, you’re ensuring that the value entered into the amount field is properly submitted and saved to the database when the record is saved in SuiteCRM.

Note: If you put this in editview and/or quickcreate view, you’ll need to turn off inline editing to prevent users from using inline edit to change the values.

Role-Based Customization

Smarty templates allow for role-based customization, ensuring that users see only what they’re allowed to see and interact with.

Example: Role-Based Field Permissions

To set field permissions based on user roles, extend the ViewEdit class and override its display method.

In the example below we want to both make amount uneditable by making a ‘<span>’ and only allowing ‘<input>’ if it is not in status closed won. The Admins will always be able to edit.

'customCode' => '{if $is_admin}<input type="text" name="custom_message_c" value="{$fields.amount.value}" />{elseif $fields.sales_stage.value eq "Closed Won"}<span>{$fields.amount.value|format_currency:"$ ":true}</span>{else}<input type="text" name="custom_message_c" value="{$fields.amount.value}" id="amount" name="amount" />{/if}',

In order to get $is_admin, you’re going to need to pass two variables to the Smart Template:

copy modules/Contacts/views/view.edit.php to custom/modules/Contacts/views/view.edit.php

1) isAdministrator

2) readOnly

Add the following code to extend ViewEdit

class AccountsViewEdit extends ViewEdit
{
    public function __construct()
    {
        parent::__construct();
        $this->useForSubpanel = true;
        $this->useModuleQuickCreateTemplate = true;
    }
    
    public function display()
    {
        global $current_user;

        // Check if the user is an administrator
        $isAdministrator = $current_user->is_admin;

        // Set the $readOnly variable based on the user's administrator status
        $readOnly = $isAdministrator ? '' : 'readonly = "readonly"';

        // Assign $readOnly to Smarty template
        $this->ev->ss->assign('readOnly', $readOnly);
        
        //Assign $isAdministrator to Smarty template
        $this->ev->ss->assign('isAdministrator', $isAdministrator);

        parent::display(); // Call the parent display function to render the view
    }
}

By extending the ViewEdit class and overriding its display method, we can pass variables such as $readOnly and $isAdministrator to the Smarty template. This allows for dynamic control over field behavior based on user roles, enhancing security and usability within SuiteCRM.

Note: If you put this in editview and/or quickcreate view, you’ll need to turn off inline editing to prevent users from using inline edit to change the values.

Other Use Cases

Example 1: Dynamic Field Labels

You can use Smarty templates to dynamically change field labels based on certain conditions. For instance, you might want to display different labels for a field depending on the user’s role or the value of another field.

'customCode' => '{if $fields.user_type.value == "Admin"}Administrative Contact{else}Regular Contact{/if}',

Example 2: Calculated Fields

Smarty templates can perform calculations and display the result in a field. This is useful for fields that need to show derived data based on other fields’ values.

The code below makes an uneditable field:

'customCode' => '{$fields.quantity.value * $fields.unit_price.value}',

Note: this does not change the value live on screen, but populates the value after save. You need to add it to both the edit view and the detail view. Here’s an example of how you could keep the input field:

'customCode' => '<input type="currency" value="{$fields.amount.value * $fields.probability.value/100}" id="weighted_opp_amount_c" name="weighted_opp_amount_c"/>',

Note: if you want the value to save in the DB afterwards, you need to include the id and name of the field to save the value to as in the above example.

This is better used to display non-db values on the detailview. It doesn’t work very well in editview. For example if the value of the variable is changed, it doesn’t update the value correctly until the NEXT re-saving of the record. If you need to calculate a field in editview, before_save hooks are better for this application.

Example 3: Conditional Field Visibility

You can control the visibility of fields based on certain conditions using Smarty templates. For example, you might want to show additional fields only when a certain checkbox is checked.

'customCode' => '{if $fields.show_additional_info.value == "1"}<input type="text" name="additional_info" />{/if}',

Example 4: Custom Validation Rules

Smarty templates can enforce custom validation rules on field inputs. This ensures that data entered by users meets specific criteria before being accepted.

'customCode' => '{if strlen($fields.email.value) > 0 && !filter_var($fields.email.value, FILTER_VALIDATE_EMAIL)}Invalid email address{/if}',

This specific example utilizes Smarty templates to enforce a custom validation rule for an email field. Let’s break down what each part of the Smarty code does:

  • {if strlen($fields.email.value) > 0 && !filter_var($fields.email.value, FILTER_VALIDATE_EMAIL)}: This part checks if the length of the email field value is greater than 0 (meaning there is some input) and if the input fails to pass the PHP FILTER_VALIDATE_EMAIL filter, indicating that it is not a valid email address.
  • Invalid email address: If the condition above evaluates to true (meaning the email is either empty or not valid), this message “Invalid email address” will be displayed to the user, indicating that the input provided is not a valid email address.

Example 5: Embedding External Content

You can embed external content, such as images or videos, within fields using Smarty templates. This allows for richer data representation within SuiteCRM.

First, you’ll want to create a non-db field in edviewdefs.php like this:

0 => 
    array(
  'name' => 'non_db_field_c', // Name of the non-db field
  'label' => 'LBL_NON_DB_FIELD_LABEL', // Label for the field
  ' displayParams' => array(
  'readonly' => true,
	), // Set the field as non-editable
    ),

You could create a non-db field and then insert a custom image/video like below.

'customCode' => '<img src="https://example.com/image.jpg" alt="Custom Image" />',

You could also make the image source another field in the module and get the URL image link or video iframe from there.

These additional examples demonstrate the versatility of Smarty templates in SuiteCRM customization, allowing for a wide range of advanced functionality beyond the basic examples covered in the article.

If you have any other ideas of how these can be used in SuiteCRM, please send me some examples!

If you’re looking for a SuiteCRM Developer or SuiteCRM Consultant, I do this for a living! Please reach out to me.

About the Author