PHP code example of tractorcow / silverstripe-campaignmonitor

1. Go to this page and download the library: Download tractorcow/silverstripe-campaignmonitor library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tractorcow / silverstripe-campaignmonitor example snippets



	function updateCMSFields(FieldList $fields) {

		// Load base object
		$resources = CMResources::create("my api key");

		// Get clients under our account
		$clients = $resources->Clients()->map();
		$fields->addFieldToTab(
			'Root.CampaignMonitor',
			DropdownField::create('Client', 'Client', $clients)
		);

		// check if client is available to select
		if($this->owner->Client && ($client = $resources->getClient($this->owner->Client))) {
			$lists = $client->Lists()->map();
			$fields->addFieldToTab(
				'Root.CampaignMonitor',
				DropdownField::create('DefaultList', 'Default List', $lists)
			);
		}
	}



	public function subscribe($data, $form)
	{
		$listID = SiteConfig::current_site_config()->DefaultList;
		$resources = CMResources::create("my api key");
		if($resources && $listID && $list = $resources->getList($listID)) {
			$this->addUserToList($data, $list);
			Director::redirect($this->Link('thanks'));
		}
		// Error handling here
	}

	protected function addUserToList($data, $list)
	{
		if(empty($list)) return;

		// Create subscriber
		$fields = [
			'EmailAddress' => $data['Email'],
			'Name' => $data['FirstName'],
			'CustomFields' => [
				'LastName' => $data['LastName'],
				'Company' => $data['Company'],
				'Phone' => $data['Phone'],
				'Mobile' => $data['Mobile']
			],
			'Resubscribe' => true,
			'RestartSubscriptionBasedAutoresponders' => true
		];
		$subscriber = CMSubscriber::create(null, $fields, $list);
		$subscriber->Save();
	}