bar
3/22/2016 - 9:48 AM

Checkbox which triggers ajax call Disable options in a form select list

Checkbox which triggers ajax call Disable options in a form select list

<?php 

function module_name_form_alter(&$form, &$form_state, $form_id) {
  $form['text_field_name']['und'][0]['value']['#default_value'] = "Default value";
  //Hide field
  hide($form['text_filed_name']);
  //Create a placeholder fieldset
  $form['placeholder'] = array(
    '#title' => '',
    '#prefix' => '<div id="placeholder">',
    '#suffix' => '</div>',
    '#type' => 'fieldset',
    '#description' => '',
    '#weight' => 2,
  );
  //Create a special ajax checkbox
  $form['ajax_checkbox'] = array(
    '#type' => 'checkbox',
    '#title' => t('Fancy ajax checkbox title'),
    '#weight' => 1,
    '#ajax' => array(
      'callback' => 'ajax_checkbox_callback',
      'wrapper' => 'placeholder',
      'effect' => 'fade',
    ),
  ); 
  //Checking the special ajax checkbox state
  if (!empty($form_state['values']['ajax_checkbox']) 
        && $form_state['values']['ajax_checkbox']) {
    //clear default field value and show the field
    $form['text_field_name']['und'][0]['value']['#default_value'] = "";
    show($form['text_field_name']);
    //move text_field_name to the placeholder
    $form['placeholder']['text_field_name'] = $form['text_field_name'];
    //remove unused field instance form $form variable
    unset($form['text_field_name']);
  }
}
 
/**
 * Callback for the ajax special checkbox
 */
function ajax_checkbox_callback($form, $form_state) {
  return $form['placeholder'];
}

//// ***************************************************************************


function cle_helper_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  // look for the cle submissions views
  if (strpos($form['#id'], 'cle-submissions-page') && isset($form['field_assignment_target_id'])) {
    // pull out the options so we can set new ones
    $options = $form['field_assignment_target_id']['#options'];
    $newoptions = array('All' => t('- Any -'));
    // load the related entities
    $assignments = entity_load('node', array_keys($options));
    // loop through assignment entities to assemble
    foreach ($assignments as $assignment) {
      $disabled = FALSE;
      $name = $assignment->title;
      // see if it is a private submission
      if ($assignment->field_visibility['und'][0]['value'] == 0) {
        $name .= '(' . t('Private') . ')';
        $disabled = TRUE;
      }
      // if it should be disabled then keep it in the list but disable it
      if ($disabled) {
        $key = $name;
        $value = array();
      }
      else {
        $key = $assignment->nid;
        $value = check_plain($name);
      }
      // append our modified (potentially) output to the options
      $newoptions[$key] = $value;
    }
    $form['field_assignment_target_id']['#options'] = $newoptions;
  }
}