Use Toolset Form Slug in the CRED API, instead of their IDs

By default, when using the Toolset Forms (CRED) API, the suggestion is to listen to the Form ID in order to bind the code to a specific ID.

This works fine as long you do not migrate the website to another instance or import/export those forms to other websites.
If you do that, the ID of the forms will change, as per the auto incremental nature of Post IDs in any WordPress install.
The slug of those forms however will never change (unless you edit them).

In order to craft code that is future-proof and does not rely on the ID, you need a helper function.

This is the approach I take on all projects:

  1. Craft a helper function (in my case it will usually be OOP code, but I share the procedural function here):
	/**
	 * Get Form ID by Slug, since IDs can change when we migrate sites, but slugs not.
	 *
	 * @since             YOUR VERSION
	 * @param string $form_slug The Form name.
	 * @param string $form_type The Form Type.
	 * @return $form_id.
	 */
	function get_toolset_form_id( $form_slug, $form_type ) {

		$form = get_page_by_path( $form_slug, OBJECT, $form_type );

		if ( $form ) {
			$form_id = $form->ID;
		} else {
			$form_id = 0;
		}

		return $form_id;

	}
  1. Then, in your CRED API (such as cred_save_data or else) you will use it like so:
    $form_id = get_toolset_form_id( 'your-form-slug', 'cred-form' ); // cred-form for POST forms, user-form for USER forms)
    if ( $form_data['id'] === $form_id ) {...}

Example:

add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
    // if a specific form
   $form_id = get_toolset_form_id( 'your-form-slug', 'cred-form' );
   if ( $form_data['id'] === $form_id )
    {
        if (isset($_POST['my_custom_field']))
        {
            // add it to saved post meta
            add_post_meta($post_id, '__my_custom_field', $_POST['my_custom_field'], true);
        }
    }
}