<?

/**
* Implements hook_form_alter to add a delete button for flexifield entries
*/
function flexifield_delete_form_alter(&$form, &$form_state, $form_id){
  $flexifield_exists = false;
  foreach($form['#field_info'] as &$fields) {
    if(is_array($fields) && $fields['type'] == 'flexifield' && is_array($form[$fields['field_name']]))
    {
     $flexifield_exists = true;
     foreach ($form[$fields['field_name']] as $key => &$flex) {
       if (is_array($flex) && isset($flex['#default_value']['item_id'])) {
         $flex['delete'] = array(
           '#type' => 'checkbox',
           '#title' => t('Remove Item'),
           '#weight' => 50
         );
       }
     }
    
    }
  }
  if($flexifield_exists && !in_array('_flexifield_delete_flex_node_form_submit')){
     array_push($form['#submit'], '_flexifield_delete_flex_node_form_submit'); // only need this submit handler once
  }
}

/**
* Delete any field_flex where the delete checkbox is checked, this works if javascript is off
*/
function _flexifield_delete_flex_node_form_submit(&$form, &$form_state){

  foreach($form['#field_info'] as &$fields) {
    if(is_array($fields) && $fields['type'] == 'flexifield')
    {
      foreach($form_state['values'][$fields['field_name']] as $id => $item){
        if($item['delete'] == 1){
          unset($form_state['values'][$fields['field_name']][$id]);
        }
      }
      
    }
  }
}