Filling eForm report dynamically in MODX Evo

What to do when we want our form to be dynamic?

eForm function that you will find below, was a life saver for me not so long ago.

eForm is one of MODX most popular snippet. It is responsible for generating and processing forms in MODX Evo. It works like a charm with static form like those used for contact/feedback/booking.

But hey, what to do when our form is going to be generated dynamic withe use of for example Ditto? Sometimes it will have more sometimes less fields or different field names or we will want to exclude empty fields from report. What to do when we want our form to be dynamic?

In MODX almost everything is possible so relax. eForm is very flexible and its maker was aware of our future needs ;) Thats why he included events linked to custom PHP containing anything we want. That is what we are going to use now.

1. Let's create our custom function

First step is to create snippet (named it eFormFunctions) that will contain function, which will scan through submited form, retrieve field names with it's values, and at the end it will create new variable with whole new dynamic form content for report. We are going to use this variable as a placeholder inside a chunk that will be our form report template.

// by
function populate_report( &$fields ){

  $output = '<table border="1">';

  foreach ($fields as $key => $value) {
  // remove empty and unnecesary fields from report
    if($value!='' && $key!='postdate' && $key!='formid' && $key!='submit'){
      $output .= '<tr valign="top"><td>'.$key.'</td><td>'.$value.'</td></tr>';

  $output .= '</table>';

  $fields['dynamicFields'] = $output;

  return true;


2. eForm parameter

We can say that hard part is behind us. Now, we have to run our snippet (eFormFunctions) in place where we run eForm.

[ ! eFormFunctions ! ]
[ ! eForm ! ]

There should be typical eForm parameters above ofcours. Additionaly we have to add parameter which is responsible for running our new function before submiting our form. Parameter is called &eFormOnBeforeMailSent and in our case its value should be populate_report.

[ ! eFormFunctions ! ]
[ ! eForm? &eFormOnBeforeMailSent=`populate_report` ! ]

3. Report template

The only thing we need to put in our report template is placeholder [ + dynamicFields + ] and that is all. From now on our form report is going to be generated dynamically :) It is possible to extend this method, so it will get MODX documents names with specified IDs when running. "What for?" you may ask. For example you can use it for products order form :)

Tags: code, eform, evo, modx, php, snippet