SugarCRM: Custom Logic Hook - php

I am looking to develop a custom logic hook for our SugarCRM system (uses PHP) which provides the following function:
On Save of a Quote record (either new or update):
IF no contact records have already been linked to the quote THEN
Get contacts linked to the related Opportunity
Link these contacts to the quote
I have created the logic hook as per SugarCRM developer documentation and loaded into our dev instance (we run in SugarCloud) but the hook does not appear to fire. Can anyone help me?
./custom/Extension/modules/Quotes/Ext/LogicHooks/initialiseRecord.php
<?php
$hook_version = 1;
$hook_array['after_save'][] = Array(
//Processing index. For sorting the array.
1,
//Label. A string value to identify the hook.
'after_save example',
//The PHP file where your class is located.
'custom/modules/Quotes/initialise_record.php',
//The class the method is in.
'after_save_initialise_class',
//The method to call.
'after_save_initialise'
);
.custom/modules/Quotes/initialise_record.php
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
// bean in this context will be Quotes bean being saved
class after_save_initialise_class
{
function after_save_initialise($bean, $event, $arguments)
{
require_once('include/SugarQuery/SugarQuery.php');
$sugarQuery = new SugarQuery();
//Determine if contacts have already been linked
if ($bean->load_relationship('contacts')) {
//Fetch related beans
$relatedBeans = $bean->contacts->get();
// If no contacts have already been connected then initialise. Otherwise abort.
if (count($relatedBeans) === 0) {
// Step 1: Get Opportunity related to quote.
if ($bean->load_relationship('opportunities')) {
//Fetch related beans
$relatedOpportunityBeans = $bean->opportunities->get();
//Retrieve the bean id of the linked opportunity record
$opportunity_record_id = $relatedOpportunityBeans[0];
// Step 2: Get Contacts linked to Opportunity
//Retrieve Opportunity bean
$opportunity_bean = BeanFactory::retrieveBean('Opportunities', $opportunity_record_id);
if ($opportunity_bean->load_relationship('contacts')) {
//Retrieve all contacts connected to that opportunity
$relatedContactBeanIds = $bean->contacts->get();
// Loop through these adding them to the quote bean
foreach ($relatedContactBeanIds as &$value) {
// quotes_contacts_1 is the name of custom many-to-many relationship in SugarCRM between the Quotes and Contacts module created in 'Studio' within SugarCRM
$bean->quotes_contacts_1->add($value);
};
};
};
}
}
}
}
.manifest.php {Used by SugarCRM Package Loader to install the package}
<?php
$manifest = array(
'key' => 202106270819,
'name' => 'Sync Contacts To Quote',
'description' => 'Adds Custom Logic Hook to Sync Contacts from Opportunity to Quote Level',
'author' => 'TBC',
'version' => '1.0',
'is_uninstallable' => true,
'type' => 'module',
'acceptable_sugar_versions' =>
array(
'regex_matches' => array(
'11.0.*' //any 11.0 release
),
),
'acceptable_sugar_flavors' =>
array(
'PRO',
'ENT',
'ULT'
),
'readme' => '',
'icon' => '',
'remove_tables' => '',
'uninstall_before_upgrade' => false,
);
$installdefs = array (
'id' => 'SyncContactOpportunityQuote',
'hookdefs' => array(
array(
'from' => '<basepath>/custom/Extension/modules/Quotes/Ext/LogicHooks/initialiseRecord.php',
'to_module' => 'application',
)
),
'copy' => array(
0 => array(
'from' => '<basepath>/custom/modules/Quotes/initialise_record.php',
'to' => 'custom/modules/Quotes/initialise_record.php'
)
)
);
?>
References:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_11.0/Architecture/Logic_Hooks/
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_11.0/Data_Framework/Models/SugarBean/#Updating_a_Bean

Does your Hook get executed at all? How did you verify that it does or doesn't?
If it does get loaded, I suspect that it skips/quits at
//Determine if contacts have already been linked
if ($bean->load_relationship('contacts')) {
//Fetch related beans
$relatedBeans = $bean->contacts->get();
contacts in 2nd and last line isn't an actual field in Quotes, is it?
Did you mean to use quotes_contacts_1 in those two places?
(Which you referred to farther below)
Also with regards to the manifest.php:
I'm not familiar with hookdefs (I just use regular copy to install the hook file), but 'to_module' => 'application',, seems odd - don't you mean 'to_module' => 'Quotes',?

To get related contacts from opportunities
$opp = $bean->opportunities->getBeans();
$opportunity_record_id = $opp->id;

Related

Filter list that does not have an invalid email and opt-out email using SugarCRM 7 API

I want to filter list that does not have an invalid email and opt-out email in Leads and Contact module using SugarCRM 7 API.
I have added below email filter in arguments but does not work. How to email filter via SugarCRM 7.x rest API.
$filter_arguments = array(
"filter" => array(
array(
"assigned_user_id" => 1,
),
array(
"email1" => array(
array(
'opt_out' => array(
'$equals' => ''
)
)
)
),
),
);
$url = $base_url . "/Contacts/filter";
Thanks.
This much code will not help you please check this :
Reference Link 1
Reference Link 2
The following example will demonstrate how to add a predefined filter on the Accounts module to return all records with an account type of "Customer" and industry of "Other".
To create a predefined filter, create a display label extension in ./custom/Extension/modules/<module>/Ext/Language/. For this example, we will create:
./custom/Extension/modules/Accounts/Ext/Language/en_us.filterAccountByTypeAndIndustry.php
<?php
$mod_strings['LBL_FILTER_ACCOUNT_BY_TYPE_AND_INDUSTRY'] = 'Customer/Other Accounts';
Next, create a custom filter extension in ./custom/Extension/modules/<module>/Ext/clients/base/filters/basic/.
For this example, we will create:
./custom/Extension/modules/Accounts/Ext/clients/base/filters/basic/filterAccountByTypeAndIndustry.php
<?php
$viewdefs['Accounts']['base']['filter']['basic']['filters'][] = array(
'id' => 'filterAccountByTypeAndIndustry',
'name' => 'LBL_FILTER_ACCOUNT_BY_TYPE_AND_INDUSTRY',
'filter_definition' => array(
array(
'account_type' => array(
'$in' => array(
'Customer',
),
),
),
array(
'industry' => array(
'$in' => array(
'Other',
),
),
),
),
'editable' => false,
'is_template' => false,
);
You should notice that the editable and is_template options have been set to "false". If editable is not set to "false", the filter will not be displayed in the list view filter's list.
Finally, navigate to Admin > Repair and click "Quick Repair and Rebuild" to rebuild the extensions and make the predefined filter available for users.
Adding Initial Filters to Lookup Searches
To add initial filters to record lookups and type-ahead searches, define a filter template. This will allow you to filter results for users when looking up a parent related record. The following example will demonstrate how to add an initial filter for the Account lookup on the Contacts module. This initial filter will limit records to having an account type of "Customer" and a dynamically assigned user value determined by the contact's assigned user.
To add an initial filter to the Contacts record view, create a display label for the filter in ./custom/Extension/modules/<module>/Ext/Language/. For this example , we will create:
./custom/Extension/modules/Accounts/Ext/Language/en_us.filterAccountTemplate.php
<?php
$mod_strings['LBL_FILTER_ACCOUNT_TEMPLATE'] = 'Customer Accounts By A Dynamic User';
Next, create a custom template filter extension in ./custom/Extension/modules/<module>/Ext/clients/base/filters/basic/.
For this example, create:
./custom/Extension/modules/Accounts/Ext/clients/base/filters/basic/filterAccountTemplate.php
<?php
$viewdefs['Accounts']['base']['filter']['basic']['filters'][] = array(
'id' => 'filterAccountTemplate',
'name' => 'LBL_FILTER_ACCOUNT_TEMPLATE',
'filter_definition' => array(
array(
'account_type' => array(
'$in' => array(),
),
),
array(
'assigned_user_id' => ''
)
),
'editable' => true,
'is_template' => true,
);
As you can see, the filter_definition contains arrays for account_type and assigned_user_id. These filter definitions will receive their values from the contact record view's metadata. You should also note that this filter has is_template and editable set to "true". This is required for initial filters.
Once the filter template is in place, modify the contact record view's metadata. To accomplish this, edit ./custom/modules/Contacts/clients/base/views/record/record.php to adjust the account_name field. If this file does not exist in your local Sugar installation, navigate to Admin > Studio > Contacts > Layouts > Record View and click "Save & Deploy" to generate it. In this file, identify the panel_body array as shown below:
1 =>
array (
'name' => 'panel_body',
'label' => 'LBL_RECORD_BODY',
'columns' => 2,
'labelsOnTop' => true,
'placeholders' => true,
'newTab' => false,
'panelDefault' => 'expanded',
'fields' =>
array (
0 => 'title',
1 => 'phone_mobile',
2 => 'department',
3 => 'do_not_call',
4 => 'account_name',
5 => 'email',
),
),
Next, modify the account_name field to contain the initial filter parameters.
1 =>
array (
'name' => 'panel_body',
'label' => 'LBL_RECORD_BODY',
'columns' => 2,
'labelsOnTop' => true,
'placeholders' => true,
'newTab' => false,
'panelDefault' => 'expanded',
'fields' =>
array (
0 => 'title',
1 => 'phone_mobile',
2 => 'department',
3 => 'do_not_call',
4 => array (
//field name
'name' => 'account_name',
//the name of the filter template
'initial_filter' => 'filterAccountTemplate',
//the display label for users
'initial_filter_label' => 'LBL_FILTER_ACCOUNT_TEMPLATE',
//the hardcoded filters to pass to the templates filter definition
'filter_populate' => array(
'account_type' => array('Customer')
),
//the dynamic filters to pass to the templates filter definition
//please note the index of the array will be for the field the data is being pulled from
'filter_relate' => array(
//'field_to_pull_data_from' => 'field_to_populate_data_to'
'assigned_user_id' => 'assigned_user_id',
)
),
5 => 'email',
),
),
Finally, navigate to Admin > Repair and click "Quick Repair and Rebuild". This will rebuild the extensions and make the initial filter available for users when selecting a parent account for a contact.
Adding Initial Filters to Drawers from a Controller
When creating your own views, you may need to filter a drawer called from within your custom controller. Using an initial filter, as described in the Adding Initial Filters to Lookup Searches section, we can filter a drawer with predefined values by creating a filter object and populating the config.filter_populate property as shown below:
//create filter
var filterOptions = new app.utils.FilterOptions()
.config({
'initial_filter': 'filterAccountTemplate',
'initial_filter_label': 'LBL_FILTER_ACCOUNT_TEMPLATE',
'filter_populate': {
'account_type': ['Customer'],
'assigned_user_id': 'seed_sally_id'
}
})
.format();
//open drawer
app.drawer.open({
layout: 'selection-list',
context: {
module: 'Accounts',
filterOptions: filterOptions,
parent: this.context
}
});
To create a filtered drawer with dynamic values, create a filter object and populate the config.filter_relate property using the populateRelate method as shown below:
//record to filter related fields by
var contact = app.data.createBean('Contacts', {
'first_name': 'John',
'last_name': 'Smith',
'assigned_user_id': 'seed_sally_id'
});
//create filter
var filterOptions = new app.utils.FilterOptions()
.config({
'initial_filter': 'filterAccountTemplate',
'initial_filter_label': 'LBL_FILTER_ACCOUNT_TEMPLATE',
'filter_populate': {
'account_type': ['Customer'],
},
'filter_relate': {
'assigned_user_id': 'assigned_user_id'
}
})
.populateRelate(contact)
.format();
//open drawer
app.drawer.open({
layout: 'selection-list',
context: {
module: 'Accounts',
filterOptions: filterOptions,
parent: this.context
}
});

Create campaign with dynamic segment using MailChimp API V3.0

Using MailChimp API V3.0 to create a campaign.
I want to create a campaign that sends to users with a specific interest. It looks like this is possible in the docs, but I've tried every permutation I can think of. I can create the campaign fine as long as I leave out the segment_ops member. Does anyone have an example of PHP code that will do it?
It seems that interests are handled strangely since you don't include the interest-category when setting a users interests via the API. I'm not sure how this affects campaign creation.
I've gotten this to work, API definition can be found here https://us1.api.mailchimp.com/schema/3.0/Segments/Merge/InterestSegment.json
Interests have to be grouped under interest categories (called 'Groups' in some parts of the UI).
Here is the JSON for the segment_opts member of the recipients array:
"segment_opts": {
"match": "any",
"conditions": [{
"condition_type": "Interests",
"field": "interests-31f7aec0ec",
"op": "interestcontains",
"value": ["a9014571b8", "5e824ac953"]
}]
}
Here is the PHP array version with comments. The 'match' member refers to the the rules in the array of 'conditions'. The segment can match any, all, or none of the conditions. This example has only one condition, but others can be added as additional arrays in the 'conditions' array:
$segment_opts = array(
'match' => 'any', // or 'all' or 'none'
'conditions' => array (
array(
'condition_type' => 'Interests', // note capital I
'field' => 'interests-31f7aec0ec', // ID of interest category
// This ID is tricky: it is
// the string "interests-" +
// the ID of interest category
// that you get from MailChimp
// API (31f7aec0ec)
'op' => 'interestcontains', // or interestcontainsall, interestcontainsnone
'value' => array (
'a9014571b8', // ID of interest in that category
'5e824ac953' // ID of another interest in that category
)
)
)
);
You may also send to a Saved segment. The gotcha on this is that the segment_id has to be int. I was saving this value in a db as varchar, and it would not work unless cast to int.
(i am using use \DrewM\MailChimp\MailChimp;)
$segment_id = (int) $methodThatGetsMySegmentID;
$campaign = $MailChimp->post("campaigns", [
'type' => 'regular',
'recipients' => array(
'list_id' => 'abc123yourListID',
'segment_opts' => array(
'saved_segment_id' => $segment_id,
),
),
'settings' => array(
'subject_line' => 'A New Article was Posted',
'from_name' => 'From Name',
'reply_to' => 'info#example.com',
'title' => 'New Article Notification'
)
]);

Changing display logic for a field in sugarcrm

I have the following situation: Contacts without a first or last name, in fact, they only have a email address.
I can work with these contacts fine, but when I use the listview anywhere (for instance to show all contacts from a company) there now is no way to click through to the contact (normally you would click on the name).
I'm looking for a way to solve this, for instance by showing a clickable text like 'name not known', but can't figure out how to do this. I've been looking at the manual and in the files in the modules directory and the sugarfields dir, but can't quite figure it out.
The closest I got was in /sugarcrm/modules/Contacts/metadata/listviewdefs.php
where this piece of code resides:
$listViewDefs['Contacts'] = array(
'NAME' => array(
'width' => '20%',
'label' => 'LBL_LIST_NAME',
'link' => true,
'contextMenu' => array('objectType' => 'sugarPerson',
'metaData' => array('contact_id' => '{$ID}',
'module' => 'Contacts',
'return_action' => 'ListView',
'contact_name' => '{$FULL_NAME}',
'parent_id' => '{$ACCOUNT_ID}',
'parent_name' => '{$ACCOUNT_NAME}',
'return_module' => 'Contacts',
'return_action' => 'ListView',
'parent_type' => 'Account',
'notes_parent_type' => 'Account')
),
'orderBy' => 'name',
'default' => true,
'related_fields' => array('first_name', 'last_name', 'salutation', 'account_name', 'account_id'),
),
Somewhere there has to be a function that joins the first and lastname together...
Edit: I found a solution:
The actual concatenation function is in /sugarcrm/include/SugarObjects/templates/person/person.php and is called _create_proper_name_field()
I can modify the output for my specific case by adding something like this to the end of the function:
if (empty(trim($full_name))){
$full_name = 'Name unknown';
}
However, I would rather have a upgrade safe solution, so that will be the next challenge.
Don't edit the core because the next upgrade will break your SugarCRM instance. Use logic hooks to be upgrade safe:
create a file 'logic_hooks.php' in /custom/modules/Contacts/
In that file, add the followin code:
<?php
$hook_array['before_save'][] = Array(1,'logic_fill_name','custom/modules/Contacts/logic_hooks/logics.php','ContactLogics','logic_fill_name');
After you have done this. create the file 'logics.php' in /custom/modules/Contacts/logic_hooks.
In the logics.php file, add something like:
<?php
require_once 'include/SugarQuery/SugarQuery.php';
/**
* Class ContactLogics
*/
class ContactLogics {
/**
* #param $bean
* #param $event
* #param $arguments
*/
public function logic_fill_name($bean, $event, $arguments) {
if (empty(trim($bean->first_name)) && empty(trim($bean->last_name))){
$bean->last_name = 'Name unknown';
}
}
}
Now some explanation. When you edited a recordview and pressed the save button, the logic hook 'before_save' will be triggered. This code will change the full name to 'Name unknown' when the full name is empty. When the 'before_save' is executed, the actual save will take place.

Troubleshooting dynamic dropdowns in SugarCRM 6.5

I had asked a question here a while back about setting up database populated dropdowns for SugarCRM. I received a really good answer and, after more php studies and a dev instance running, I decided to give it a shot. The instructions I followed can be found here. After I run the repair and rebuild, I would expect to see the custom field in my Fields list under the module in studio, but have not been able to find it. The module is named Makers (a1_makers as a database table). For good orders sake, there were no errors when I repaired/rebuilt after saving the files. Per the instructions, I first created a php file with a custom function to query the database (custom/Extension/application/Ext/Utils/getMakers.php):
<?php
function getMakers() {
static $makers = null;
if (!$makers){
global $db;
$query = "SELECT id, name FROM a1_maker";
$result = $db->query($query, false);
$accounts = array();
$accounts[''] = '';
while (($row = $db->fetchByAssoc($result)) !=null) {
$accounts[$row['id']] = $row['name'];
}
}
return $makers;
}
?>
Then, I set 'function' field in Vardefs to point to the function (custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php):
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'len' => '100',
'comment' => 'List of makers populated from the database',
);
?>
Unfortunately, there are no errors and the repair/rebuild runs fine. I am just unable to see the custom field when I go into studio. Can anyone please help point out what I may be doing wrong?
I would recommend checking existence of newly created field 'list_of_makers' in cache/modules/Maker/Makervardefs.php file. If new field definition exists in that file, try add 'studio' => 'visible' to custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php to get something like this:
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
);
Try to edit your custom/modules/Maker/metadata/editviewdefs.php manually and insert field definition by hand in proper place if everything above won't work.
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
'studio' => array(
'listview' => true,
'detailview' => true,
'editview' => true
),
);

MailChimp API PHP - Add to Interest Group

I'm currently using the MailChimp API for PHP, version 1.3.1 (http://apidocs.mailchimp.com/api/downloads/#php)
I've set up a list in MailChimp, and would like to dynamically add:
Subscribers to the list (done: $objMailChimp->listBatchSubscribe($strMailingListID, ...))
Interest Groupings (done: $objMailChimp->listInterestGroupingAdd($strMailingListID, ...))
Interest Groups into those Groupings (done: $objMailChimp->listInterestGroupAdd($strMailingListID, ...))
Subscribers assigned to relevant Groups (not done)
The API (http://apidocs.mailchimp.com/api/1.3/#listrelated) is somewhat unclear on how to add a subscriber to an interest group - does anyone here have any ideas?
As of version 2.0 of MailChimp's API, this should work:
$merge_vars = array(
'GROUPINGS' => array(
array(
'name' => "GROUP CATEGORY #1", // You can use either 'name' or 'id' to identify the group
'groups' => array("GROUP NAME","GROUP NAME")
),
array(
'name' => "GROUP CATEGORY #2",
'groups' => array("GROUP NAME")
)
)
);
Source: http://apidocs.mailchimp.com/api/2.0/lists/subscribe.php
Using a barebones PHP wrapper (https://github.com/drewm/mailchimp-api/) you can then send this to MailChimp via either the lists/subscribe or lists/batch-subscribe:
$MailChimp = new MailChimp('API_KEY');
$result = $MailChimp->call('lists/subscribe', array(
'id' => 'LIST ID',
'email' => array('email'=>'trevor#example.com'),
'merge_vars' => $merge_vars
));
For MailChimp API v3
As of v3, 'groupings' has changed to 'interests'.
You have to find out the ID of the group (interest) that you are wanting to add to. Unfortunately this cannot be found anywhere on the MailChimp dashboard.
The easiest way to find out the 'interest' ID (rather than creating a script) is to go to the MailChimp playground and then, after entering in your API key, route to...
lists > the list in question > interest-categories (in the sub-resources dropdown)
then...
interests (in the sub-resources dropdown) for interest category
then...
Click through to the interest and refer to the 'id' field, ignoring the other ID fields
OR
lists > the list in question > members (in the sub-resources dropdown)
then...
load (in the actions dropdown) for any member
or
Create Members (button)
The page will load the member's details. Scroll down until you see the 'interests' array/object. There you will see the IDs. Notice they can be set to true or false.
You will have to figure out which ID relates to what 'group'/'interest' by going about the previous method or making the call, and then looking at the member's details via your MailChimp dashboard.
So when it comes to actually making the POST call ('member' create), you would want something on the lines of...
{
"email_address":"example#freddiesjokes.com",
"status":"subscribed",
"interests": {
"b8a9d7cbf6": true,
"5998e44916": false
},
# ADDITIONAL FIELDS, IF REQUIRED...
"merge_fields":{
"FNAME": "foo bar",
"LNAME": "foo bar",
"MERGE3": "foo bar",
"MERGE4": "foo bar"
}
}
A PUT call ('member' edit) example...
{
"interests": {
"b8a9d7cbf6": false,
"5998e44916": true
}
}
It seems that you must declare every 'interest', and state whether it is true or false.
I could not get the other answers on this page to work. Here's the merge vars that I had to use:
$merge_vars = array(
'GROUPINGS' => array(
0 => array(
'id' => "101", //You have to find the number via the API
'groups' => "Interest Name 1, Interest Name 2",
)
)
);
Use GROUPINGS merge var:
Set Interest Groups by Grouping. Each element in this array should be
an array containing the "groups" parameter which contains a comma
delimited list of Interest Groups to add. Commas in Interest Group
names should be escaped with a backslash. ie, "," => "\," and either
an "id" or "name" parameter to specify the Grouping - get from
listInterestGroupings()
Here's the code I got to work
require_once 'MCAPI.class.php';
require_once 'config.inc.php'; //contains apikey
// use this once to find out id of interest group List
//$retval = $api->listInterestGroupings($listId);
//echo '<pre>';
//print_r($retval);
//echo '</pre>';
//die();
$emailAddress = 'info#example.com';
//You have to find the number via the API (id of interest group list)
$interestGroupListId = FILLMEIN;
$api = new MCAPI($apikey);
// Create an array of Interest Groups you want to add the subscriber to.
$mergeVars = array(
'GROUPINGS' => array(
0 => array(
'id' => $interestGroupListId,
'groups' => "FILL IN GROUP NAMES",
)
)
);
// Then use listUpdateMember to add them
$retval = $api->listUpdateMember($listId, $emailAddress, $mergeVars);
if ($api->errorCode){
echo "Unable to update member info!\n";
echo "\tCode=".$api->errorCode."\n";
echo "\tMsg=".$api->errorMessage."\n";
} else {
echo "Returned: ".$retval."\n";
}
This is a variation of Justins answer but having tried all the above this is the only one I could get to work with DrewM's MailChimp wrapper
$merge_vars = array(
'GROUPINGS' => array(
0 => array(
'id' => '[GROUP_LIST_ID]', // need grouping ID
'name' => '[OR_GROUP_LIST_NAME]', // or name instead
'groups' => array( '[GROUP_NAME_1]', '[GROUP_NAME_2]' )
)
),
);
$mc = new MailChimp('[YOUR_MAILCHIMP_API]');
$mc->call(
'lists/subscribe', array(
'id' => '[YOUR_LIST_ID]', // list ID
'email' => array( 'email' => 'someone#something.com'),
'merge_vars' => $merge_vars,
'double_optin' => true,
'update_existing' => true,
'replace_interests' => false, // do you want to add or replace?
'send_welcome' => false,
)
);
If you are unsure of your groups lists ID and wish to use it you can call:
$current_groupings = $mc->call( 'lists/interest-groupings', array(
'id' => '[GROUP_LIST_ID]',
) );
var_dump($current_groupings);
Also please note optional but very important last parameter of listUpdateMember, by default replace_interests it set to true so it will overwrite any subscription the user you are updating could have had in the past. If you want to add new ones not touching previous ones just pass the new group name you wanna add and set replace_interests to false.
$api = new MailChimp('API_KEY');
$pArray = array('GROUPINGS'=>array(
array('name'=>'GROUP CATEGORY', 'groups'=>'group1,group2'),
)
);
if (is_array($pArray)) {
$api->listUpdateMember($pListId, $pEmail, $pArray, '', false);
}
Example using DrewM's MailChimp wrapper and shorthand syntax for arrays (PHP 5.4+) add to groups:
$merge_vars = [
'GROUPINGS' => array(
0 => [
'id' => 12345, // need grouping ID
'name' => 'Interests', // or name instead
'groups' => [ 'cars', 'trucks' ]
]
]
];
$mc = new MailChimp('API_KEY');
$mc->call(
'lists/subscribe', [
'id' => '9876', // list ID
'email' => array[ 'email' => 'example#abc.com' ],
'merge_vars' => $merge_vars,
'double_optin' => true,
'update_existing' => true,
'replace_interests' => false, // do you want to add or replace?
'send_welcome' => false,
]
);
You need grouping 'name' OR 'id', both are not needed. To get grouping ID use: lists/interest-groupings

Categories