<?php
/**
 * Plugin Name: PDB Array Form Element
 * Description: a demonstration of the basic technique for creating a custom form element in Participants Database
 * 
 */

add_filter( 'pdb-set_form_element_types', 'my_array_register_element' );
add_action( 'pdb-form_element_build_array','my_array_element_building_function' );
add_filter( 'pdb-before_display_form_element','my_array_element_value_display_function', 10, 2 );

/**
 * adds the form element to the list of form elements
 * 
 * @param array $elements
 * @return array
 */
function my_array_register_element( $elements )
{
  $elements['array'] = 'List';
  return $elements;
}

/**
 * supplies the form element HTML
 *
 * @param PDb_FormElement object $field
 * @return null
 */
function my_array_element_building_function( $field )
{
  $value = maybe_unserialize( $field->value );
  $field->output = '
<div class="array-element-container">
  <input type="text" name="' . $field->name . '[]" value="' . $value[0] . '" />
  <input type="text" name="' . $field->name . '[]" value="' . $value[1] . '" />
  <input type="text" name="' . $field->name . '[]" value="' . $value[2] . '" />
</div>
';
}

/**
 * shows the value of the array
 *
 * @param bool $value the raw value of the field, this comes in as bool false if it has not 
 *                    been altered, the filter must return bool false if the value is not 
 *                    to be altered by the filter function
 * @param PDb_Field_Item object $field
 * @return string|bool HTML value to display, bool false if unaltered
 */
function my_array_element_value_display_function( $value, $field )
{
  if ( $field->form_element === 'array' ) {
    $value = '<span class="array-element-value">' . implode( ', ', maybe_unserialize( $field->value ) ) . '</span>';
  }
  return $value;
}