Custom form code for multiple forms (mailerlite integration)

I’ve written this integration for Mailerlite and set it up for one of my forms:

<?php 
function my_form_custom_action( $form ) {  
  $form_fields = $form->get_fields();
  $form_id = $form_fields['formId'];

  if( $form_id !== 'yzrfqi' ) return;
  $email_address = $form->get_field_value( 'lqmhlc' );

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.mailerlite.com/api/v2/groups/XXXXXXXX/subscribers/",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode([
    'email' => $email_address,
    'enable' => true
  ]),
  CURLOPT_HTTPHEADER => [
    "X-MailerLite-ApiDocs: true",
    "X-MailerLite-ApiKey: XXXXXXXXXXXXXXXXXXXXX",
    "accept: application/json",
    "content-type: application/json"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  return $err;
} else {
  return $response;
}
  // Set result in case it fails
  $form->set_result([
    'action' => 'my_custom_action',
    'type'    => 'success', //or danger or info
    'message' => esc_html__('There was an error. Please contact us via email', 'bricks'),
  ]);

}
add_action( 'bricks/form/custom_action', 'my_form_custom_action', 10, 1 );
?>

I have multiple different forms on different pages. How do I easily make this code apply to all forms and their email fields? Without just multiplying the entire code.

Hi @christian , I’m in the same situation here. Did you find a solution in the end, for this use case ? (multiple forms)

Nope, I just have this script x3 for 3 different forms… Not good practice, I know :frowning:

function my_form_custom_action( $form ) {  
  $form_fields = $form->get_fields();
  $form_id = $form_fields['formId'];

  if ($form_id !== 'yzrfqi' || $form_id !== 'jkhjkhkh' || $form_id !== 'uuyyr') {
    return;
} else {
    $email_address = $form->get_field_value( $form_id );
}

$curl = curl_init();
function my_form_custom_action( $form ) {  
  $form_fields = $form->get_fields();
  $form_id = $form_fields['formId'];
if( $form_id == 'yzrfqi' ) {
$email_address = $form->get_field_value( 'lqmhlc' );
$curl = curl_init();
curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.mailerlite.com/api/v2/groups/XXXXXX/subscribers/",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode([
    'email' => $email_address,
    'enable' => true
  ]),
  CURLOPT_HTTPHEADER => [
    "X-MailerLite-ApiDocs: true",
    "X-MailerLite-ApiKey: XXXXXXXXX",
    "accept: application/json",
    "content-type: application/json"
  ],
]);
return curl_exec($curl);
}
  // Set result in case it fails
  $form->set_result([
    'action' => 'my_custom_action',
    'type'    => 'success', //or danger or info
    'message' => esc_html__('There was an error. Please contact us via email', 'bricks'),
  ]);

}
add_action( 'bricks/form/custom_action', 'my_form_custom_action', 10, 1 );

Btw @matt_SF I updated the code a bit compared to the one in the top

@clickfusion63 You need to get the field for the email on the form, so I don’t think yours will work

Thank you for your answer @christian .
I’m using the new API version so I had to change some things :

function my_form_custom_action( $form ) {

    $form_fields = $form->get_fields();
    $form_id = $form_fields['formId'];

    $groupID = "XXXXXXX";

    if( $form_id == 'yzrfqi' ) {
        $email_address = $form->get_field_value( 'lqmhlc' );
        $name = $form->get_field_value( 'cjtlqe' );

        $data = [
            'email' => $email_address,
            'fields' => [
                'name' => $name,
            ],
            'groups' => [$groupID],
        ];

        $data_json = wp_json_encode($data);

        $curl = curl_init();
        curl_setopt_array($curl, [
          CURLOPT_URL => "https://connect.mailerlite.com/api/subscribers", // API v3 endpoint,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data_json,
            CURLOPT_HTTPHEADER => [
            "Authorization: Bearer API_TOKEN",
            "Content-Type: application/json",
            "Accept: application/json",
            ],
        ]);
        return curl_exec($curl);
    }
  // Set result in case it fails
  $form->set_result([
    'action' => 'my_custom_action',
    'type'    => 'success', //or danger or info
    'message' => esc_html__('There was an error. Please contact us via email', 'bricks'),
  ]);

}
add_action( 'bricks/form/custom_action', 'my_form_custom_action', 10, 1 );

It’s not working right now, but I’m still on it.
Thanks again!

EDIT : Actually there was just a typo… I updated the code block and wrote the whole modified function. Now it’s working :partying_face:
Again, thank you @christian :pray:

nice! :slight_smile:
Did you figure out how to make it for more than one form without duplicating the whole code?

The solution would be to use an array containing the forms Ids and an array containing the groups Ids. Then, writing a function that will get the current used form and perform the action…
But I don’t know yet how to write that in php :sweat_smile:!

I’ll tackle it during the next days. If I manage to do it I’ll post the solution :+1:

1 Like

OK, here we go:


function my_form_custom_action( $form ) {
    $form_fields = $form->get_fields(); // Get the fields of the current form
    $form_id = $form_fields['formId']; // Get the form id

    // Map form IDs to group IDs
    $form_groups = [
        'form1_id' => 'group1_id',
        'form2_id' => 'group2_id',
        // Add more mappings as needed
    ];

    // Check if the current form's ID exists in the mappings
    if (array_key_exists($form_id, $form_groups)) {
        $groupID = $form_groups[$form_id]; // Get the group ID based on the form

        // Assuming you have a consistent way to identify email and name fields across forms,
        // you might still need specific handling if field IDs differ from form to form.
        $email_address = $form->get_field_value('email_field_id'); // Adjust field ID as necessary
        $name = $form->get_field_value('name_field_id'); // Adjust field ID as necessary

        // User data formatted for MailerLite
        $data = [
            'email' => $email_address,
            'fields' => ['name' => $name],
            'groups' => [$groupID],
        ];

        $data_json = wp_json_encode($data);

        // Sending the data to MailerLite
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://connect.mailerlite.com/api/subscribers",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data_json,
            CURLOPT_HTTPHEADER => [
                "Authorization: Bearer API_TOKEN",
                "Content-Type: application/json",
                "Accept: application/json",
            ],
        ]);
        $response = curl_exec($curl);
        curl_close($curl);

        // Handle response
        if ($response) {
            $form->set_result([
                'action' => 'my_custom_action',
                'type' => 'success',
                'message' => esc_html__('Thank you for subscribing!', 'bricks'),
            ]);
        } else {
            // If the request fails, set an error message
            $form->set_result([
                'action' => 'my_custom_action',
                'type' => 'danger',
                'message' => esc_html__('There was an error. Please contact us via email', 'bricks'),
            ]);
        }
    }
}
add_action('bricks/form/custom_action', 'my_form_custom_action', 10, 1);

So, I tried it only with 2 different forms but it’s working :partying_face: :smiley:
I’m not a PHP developer though so, if someone could review this snippet and share his thoughts, that would be great.

1 Like