BlogFileMaker

How to Use FileMaker 17 to Connect the Data API and Your WordPress Website

By June 13, 2018 May 7th, 2019 9 Comments

Connecting Your WordPress Website and FileMaker Solution

In this post, we demonstrate how you can submit a form built with a freely available WordPress plugin, Ninja Forms. This makes building web forms easy while staying compliant with a WordPress theme. This process also supports responsiveness of your WordPress deployment.

You do not need access to the backend MySQL database, which is not always easy or available. This makes it very portable and convenient to add as a WordPress administrator. You only need to add a custom action to the Theme Functions (“functions.php”) file in WordPress and specify that custom action in your Ninja Forms configuration.

Previous Strategy: Custom Web Publishing

Previously in FileMaker 16 and prior, you could send data to a CWP (custom web publishing) script that could include the FM API for PHP and use that to insert to your database. This required a web server running PHP, possibly on the same machine where FileMaker Server was running.

Simplified Process with the FileMaker Data API

That changes in FileMaker 17. Now, you can communicate directly with the newly available Data API to insert a new record in your database with no other pieces needed or external APIs to load.

Both methods use a WordPress function, WP_Http(), to make the external requests and submit all form data entered by end users. In WordPress, go to Appearance->Editor, then select the Theme Functions file and insert the following code, with adjustments made to the variables at the top of the function.

add_action( 'fm_WordPress_action', 'fm_data_api_form' );
function fm_data_api_form( $form_data ){
  // set variables
  $myServer = 'https://your_server_name/'; // the url of your server
  $myUser = 'Username'; // your username
  $myPass = 'password'; // your password 
  $myFile = 'Your_File'; // your file name
  $myLayout = 'Your_Layout'; // your layout name
  
  // authenticate and get token
  $myEndpoint = 'fmi/data/v1/databases/' . $myFile . '/sessions';
  $post_url = $myServer . $myEndpoint;
  $headers = array('Authorization' => 'Basic '.base64_encode("$myUser:$myPass") , 'Content-Type' => 'application/json');
  $request = new WP_Http();
  $response = $request->request($post_url, array( 'method' => 'POST', 'body' => $myJSON, 'headers' => $headers ));
  if($response){
    //inspect response
    $responseObj = json_decode($response['body'], false);
    $responseCode = $responseObj->messages[0]->code;
 
    if($responseCode == '0'){
      $responseToken = $responseObj->response->token;
 
      // format json from form data
      $form_array = array('fieldData'=>array());
      foreach( $form_data['fields'] as $field ) {
       // get key/value pairs into an array by themselves
        if($field['key'] != 'submit_button'){
          $form_array['fieldData'][$field['key']] = $field['value'];
        }
      }
      $myJSON_Data = json_encode($form_array);
      
      // insert record
      $myEndpoint = 'fmi/data/v1/databases/' . $myFile . '/layouts/' . $myLayout . '/records';
      $post_url = $myServer . $myEndpoint;
      $headers = array('Authorization' => 'Bearer ' . $responseToken , 'Content-Type' => 'application/json');
      $request = new WP_Http();
      $response = $request->post( $post_url, array( 'method' => 'POST', 'body' => $myJSON_Data, 'headers' => $headers ) );
 
      if($response){
        // ok
      } else {
        // insert err
      }
      // log out
      $myEndpoint = 'fmi/data/v1/databases/' . $myFile . '/sessions/' . $responseToken;
      $post_url = $myServer . $myEndpoint;
      $headers = array('Content-Length' => '0');
      $request = new WP_Http();
      $response = $request->post( $post_url, array( 'method' => 'DELETE', 'headers' => $headers ) );      
    } else {
      // authentication err
    }
  }
}

Enabling Ninja Forms

To use with Ninja Forms, we configure the “Emails & Actions” configuration (see Figure 1) for the form we are working on, enable the “Web Hook,” (see Figure 2) and give it a Name and Hook Tag. The Hook Tag here is important, and it needs to match the action name given in the custom action. In the code above, it is the first parameter of the add_action function, where we name it “fm_WordPress_action”.

Emails & Actions tab for configurating a Ninja Form

Figure 1- Use “Emails & Actions” to configure your form


Use the slide to enable the Web Hook action

Figure 2- Use the slider to enable the “Web Hook” action.

If we break down the above code, we see the performance of two steps. The first is to authenticate to the database and get a token back. Once we have successfully authenticated and have a token, we use that in the header of our HTTP request to submit JSON to the Data API that completes our record creation.

There are RESTful endpoints used to perform both authenticating and record creation. You can find these in the Data API documentation. First, we send credentials using a HTTP header and receive a token upon successfully authenticating to the database.

Once we have a token, we do a bit of cleanup work to get our data out of the form, where we reference the “Field Key” from the form builder, and correctly format the JSON we will submit as the body of our request to create a new record. We define the Field Key for each field in the form (see Figure 3).

Define the Field Key for each field

Figure 3 – Define the Field Key for each field.

Of course, all field keys need to match with the field names in your database. Also, this assumes that you have correctly set up security in your FileMaker file, and have enabled the “fmrest” privilege set for the account used to perform this action (see Figure 4).

Set up security in your FileMaker file to enable the "fmrest" privilege set.

Figure 4 – Set up security in your FileMaker file to enable the “fmrest” privilege set.

You will see the File and Layout specified in the endpoint we reference, so we only then need to include the JSON containing our record data, in addition to passing our authentication token as a header. All this is simple enough, once you have achieved a cursory understanding of REST architecture and how to work with it.

Licensing and Costs

FileMaker Server includes an amount of data transfer at no additional cost. The good news is that the amount already provided — 2GB of data, per user each month — should be more than enough for most every use case. That does not include container data and only counts toward outbound data transfer. Data is also shared for all users.

For example, if you have a FileMaker Server with five licensed users, that would be 10 GB/month, or 120 GB for the year. That far exceeds the amount that most solutions see in data transfer even with FileMaker Pro pushing user interface and containers. If you go beyond this very high threshold, you would likely want to pay additionally for the support to handle that kind of traffic.

Considering the cost of FileMaker Server effectively includes this licensing, I would not hesitate to recommend using the Data API in any new development.

Building on Your FileMaker-WordPress Integration

This is just an example showing a basic integration of a WordPress form used to create a record in your database. You could build on this example to add more robust error handling or additional functionality.

Integrating with FileMaker is easier than ever! Hopefully this article gives you some insight into how you can extend your FileMaker applications in ways previously not conceived.

If you have any questions or need additional help integrating your FileMaker solution with your website, please contact my team. We’d love to see if we’re a good fit for your next project.

References

Mike Duncan

Mike Duncan

Mike is an AWS Certified Solutions Architect as well as a certified FileMaker Developer. In addition to his work, Mike also enjoys pursuing his art, freelance writing, traveling, and spending time with his family.

9 Comments

  • Avatar Jordan says:

    nice work. Would love to see an example using ContactForm 7 … it is by far the most popular contact form plugin.

    • Avatar Mike Duncan says:

      You might be able to by adding an event listener, then the code presented here may be a guide to what the javascript function would look like.

  • Avatar Damien Kelly says:

    Great article, I got it working nicely in FMS17, great share! I did notice it does not work with FMS16, any idea why? Thanks again

    • Avatar Mike Duncan says:

      Hi Damien,
      The Data API in FMS 16 is different than the final release in 17. Considering the version in 16 is a beta, I would focus on the current version. Of course you can use CWP instead of the Data API in previous versions of FMS as well.

  • […] Source: How to Connect FileMaker Data API to a WordPress Website […]

  • Avatar Damien Kelly says:

    Thanks for the reply Mike, made sense when I saw the previous Data API structure.

    Is it possible using this method to feed data into a NinjaForm? I know you can via query string – what about sending in a primary key, and having the NinjaForm extract the data from FileMaker via API and then populate the form?

  • Avatar Malta Code says:

    This is one way, sending data from Ninja forms to a FM Database. What about the other way around, a user logs in a WordPress site and will presented by some FM Data (for instance all their open tickets, orders, invoices, etc.) based on their email or id. How would you suggest this setup?

    • Avatar Mike Duncan says:

      There are several ways to tackle this scenario. One would be to create a custom template and point to some custom PHP to include, then display that in your WP site. This is basically custom web publishing so would require more development, especially if you want to also support the CSS and theming inherited from WordPress, but can be done.

Leave a Reply