Insert a custom block in an email for Joomla

This step by step guide shows you how to develop your own add-on, allowing you to insert a dynamic HTML block in your emails with data pulled from an other extension.

You may want to send to your users the latest products you have in store this month, the upcoming events they can book, or your latest articles built with an other extension.

To do this, you can either copy your content title, image, description, etc... or you can use one of our add-ons.

If we don't have any add-on yet for the extension you're using, you can create it using this guide, which will add a new block type in our email editor:

As an example, here is a simple Joomla article inserted in an email:

For this step by step guide, we will create an integration with Phoca download that lets you:

  • search and insert a file

  • insert files by category

Base file

Before continuing, make sure you created a custom add-on by following this guide:

Making a custom add-on

In your add-on main folder, add an image that will be shown as the icon of your new block type. We will use this image in this example:

In the file plugin.php, add the following method to your class:

public function __construct()
{
    parent::__construct();
    $this->installed = acym_isExtensionActive('com_phocadownload');

    $this->pluginDescription->name = 'Phoca Download';
    $this->pluginDescription->icon = ACYM_DYNAMICS_URL.basename(__DIR__).'/icon.png';
}
  • on line 4, we make sure the Phoca Download extension is installed. AcyMailing won't show the block type if this is not the case. If you don't need to check for an extension to be installed, remove this line

  • on line 6, the name you set will be shown on your block type

  • on line 7, the URL must point to your icon image

Define the insertion options

For your integration to be visible in the editor, you will need to add the following method to your plugin.php file:

public function getPossibleIntegrations()
{
    return $this->pluginDescription;
}

If you return null in this method, your integration won't be shown. This gives you the possibility to add conditions here.

At this point your new block type should be visible in the editor:

To define the insertion options that will be shown in the right panel of the editor, you will need to add this use statement at the top of the plugin.php file:

use AcyMailing\Helpers\TabHelper;

Then add this method:

public function insertionOptions($defaultValues = null)
{
    $this->defaultValues = $defaultValues;
    $this->categories = acym_loadObjectList('SELECT id, parent_id, title FROM `#__phocadownload_categories`');

    $tabHelper = new TabHelper();
    $identifier = $this->name;
    $tabHelper->startTab(acym_translation('ACYM_ONE_BY_ONE'), !empty($this->defaultValues->defaultPluginTab) && $identifier === $this->defaultValues->defaultPluginTab);

    $displayOptions = [
        [
            'title' => 'ACYM_DISPLAY',
            'type' => 'checkbox',
            'name' => 'display',
            'options' => [
                'title' => ['ACYM_TITLE', true],
                'description' => ['ACYM_DESCRIPTION', true],
                'readmore' => ['ACYM_READ_MORE', false],
            ],
        ],
        [
            'title' => 'ACYM_CLICKABLE_TITLE',
            'type' => 'boolean',
            'name' => 'clickable',
            'default' => true,
        ],
        [
            'title' => 'ACYM_CLICKABLE_IMAGE',
            'type' => 'boolean',
            'name' => 'clickableimg',
            'default' => false,
        ],
        [
            'title' => 'ACYM_TRUNCATE',
            'type' => 'intextfield',
            'isNumber' => 1,
            'name' => 'wrap',
            'text' => 'ACYM_TRUNCATE_AFTER',
            'default' => 0,
        ],
        [
            'title' => 'ACYM_DISPLAY_PICTURES',
            'type' => 'pictures',
            'name' => 'pictures',
        ],
    ];

    echo $this->displaySelectionZone($this->getFilteringZone().$this->prepareListing());
    echo $this->pluginHelper->displayOptions($displayOptions, $identifier, 'individual', $this->defaultValues);

    $tabHelper->endTab();
    $identifier = 'auto'.$this->name;
    $tabHelper->startTab(acym_translation('ACYM_BY_CATEGORY'), !empty($this->defaultValues->defaultPluginTab) && $identifier === $this->defaultValues->defaultPluginTab);

    $catOptions = [
        [
            'title' => 'ACYM_ORDER_BY',
            'type' => 'select',
            'name' => 'order',
            'options' => [
                'id' => 'ACYM_ID',
                'publish_up' => 'ACYM_PUBLISHING_DATE',
                'title' => 'ACYM_TITLE',
                'rand' => 'ACYM_RANDOM',
            ],
        ],
    ];

    $this->autoContentOptions($catOptions);
    $this->autoCampaignOptions($catOptions);
    $displayOptions = array_merge($displayOptions, $catOptions);

    echo $this->displaySelectionZone($this->getCategoryListing());
    echo $this->pluginHelper->displayOptions($displayOptions, $identifier, 'grouped', $this->defaultValues);

    $tabHelper->endTab();
    $tabHelper->display('plugin');
}

You will need to modify multiple parts of this method:

  • line 4, we need to get the Phoca Download categories to be able to filter files. AcyMailing always needs the id, parent_id and title columns. If these columns have a different name for your extension, you must use the SQL "AS" to rename the column in the pulled data

  • if your extension's main parent category ID is 0, you need to add $this->rootCategoryId = 0; into the add-on's construct method. This will help AcyMailing display the categories correctly on the listing

  • line 10 we define the most common options shown in the right panel, you may want to modify the lines 16 to 18 if you want to have more data to display in your email

  • lines 61 to 64, we define the possible columns used to order the files when multiple ones are inserted by category

You will also need to add this method to prepare the listing showing the content you can insert:

public function prepareListing()
{
    $this->querySelect = 'SELECT item.id, item.title, item.publish_up ';
    $this->query = 'FROM #__phocadownload AS item ';
    $this->filters = [];
    $this->filters[] = 'item.published = 1';
    $this->searchFields = ['item.id', 'item.title'];
    $this->pageInfo->order = 'item.id';
    $this->elementIdTable = 'item';
    $this->elementIdColumn = 'id';

    parent::prepareListing();

    if (!empty($this->pageInfo->filter_cat)) {
        $this->filters[] = 'item.catid = '.intval($this->pageInfo->filter_cat);
    }

    return $this->getElementsListing(
        [
            'header' => [
                'title' => [
                    'label' => 'ACYM_TITLE',
                    'size' => '7',
                ],
                'publish_up' => [
                    'label' => 'ACYM_PUBLISHING_DATE',
                    'size' => '4',
                    'type' => 'date',
                ],
                'id' => [
                    'label' => 'ACYM_ID',
                    'size' => '1',
                    'class' => 'text-center',
                ],
            ],
            'id' => 'id',
            'rows' => $this->getElements(),
        ]
    );
}

Let's break down this code:

  • line 3, we get the columns needed to show the content that can be inserted. You should always at least get the id and the title

  • line 4, we define in which table we get the content that can be inserted.

  • we can filter the content shown in the insertion options by adding conditions in the filter line 7. In this case, we chose to only show the files that are published

  • line 7, we get the columns on which we want the search field to be applied when searching for a content to insert

  • line 8, we define the column used to order the results. We chose to show the files by id (recent files first)

  • line 9, we define the table containing the information we need. We often apply the alias "item" on the main table to make the query shorter

  • lines 10 and 36, we define the column name containing the id (often "id", but some extensions can have "ID", "content_id", etc...)

  • line 15, we add a condition if a category is selected in the category filter. In this case, the category id of a file is stored in the column "catid"

  • lines 21, 25 and 30 must use the column names that are selected on line 3. These will be shown on the files listing. You can add as many columns as you want, but you should always make sure that the total size is always 12. In this example, the title has a size of 7 (line 23), the publishing date has a size of 4 (line 27) and the id has a size of 1 (line 32)

At this point you should see your insertion options on the right panel after dragging your new block type into an email:

Dynamically insert a content one by one in an email

Now that we have our insertion options, we can at the code inserting our content into the email. For this, add this method to your plugin.php file:

public function replaceContent(&$email)
{
    $this->replaceOne($email);
}

We will modify it later, for now you don't need to modify it.

Add this other method that defines how the inserted content should look like:

public function replaceIndividualContent($tag)
{
    $query = 'SELECT * FROM #__phocadownload WHERE `published` = 1 AND `id` = '.intval($tag->id);
    $element = $this->initIndividualContent($tag, $query);

    if (empty($element)) {
        return '';
    }

    $link = 'index.php?option=com_phocadownload&view=file&id='.$element->id;
    $link = $this->finalizeLink($link, $tag);

    $title = '';
    $afterArticle = '';
    $imagePath = '';
    $contentText = '';

    if (in_array('title', $tag->display)) {
        $title = $element->title;
    }

    if (!empty($tag->pict) && !empty($element->image_download)) {
        $imagePath = 'images/phocadownload/'.$element->image_download;
    }

    if (in_array('description', $tag->display)) {
        $contentText .= $element->description;
    }

    if (in_array('readmore', $tag->display)) {
        $afterArticle .= '<a class="acymailing_readmore_link" style="text-decoration:none;" target="_blank" href="'.$link.'">
            <span class="acymailing_readmore">'.acym_escape(acym_translation('ACYM_READ_MORE')).'</span>
        </a>';
    }

    $format = new stdClass();
    $format->tag = $tag;
    $format->title = $title;
    $format->afterArticle = $afterArticle;
    $format->imagePath = $imagePath;
    $format->altImage = $title;
    $format->description = $contentText;
    $format->link = empty($tag->clickable) && empty($tag->clickableimg) ? '' : $link;
    $result = '<div class="acymailing_content">'.$this->pluginHelper->getStandardDisplay($format).'</div>';

    return $this->finalizeElementFormat($result, $tag, []);
}

Here are the most important things to modify:

  • line 3, you need to make an SQL query that gets all the data you need to display in your email. The id of the selected content can be found in the variable $tag->id.

  • on line 10 you need to build the URL that shows the content on the front-end of your website. It will be added to the title and image of the inserted content

  • lines 18 to 34, we look at the options checked in $tag->display and prepare the data we want to display. All the options selected in the editor's insertion options are stored in $tag, and the data of the content to insert is is $element

  • lines 36 to 43, we create an object used by our code to automatically generate the HTML to insert in the email. Note that you could simply return the HTML you want, but using our code makes life easier to handle most of our options automatically (shorten the description, resize/remove images, add a link to the title/image, etc...)

You should now be able to insert a single element with your new block type:

Dynamically insert content by category in an email

Now that our custom add-on lets us insert file listings one by one, we can make it insert them in bulk.

Start by modifying the method replaceContent that we previously added, and call the function replaceMultiple like this, just before calling replaceOne:

public function replaceContent(&$email)
{
    $this->replaceMultiple($email);
    $this->replaceOne($email);
}

You then need to add this method:

public function generateByCategory(&$email)
{
    $tags = $this->pluginHelper->extractTags($email, 'auto'.$this->name);
    $this->tags = [];
    $time = time();

    if (empty($tags)) {
        return $this->generateCampaignResult;
    }

    foreach ($tags as $oneTag => $parameter) {
        if (isset($this->tags[$oneTag])) {
            continue;
        }

        $query = 'SELECT DISTINCT element.`id` FROM #__phocadownload AS element ';

        $where = [];

        $selectedArea = $this->getSelectedArea($parameter);
        if (!empty($selectedArea)) {
            $where[] = 'element.catid IN ('.implode(',', $selectedArea).')';
        }

        $where[] = 'element.published = 1';
        $where[] = 'element.`publish_up` < '.acym_escapeDB(date('Y-m-d H:i:s', $time - date('Z')));
        $where[] = 'element.`publish_down` > '.acym_escapeDB(date('Y-m-d H:i:s', $time - date('Z'))).' OR element.`publish_down` = 0';

        if (!empty($parameter->min_publish)) {
            $parameter->min_publish = acym_date(acym_replaceDate($parameter->min_publish), 'Y-m-d H:i:s', false);
            $where[] = 'element.`publish_up` >= '.acym_escapeDB($parameter->min_publish);
        }

        if (!empty($parameter->onlynew)) {
            $lastGenerated = $this->getLastGenerated($email->id);
            if (!empty($lastGenerated)) {
                $where[] = 'element.`publish_up` > '.acym_escapeDB(acym_date($lastGenerated, 'Y-m-d H:i:s', false));
            }
        }

        $query .= ' WHERE ('.implode(') AND (', $where).')';

        $this->tags[$oneTag] = $this->finalizeCategoryFormat($query, $parameter, 'element');
    }

    return $this->generateCampaignResult;
}

This basically builds an SQL query that gets the file listing IDs that should be inserted in the email, based on what you selected in the insertion options:

  • line 16 we select the id of the Phoca Download files

  • on line 22, we make sure only the files in the selected categories are inserted. If the category relationship is stored in an other table you may need to adapt the query and join on this other table for example

  • line 25 to 27 we make sure only published files are inserted

  • the lines 29 to 39 are only useful if you want to use your integration with automatic campaigns. This makes sure that the auto-campaign is only sent if the minimum number of files inserted is met, and that the same file isn't inserted in multiple campaigns

At this point your integration is ready and you should be able to insert the content either one by one or by category in your emails!

Here is the entire code for the plugin.php file:

<?php

use AcyMailing\Libraries\acymPlugin;
use AcyMailing\Helpers\TabHelper;

class plgAcymExampleaddon extends acymPlugin
{
    public function __construct()
    {
        parent::__construct();
        $this->installed = acym_isExtensionActive('com_phocadownload');

        $this->pluginDescription->name = 'Phoca Download';
        $this->pluginDescription->icon = ACYM_DYNAMICS_URL.basename(__DIR__).'/icon.png';

        $this->rootCategoryId = 0;
    }

    public function getPossibleIntegrations()
    {
        return $this->pluginDescription;
    }

    public function insertionOptions($defaultValues = null)
    {
        $this->defaultValues = $defaultValues;
        $this->categories = acym_loadObjectList('SELECT id, parent_id, title FROM `#__phocadownload_categories`');

        $tabHelper = new TabHelper();
        $identifier = $this->name;
        $tabHelper->startTab(acym_translation('ACYM_ONE_BY_ONE'), !empty($this->defaultValues->defaultPluginTab) && $identifier === $this->defaultValues->defaultPluginTab);

        $displayOptions = [
            [
                'title' => 'ACYM_DISPLAY',
                'type' => 'checkbox',
                'name' => 'display',
                'options' => [
                    'title' => ['ACYM_TITLE', true],
                    'description' => ['ACYM_DESCRIPTION', true],
                    'readmore' => ['ACYM_READ_MORE', false],
                ],
            ],
            [
                'title' => 'ACYM_CLICKABLE_TITLE',
                'type' => 'boolean',
                'name' => 'clickable',
                'default' => true,
            ],
            [
                'title' => 'ACYM_CLICKABLE_IMAGE',
                'type' => 'boolean',
                'name' => 'clickableimg',
                'default' => false,
            ],
            [
                'title' => 'ACYM_TRUNCATE',
                'type' => 'intextfield',
                'isNumber' => 1,
                'name' => 'wrap',
                'text' => 'ACYM_TRUNCATE_AFTER',
                'default' => 0,
            ],
            [
                'title' => 'ACYM_DISPLAY_PICTURES',
                'type' => 'pictures',
                'name' => 'pictures',
            ],
        ];

        echo $this->displaySelectionZone($this->getFilteringZone().$this->prepareListing());
        echo $this->pluginHelper->displayOptions($displayOptions, $identifier, 'individual', $this->defaultValues);

        $tabHelper->endTab();
        $identifier = 'auto'.$this->name;
        $tabHelper->startTab(acym_translation('ACYM_BY_CATEGORY'), !empty($this->defaultValues->defaultPluginTab) && $identifier === $this->defaultValues->defaultPluginTab);

        $catOptions = [
            [
                'title' => 'ACYM_ORDER_BY',
                'type' => 'select',
                'name' => 'order',
                'options' => [
                    'id' => 'ACYM_ID',
                    'publish_up' => 'ACYM_PUBLISHING_DATE',
                    'title' => 'ACYM_TITLE',
                    'rand' => 'ACYM_RANDOM',
                ],
            ],
        ];

        $this->autoContentOptions($catOptions);
        $this->autoCampaignOptions($catOptions);
        $displayOptions = array_merge($displayOptions, $catOptions);

        echo $this->displaySelectionZone($this->getCategoryListing());
        echo $this->pluginHelper->displayOptions($displayOptions, $identifier, 'grouped', $this->defaultValues);

        $tabHelper->endTab();
        $tabHelper->display('plugin');
    }

    public function prepareListing()
    {
        $this->querySelect = 'SELECT item.id, item.title, item.publish_up ';
        $this->query = 'FROM #__phocadownload AS item ';
        $this->filters = [];
        $this->filters[] = 'item.published = 1';
        $this->searchFields = ['item.id', 'item.title'];
        $this->pageInfo->order = 'item.id';
        $this->elementIdTable = 'item';
        $this->elementIdColumn = 'id';

        parent::prepareListing();

        if (!empty($this->pageInfo->filter_cat)) {
            $this->filters[] = 'item.catid = '.intval($this->pageInfo->filter_cat);
        }

        return $this->getElementsListing(
            [
                'header' => [
                    'title' => [
                        'label' => 'ACYM_TITLE',
                        'size' => '7',
                    ],
                    'publish_up' => [
                        'label' => 'ACYM_PUBLISHING_DATE',
                        'size' => '4',
                        'type' => 'date',
                    ],
                    'id' => [
                        'label' => 'ACYM_ID',
                        'size' => '1',
                        'class' => 'text-center',
                    ],
                ],
                'id' => 'id',
                'rows' => $this->getElements(),
            ]
        );
    }

    public function replaceContent(&$email)
    {
        $this->replaceMultiple($email);
        $this->replaceOne($email);
    }

    public function replaceIndividualContent($tag)
    {
        $query = 'SELECT * FROM #__phocadownload WHERE `published` = 1 AND `id` = '.intval($tag->id);
        $element = $this->initIndividualContent($tag, $query);

        if (empty($element)) {
            return '';
        }

        $link = 'index.php?option=com_phocadownload&view=file&Itemid=1140&id='.$element->id;
        $link = $this->finalizeLink($link, $tag);

        $title = '';
        $afterArticle = '';
        $imagePath = '';
        $contentText = '';

        if (in_array('title', $tag->display)) {
            $title = $element->title;
        }

        if (!empty($tag->pict) && !empty($element->image_download)) {
            $imagePath = 'images/phocadownload/'.$element->image_download;
        }

        if (in_array('description', $tag->display)) {
            $contentText .= $element->description;
        }

        if (in_array('readmore', $tag->display)) {
            $afterArticle .= '<a class="acymailing_readmore_link" style="text-decoration:none;" target="_blank" href="'.$link.'">
                <span class="acymailing_readmore">'.acym_escape(acym_translation('ACYM_READ_MORE')).'</span>
            </a>';
        }

        $format = new stdClass();
        $format->tag = $tag;
        $format->title = $title;
        $format->afterArticle = $afterArticle;
        $format->imagePath = $imagePath;
        $format->altImage = $title;
        $format->description = $contentText;
        $format->link = empty($tag->clickable) && empty($tag->clickableimg) ? '' : $link;
        $result = '<div class="acymailing_content">'.$this->pluginHelper->getStandardDisplay($format).'</div>';

        return $this->finalizeElementFormat($result, $tag, []);
    }

    public function generateByCategory(&$email)
    {
        $tags = $this->pluginHelper->extractTags($email, 'auto'.$this->name);
        $this->tags = [];
        $time = time();

        if (empty($tags)) {
            return $this->generateCampaignResult;
        }

        foreach ($tags as $oneTag => $parameter) {
            if (isset($this->tags[$oneTag])) {
                continue;
            }

            $query = 'SELECT DISTINCT element.`id` FROM #__phocadownload AS element ';

            $where = [];

            $selectedArea = $this->getSelectedArea($parameter);
            if (!empty($selectedArea)) {
                $where[] = 'element.catid IN ('.implode(',', $selectedArea).')';
            }

            $where[] = 'element.published = 1';
            $where[] = 'element.`publish_up` < '.acym_escapeDB(date('Y-m-d H:i:s', $time - date('Z')));
            $where[] = 'element.`publish_down` > '.acym_escapeDB(date('Y-m-d H:i:s', $time - date('Z'))).' OR element.`publish_down` = 0';

            if (!empty($parameter->min_publish)) {
                $parameter->min_publish = acym_date(acym_replaceDate($parameter->min_publish), 'Y-m-d H:i:s', false);
                $where[] = 'element.`publish_up` >= '.acym_escapeDB($parameter->min_publish);
            }

            if (!empty($parameter->onlynew)) {
                $lastGenerated = $this->getLastGenerated($email->id);
                if (!empty($lastGenerated)) {
                    $where[] = 'element.`publish_up` > '.acym_escapeDB(acym_date($lastGenerated, 'Y-m-d H:i:s', false));
                }
            }

            $query .= ' WHERE ('.implode(') AND (', $where).')';

            $this->tags[$oneTag] = $this->finalizeCategoryFormat($query, $parameter, 'element');
        }

        return $this->generateCampaignResult;
    }
}

Last updated