Table of contents

How to write twig code in script field

On most fields of type script, config variable is available

{{ config.siteUrl }} {# config is system configuration object #}

Custom Twig Functions Reference

Entity Manipulation Functions

isNew(Entity entity)

  • Description: Checks if an entity is newly created and not yet persisted
  • Returns: boolean
  • Example:
{% if isNew(product) %}
    <span class="badge">New Item</span>
{% endif %}

createEntity(string entityType, array data)

  • Description: Create a new entity of the specified type with specified data
  • Returns: New entity object
  • Example:
{% set newProduct = createEntity('Product', {name: 'Test'}) %}

findEntity(string entityType, array where)

  • Description: Retrieves a single entity by filter
  • Returns: Entity object or null
  • Example:
{% set user = findEntity('User', {name: 'john doe'}) %}

findEntities(string entityType, array where, string orderField = 'id', string orderDirection = 'ASC', int offset = 0, int limit = \PHP_INT_MAX, bool withDeleted = false)

  • Description: Finds multiple entities matching specified conditions
  • Returns: Array of entities
  • Example:
{% set activeUsers = findEntities('User', {isActive: true}) %}

String and Cryptography Functions

md5(string value)

  • Description: Generates MD5 hash of the input string
  • Returns: string (32-character hexadecimal hash)
  • Example:
{% set hashedPassword = md5('mySecretPassword') %}

parseMarkdown(string markdownText)

  • Description: Converts Markdown text to HTML
  • Returns: string (HTML-rendered text)
  • Example:
{% set htmlContent = parseMarkdown('# Title\nMarkdown content') %}

Data Conversion Functions

convertFileToBase64FromUrl(string url, ?string type = null)

  • Description: Converts a file from a URL to Base64 encoded string
  • Returns: string (Base64 representation)
  • Example:
{% set base64File = convertFileToBase64FromUrl('https://example.com/document.pdf') %}

convertFileToBase64(Entity file)

  • Description: Converts a file object to Base64 encoded string
  • Returns: string (Base64 representation)
  • Example:
{% set base64File = convertFileToBase64(file) %}

getConvertedImageUrl(Entity image, array options = {quality: 100, format: 'jpg'})

  • Description: Generates a converted image URL with specified transformations
  • Returns: string (Transformed image URL)
  • Example:
{% set thumbnailUrl = getConvertedImageUrl(product.files[0]) %}

Internationalization Functions

translate(string key, string languageCode = 'en_US', string category = 'labels', string scope = 'Global')

  • Description: Get Tranlation with specified parameters
  • Returns: string (Translated text)
  • Example:
{% set nameLabel = translate('name','en_US','fields','Product') %}

translateOption(string key, string languageCode, string field, string scope = 'Global')

  • Description: Translates a specific option's label
  • Returns: string (Translated option label)
  • Example:
{% set statusLabel = translateOption('draft', 'en_US', 'status', 'Product') %}

getAllLanguageFields(entityType, string|array fields)

  • Description: Retrieves all language-specific in the specified fields
  • Returns: array of language fields
  • Example:
{% set languageFields = getAllLanguageFields('Product', fields) %}

Product and Attribute Functions

getProductAttributeValue(string attributeId, string channelId = '', string language = 'main')

  • Aliases: pav()
  • Description: Retrieves a specific product attribute value, This works only entity in the context is another ProductAttributeValue
  • Returns: Entity
  • Example:
{% set color = getProductAttributeValue(product, 'color') %}

formatProductAttributeValue(Entity pav)

  • Aliases: formatPAV()
  • Description: Formats a product attribute value based on its type
  • Returns: Formatted string value
  • Example:
{% set formattedPrice = formatProductAttributeValue(product.price) %}

Miscellaneous Functions

isAttributeChanged(Entity entity, string attributeName)

  • Description: Checks if a specific attribute has been modified
  • Returns: boolean
  • Example:
{% if isAttributeChanged(user, 'email') %}
    {# Attribute was modified #}
{% endif %}

getFetched(Entity entity, string attributeName)

  • Description: Retrieves the original (fetched) value of an attribute
  • Returns: Original attribute value
  • Example:
{% set originalEmail = getFetched(user, 'email') %}

formatField(Entity entity, string field)

  • Description: Formats a field value according to specified format
  • Returns: Formatted value
  • Example:
{% set formattedDate = formatField(user, 'createdAt') %}

ai(string engine, string prompt)

  • Description: Generates AI-powered content from prompt using the specified ai engine
  • Returns: AI-generated content
  • Example:
{% set productDescription = ai('chatgpt','Generate a description for a luxury watch') %}

Export Feed Functions

getPreviousCategoryId(Entity category)

  • Description: Retrieves the ID of the previous category in a hierarchical category structure
  • Returns: previous category id
  • Example:

Custom Twig Filters

Entity Preparation

prepareEntity

{% set processedEntity = product|prepareEntity %}
{{ processedEntity.name }}

prepareHtmlField

{% set safeContent = article.description|prepareHtmlField %}
{{ safeContent|raw }}

Content Validation

isImage

{% set validImage = uploadedFile|isImage ? uploadedFile : defaultImage %}
<img src="{{ validImage }}" alt="Product Image">

String Manipulation

escapeDoubleQuote

{% set safeName = product.name|escapeDoubleQuote %}
<div title="{{ safeName }}">{{ product.name }}</div>

escapeStr

{% set sanitizedComment = user.comment|escapeStr %}
{{ sanitizedComment }}

backslashNToBr

{% set formattedDescription = user.description|backslashNToBr %}
<p>{{ formattedDescription|raw }}</p>

Color Generation

generateBorderColor

{% set borderStyle = product.category|generateBorderColor %}
<div style="border: 2px solid {{ borderStyle }}">{{ product.name }}</div>

generateFontColor

{% set textColor = status|generateFontColor %}
<span style="color: {{ textColor }}">{{ status }}</span>

Special Variables in System Script Fields

UiHandler Context

You cannot use php syntax there, because it is rendered in javascript context.

Prompt Field

  • entity: Entity being modified
  • entityFrom: Entity from which new entity is being created (in modal view)

Example:

Give me a description for a product with the name {{ entity.name }}

UpdateScript Field

  • entity: Entity being modified
  • entityFrom: Entity from which new entity is being created

Example:

{"description": "{{ 'Description of ' ~ entity.name }}"}

Action Context

Payload Field

  • entity: First Entity of the collection to export
  • sourceEntities: Collection of entities to export
  • sourceEntitiesIds: Array of entity IDs to export

Example:

{# Export payload processing #}
{"where":[{"type":"in","attribute":"id","value":{{ sourceEntitiesIds|json_encode|raw}}}]}

UpdateScript Field

  • entity: Entity to be updated
  • triggeredEntityType: Entity Type of the entity that triggered the update
  • triggeredEntityId: ID of the entity that triggered the update
  • triggeredEntity: Entity that triggered the update

Example:

{
  "description": "{{ entity.name }} - {{ entity.brand.name }}",
}

UpsertScript Field

  • entity: Source Entity
  • triggeredEntityType: Entity Type of the entity that triggered the update
  • triggeredEntityId: ID of the entity that triggered the update

Example:

[
    {
        "entity": "Product",
        "payload": {
            "name": "{{ entity.name }}-Duplicated"
        }
    }
]

ErrorMessage Field

  • entity: Source Entity

Example:

Action cannot be performed on product {{ entity.name }}

ExportFeed Context

Template Field

  • entities: Collection of entities to export

Example:

[
  {% for entity in entities %}
    {"name": "{{ entity.name }}"}{% if not loop.last %},{% endif %}
  {% endfor %}
]

FileNameMask Field

  • feed: Feed Data
  • filename: Default filename generated by the system
  • interation: Job iteration number

Example:

{# Custom filename generation #}
{{ feed.name }}_{{ filename }}_{{ interation }}

Workflow Context

Conditions Field

  • entity: Entity that triggers the workflow
  • user: User that triggered the workflow
  • importJobId: ID of import job if workflow is triggered during an import

Example:

{{ entity.isActive and user.id != 'system' and importJobId is empty }}

Code Suggestions and Autocomplete

The Monaco field provides intelligent suggestions:

  • Automatic variable completion
  • Filter suggestions
  • Syntax error highlighting
  • Real-time validation

Resources