Some campaign rules need two fields at once. “Stop the emails after the second purchase” is a typical one. Mautic cannot do it out of the box, so we wrote a custom Mautic campaign condition in a small plugin. Below is the rule, why the native conditions fall short, how the plugin works, what the alternatives cost you, and how to test and place such a gate in a campaign.
What was the second purchase exit rule?
The rule came from a Marketo to Mautic migration for a German B2B distributor. The client runs an online shop for trade customers. New shop accounts go through an onboarding flow: first an activation track that nudges people toward the first order, then a first purchase track that nudges them toward the second one.
In Mautic we rebuilt that flow as four campaigns: two gate campaigns that decide where a contact belongs, and two drip campaigns. The first purchase drip holds 10 emails, sent on days 3, 7 and 14, then in weeks 16 and 20, then in months 6 and 9.
The exit rule for that drip was short. A customer who places a second order leaves the flow. They are a repeat customer now, and onboarding emails would only get in the way.
The data had no “number of orders” field. It had two dates that the client’s ERP sends for every customer account:
- first order date
- last order date
If the two dates differ, the customer has ordered at least twice. Simple for a human. Not simple for Mautic.
Why can’t native Mautic compare two fields?
Mautic campaigns have a “Contact field value” condition. It takes one field, an operator and a value you type in. “Country equals Germany.” “Points greater than 50.” “Last order date before a fixed date.” Every variant compares one field with a fixed value.
Date fields also offer a relative mode, such as “today” or “yesterday”. That helps for anniversary style rules. It does not help here: in relative mode the condition only checks for equality, and the other side is still not a second field.
There is no operator for “field A is different from field B”. Segment filters work the same way, one field against a value. So the native campaign builder cannot express “first order date is not equal to last order date”, no matter how you combine the blocks.
You will meet limits like this in most migrations from Marketo. Our audit lists every exit rule and every condition during discovery, so rules like this one get a decision before the build starts. For the wider list of what transfers and what you rebuild, see Marketo to Mautic migration: what transfers and what you have to rebuild.
What did we build?
We built a small Mautic plugin with one custom campaign condition. In the campaign builder it shows up next to the native conditions, under a clear label (“Second purchase”). Marketers drag it into a campaign like any other block.
The logic fits in one sentence. For any company linked to the contact, check that the first order date and the last order date are both set and are different. If at least one company meets that test, the condition answers “yes”. Otherwise it answers “no”.
That is the whole feature. There is no helper field to fill. There is no cron script that recalculates anything. The condition reads data that the integration already writes, at the moment the campaign reaches it.
Why does a simple “dates differ” check work?
A “dates differ” check looks too simple for a purchase counter. It works because of where contacts enter the flow.
A new shop account enters the onboarding flow with no orders at all. Both dates are empty. Then the story has three states:
| Orders so far | First order date | Last order date | Condition answers |
|---|---|---|---|
| 0 | empty | empty | no |
| 1 | set | set, same as first | no |
| 2 or more | set | set, later than first | yes |
After the first order, the ERP writes the same date into both fields. After the second order, it moves the last order date forward and leaves the first one alone. From that point the dates never become equal again.
So the check does not count orders. It detects the moment the second order lands, which is exactly what the exit rule asks for.
One edge case is worth a sentence. Two orders on the same day keep both dates equal until the next order on a later day. For an onboarding flow that runs over months, that delay is harmless. If your rule needs exact counts, you need a field that holds the count (see the alternatives below).
The check also depends on the entry rule. Customers with years of order history would answer “yes” at the first gate and leave at once. Correct, but expect it in the campaign stats.
How does the condition sit in the campaign?
Placement matters more than the code. A gate that runs at the wrong moment lets an email through to a customer who already ordered twice.
A gate before every email
The condition stands in front of every email in the first purchase track. Ten emails, ten gates. Each gate asks the same question right before its send:
- “no”: the contact still has one order or none, so the email goes out and the contact moves on to the next gate.
- “yes”: the contact is a repeat customer, so the campaign adds a tag and removes the contact from the campaign.
The interval sits on the condition
Mautic lets you set a delay on each campaign event. We put the delay on the condition, not on the email. The campaign waits, say, four days, then evaluates the condition, and on “no” the email goes out immediately.
If the delay sat on the email, the condition would run right after the previous send and the email would follow days later. A second order placed in those days would not stop it. With the delay on the gate, the check happens minutes before the send, on fresh data.
”Yes” adds a tag and exits
The “yes” branch runs two actions: add a tag (for example “repeat customer”) and remove the contact from the campaign. The tag gives the marketing team something to filter on in segments and reports. The removal ends the flow cleanly, so no scheduled event stays waiting for that contact.
Hand-offs between campaigns
The gate campaigns move contacts from the activation drip to the first purchase drip, so nobody gets two onboarding emails in one week. The second purchase condition is the last hand-off: out of onboarding entirely.
What changed when companies became a separate entity?
The first version of the condition read the two dates from contact fields.
In the final data model the business data, the order dates among them, sits on a separate company entity in Mautic, keyed by the customer number from the ERP. A contact can belong to several companies, with one marked as primary. We cover that data model in Contacts vs companies in Mautic: design the data model before you migrate.
We rewrote the condition to read companies. It now loads every company linked to the contact and passes if any of them has two different order dates.
“Any company” is a business decision, not a technical default. The alternatives would be:
- Primary company only. Simpler, but a buyer who orders for a second account would stay in onboarding.
- All companies. Strict, and a person linked to a new branch with no orders would never exit.
For a shop onboarding flow, “any company” matches what the client wanted: if this person has already bought twice for any account, stop the onboarding emails. Mautic’s positive segment filters on company fields follow the same “any company” logic, so the campaign and the segments agree.
The lesson we carry into every project: if a custom condition reads business data, write down which entity owns that data before you write the condition.
What are the alternatives to a custom condition?
A custom condition is one of four ways to implement this rule. Each of the others moves the logic somewhere else.
| Approach | How it works | Trade-offs |
|---|---|---|
| Helper field written by the integration | Middleware computes “repeat customer: yes/no” or an order count and writes it to Mautic. A native field value condition reads it. | No Mautic code. Needs work from the integration team, a backfill for existing records, and a new field to keep in sync. |
| Helper field computed by a cron job | A script in Mautic compares the two dates for all records and writes the result to a third field. | No change to the integration. Adds a scheduled job to monitor, and the value is only as fresh as the last run. |
| Segment-based exit | A segment holds repeat customers, and the campaign uses “contact segments” as the condition. | Segment filters cannot compare two fields either, so this still needs a helper field underneath. Segment rebuilds add their own delay. |
| Tag written by the shop or integration | The shop adds a “repeat customer” tag on the second order. A native tag condition reads it. | Clean on the Mautic side. Puts marketing logic into the shop or middleware, and missed events leave stale tags. |
| Custom campaign condition | A plugin compares the two fields when the campaign reaches the gate. | Always reads current data, no extra field or job. Needs a developer and a plugin to maintain across Mautic updates. |
In this project the middleware belonged to the client’s own integration team. They were busy mapping ERP and CRM data into Mautic. Asking them for a computed field would have added a dependency on their schedule for a rule that only marketing needs. The custom condition kept the rule inside Mautic, under our control, with no change to their mapping.
When is a custom campaign condition the right tool?
We use a simple set of questions.
Write a custom condition when:
- the rule compares data that already exists in Mautic (two fields, a field and a related record, values on several companies);
- the answer must be fresh at the moment of sending;
- the rule belongs to marketing logic, not to the business system;
- you do not control the integration, or changing it costs more than a small plugin.
Prefer a helper field or a tag when:
- other tools also need the result (reports, CRM, sales alerts);
- the calculation is heavy, for example it needs order history that Mautic does not store;
- you have no developer to maintain plugin code after Mautic updates.
Prefer native blocks whenever they can express the rule, even as two or three blocks in a row. They need no maintenance.
How is a Mautic campaign condition plugin structured?
A Mautic plugin is a Symfony bundle that lives in the plugins/ directory. A campaign condition needs only a few parts.
The bundle class. A PHP class named after the bundle, for example FieldCompareBundle, that extends Mautic\IntegrationsBundle\Bundle\AbstractPluginBundle. It registers the plugin with the Symfony kernel.
The config file. Config/config.php returns an array with the plugin name, description, author and version. Mautic’s plugin manager reads it. Current Mautic supports Symfony autowiring, so an event subscriber does not need a manual service definition. A Config/services.php file holds any special cases.
An event subscriber. Mautic dispatches CampaignEvents::CAMPAIGN_ON_BUILD when it builds the list of available campaign blocks. Your subscriber listens to it and calls CampaignBuilderEvent::addCondition() with a unique key and a definition. The required keys are label and eventName. Optional keys include description, formType and connectionRestrictions.
A handler. When a contact reaches your condition, the campaign engine dispatches a ConditionEvent under the eventName you registered. Your listener reads the contact from the event log, evaluates the rule and calls pass() or fail(). The engine then follows the “yes” or “no” branch.
An optional form type. If marketers should configure the condition (which fields to compare, which operator), add a Symfony form type and pass it as formType. The settings are stored on the campaign event and the handler reads them back.
Here is a generic sketch. It is an illustration, not code from the client project. It compares two contact fields that the marketer picks in the condition settings:
<?php
declare(strict_types=1);
namespace MauticPlugin\FieldCompareBundle\EventListener;
use Mautic\CampaignBundle\CampaignEvents;
use Mautic\CampaignBundle\Event\CampaignBuilderEvent;
use Mautic\CampaignBundle\Event\ConditionEvent;
use MauticPlugin\FieldCompareBundle\Form\Type\FieldsDifferType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CampaignConditionSubscriber implements EventSubscriberInterface
{
public const TYPE = 'fieldcompare.fields_differ';
public const EVENT_NAME = 'fieldcompare.on_evaluate_fields_differ';
public static function getSubscribedEvents(): array
{
return [
CampaignEvents::CAMPAIGN_ON_BUILD => ['onCampaignBuild', 0],
self::EVENT_NAME => ['onEvaluate', 0],
];
}
public function onCampaignBuild(CampaignBuilderEvent $event): void
{
$event->addCondition(self::TYPE, [
'label' => 'fieldcompare.condition.fields_differ',
'description' => 'fieldcompare.condition.fields_differ.descr',
'eventName' => self::EVENT_NAME,
'formType' => FieldsDifferType::class,
]);
}
public function onEvaluate(ConditionEvent $event): void
{
if (!$event->checkContext(self::TYPE)) {
return;
}
$log = $event->getLog();
$contact = $log->getLead();
$settings = $log->getEvent()->getProperties();
$a = $contact->getFieldValue($settings['field_a']);
$b = $contact->getFieldValue($settings['field_b']);
if (!empty($a) && !empty($b) && $a !== $b) {
$event->pass();
return;
}
$event->fail();
}
}
checkContext() matters when several conditions share one event name. It makes sure the handler only answers for its own block.
To read company fields instead, load the contact’s companies and loop over them. Mautic’s CompanyLeadRepository::getCompaniesByLeadId() returns every linked company with its fields, so the “any company” rule becomes “pass on the first company where both values are set and differ”.
Keep the handler fast. The campaign engine evaluates conditions in batches during cron runs, and a slow query in a gate multiplies across thousands of contacts.
How do you test the condition?
Test the data states as well as the code. We build a small set of test contacts that cover every row of the truth table, then run the campaign on them in a test environment.
Contacts by order history:
- 0 orders. Both dates empty. Expect “no” and the email.
- 1 order. Both dates equal. Expect “no” and the email.
- 2 orders. Dates differ. Expect “yes”, the tag, and removal from the campaign.
- Second order while waiting. Start with 1 order, change the last order date during the delay before a gate. Expect the gate to stop the next email.
Contacts with several companies:
- one company with two different dates, one company with none: expect “yes”;
- two companies, each with a single order: expect “no” (two first orders in two accounts are not a repeat purchase);
- contact with no linked company at all: expect “no”, and no error in the logs.
Broken or partial data:
- One date empty, the other set. Expect “no”. This can happen when an integration sends an empty string for a field. Mautic’s company API treats an empty string as “clear the field”, so test what your middleware actually sends.
- Different formats for the same date (a date versus a date with time). Compare normalized values, or make sure the integration always writes the same format. Otherwise two equal dates look different and a one-time buyer exits too early.
Then check the campaign log for each test contact. The event log shows which branch each gate took and when. That is quicker than reading inboxes.
Campaign design tips for gate conditions
A few rules we apply to every campaign with custom gates:
- One gate per email. Do not rely on a single check at the top of the campaign. Data changes during a nine-month flow.
- Delay on the gate, send on “no”. The check should run right before the send, not days before it.
- Exit with a tag and a removal. The tag keeps a record for segments and reports. The removal clears scheduled events.
- Write the entry rule down. The “dates differ” logic only holds because contacts enter with no orders. Put that assumption in the campaign description so nobody changes the entry segment without knowing.
- Retest after data model changes. Moving fields between contacts and companies breaks conditions silently. Run the test contacts again after every change.
FAQ
Can Mautic compare two fields without a plugin? Not in a campaign condition or a segment filter. Both compare one field with a fixed value. Without a plugin you need a helper field or a tag that something else calculates.
Does a custom campaign condition survive Mautic updates? Usually yes, because it uses the public campaign events. Plan a quick test of every custom plugin as part of each Mautic update, the same way you test the rest of the instance.
Can marketers reuse the condition for other field pairs? Yes, if you give it a form type with field pickers, as in the sketch above. The condition we built for the client answers one business question, so it has a fixed label and no settings.
What if the rule needs a real order count? Then the data must contain the count. Ask the integration to write it to a field and use the native field value condition with “greater than”.
Planning a Marketo to Mautic migration with custom rules?
This is one of the building blocks of our Marketo to Mautic migration for Meesenburg.
Have a campaign rule that Mautic cannot express out of the box? Tell us about it. We will map your automations, decide with you which rules need custom code, and build and maintain the plugins. Start at Mautomic.
Tags
Written by
Mautomic Team
Mautic experts sharing insights on marketing automation, custom development, and open-source technology.