Dynamic form fields

3 posts by 2 authors in: Forums > CMS Builder
Last Post: November 6, 2018   (RSS)

By daniel - November 6, 2018 - edited: November 6, 2018

Hi Jerry,

I can think of a couple ways this could be done; it's a bit more complex than what I can fully walk you through on the forum, but I'll try to give you some ideas/somewhere to start at least.

One of the simpler methods to do this would be by encoding all of the data into a single value, which means that you can save a dynamic number of records to a single field. This can be done by passing an array of information into json_encode(). So, assuming you've done something like in that YouTube tutorial and you've named the inputs member_name[] and member_description[], it could look something like this:

  ...

  $member_data         = array();
  $member_names        = isset( $_REQUEST['member_name'] )        ? $_REQUEST['member_name']        : array();
  $member_descriptions = isset( $_REQUEST['member_description'] ) ? $_REQUEST['member_description'] : array();
  
  if (!empty( $member_names ) && !empty( $member_descriptions )) {
    foreach ($member_names as $key => $name) {
      $member_data[] = array(
        'name'        => $name,
        'description' => $member_descriptions[ $key ],
      );
    }
  
    $member_data_json = json_encode( $member_data );
    $colsToValues['member_data'] = $member_data_json;
  }
  
  ...

You could then use json_decode() to reverse the process and obtain an array of the data. It would be up to you to determine how you need to use that data, but here's an example of how it could be output in a list.

<?php
  $member_data = json_decode($exampleRecord['member_data'], true);
  foreach ($member_data as $member) {
    echo 'Name: ' . $member['name'] . '<br>';
    echo 'Description: ' . $member['description'] . '<br>';
    echo '<hr>';
  }
?>

The downside to this method is that it makes it difficult to directly view/edit the data through the CMSB back-end, as it would only be visible as the encoded data there.

Another idea could be to create a separate CMSB section for this member data and create a new record for each name/description pair, using an "ownerNum" field (or similar) to keep track of which user they belong to. This provides a better interface for accessing the data through CMSB but requires quite a bit more work to set up, especially when trying to update/delete any of the records.

Let me know if you have any questions!

Thanks,

Daniel
Technical Lead
interactivetools.com

Oh, I'm sure that there will be questions.

One of the fields will be an image, so I'll probably need to go with the more complex route

I'll tackle this over the next week or so.

Thanks for the head start

Jerry Kornbluth

.

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php