putyourlightson / craft-campaign

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

Adding a segment programatically #490

Open scandella opened 2 weeks ago

scandella commented 2 weeks 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 1 week 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);