Thursday 7 July 2016

Drupal 7 - Some useful FormAPI notes

Here's some instruction on how to make a Basic Form with a Menu Link -
https://www.drupal.org/node/1419390

Attached is a basic Hello World version demonstrating this .

How to use Ajax to display, hide or change Fields.

Say for example you have a drop down selection and you'd like it so that a choice here effects the next selections that you may take.

What you need to do is add an 'Ajax Event' to the form field . Take this for an example


$form['shop_select'] = array(
  '#type' => 'select',
  '#title' => t('Selected'),
  '#options' => array(
    0 => t('Fruit'),
    1 => t('Veg'),
  ),
  '#ajax' => array(
    'event' => 'change',
    'wrapper' => 'type-wrapper',
    'callback' => 'type_ajax_callback',
    'method' => 'replace',
  ),
  '#default_value' => 0,
  '#description' => t('Select what your looking for.'),
);


This will be added to the form in hook_form or hook_form_alter .

Following this we'll no need to set up the wrapper that's being called in '#ajax' . Note: make sure this is an 'id' in the div. Using 'class' will not work .

$form['type-wrapper'] = array('#prefix' => '
', '#suffix' => '
');

After this , still in hook_form you can write the code that will change the form to how you want it on the conditions you want. First off I'm checking what the current value in the first dropdown is

$shop_select = isset($form_state['values']['shop_select']) ? $form_state['values']['shop_select'] : 0;

I've made the default here '0' . Next I add another dropdown depending on that result.
switch ($shop_select) {
  case 0:
    // Set default options.
    $form['type-wrapper']['sizes'] = array(
      '#type' => 'select',
      '#title' => t('Sizes'),
      '#options' => array(
        0 => t('Size 1'),
        1 => t('Size 2'),
      ),
    );
    break;
  case 1:
    // Set up case 2
    $form['type-wrapper']['sizes'] = array(
      '#type' => 'select',
      '#title' => t('Sizes'),
      '#options' => array(
        2 => t('Size 3'),
        3 => t('Size 4'),
      ),
    );
    break;
}

Lastly in the 'ajax' call we set up a callback function. We use this to tell our code to only refresh that part of the form that we want it to

function sizes_ajax_callback($form, $form_state) {
   return $form['type-wrapper'];
}

No comments: