putyourlightson / craft-campaign

Send and manage email campaigns, contacts and mailing lists in Craft CMS.
https://putyourlightson.com/plugins/campaign
Other
63 stars 25 forks source link

Adding a segment programatically #490

Closed scandella closed 2 days ago

scandella commented 2 months ago

Support Request

Is there a way to add segments programmatically? As for contacts we have: FormService::createAndSubscribe()

Is there a method for segments to be added from a module?

Thanks for your help.

Plugin Version

2.15.3

bencroker commented 2 months ago

Creating a segment can be done as with any element. The challenge is going to be to construct the contact condition, which can be passed in using a ContactCondition class or an array. The simplest way to figure this out might be go inspect the request parameters in the Network tab of your browser’s dev tools when creating/saving a segment in the CP.

use Craft;
use putyourlightson\campaign\elements\SegmentElement;

$segment = new SegmentElement();
$segment->title = 'Test Segment';
$segment->slug = 'test-segment';
$segment->segmentType = 'regular';

// Pass in a ContactCondition class or an array
$segment->setContactCondition([]);

Craft::$app->getElements()->saveElement($segment);