1

I'm trying to create a form that will allow a user to select a View from a list and then display that View on the same page. For instance:

$options = array();
$options['view_one'] = 'view_one';
$options['view_two'] = 'view_two';
$options['view_three'] = 'view_three';

$form['chooseview']=array(
    '#title'=>'Choose a View',
    '#description'=>'Which View do you want to display?',
    '#type'=>'select',
    '#name'=>'chooseview',
    '#required'=>TRUE,
    '#options' => $options,
    );

print views_embed_view($form_state['values']['chooseview'],'block_1');

My question is how do I accomplish this? Drupal is not printing the embedded View from form_submit. I don't need Ajax.

2

Method #1: (No subit button, requires JS, loads all views at once but shows conditionally)

<?php 
function MYMODULE_my_custom_form($form, &$form_state) {
  $options = array();
  $options['view_one'] = 'view_one';
  $options['view_two'] = 'view_two';
  $options['view_three'] = 'view_three';

  $form['chooseview']=array(
    '#title' => t('Choose a View'),
    '#description' => t('Which View do you want to display?'),
    '#type' => 'select',
    '#name' => 'chooseview',
    '#required' => TRUE,
    '#options' => $options,
  );
  foreach ($options as $view_name) {
    $form['display'][$view_name] = array(
      '#type' => 'markup', // Not necessary - just to be clear. 
      '#markup' => views_embed_view($view_name, 'block_1'),
      '#states' => array(
        'visible' => array(
          ':input[name="chooseview"]' => array('value' => $view_name),
        ),
      ),
    );
  }
  return $form;
?>

(short, eh)

Method #2: (Submit button, JS-independent, loads only view when necessary) Note we pass $form_state to the form builder function by reference.

<?php 
function MYMODULE_my_custom_form($form, &$form_state) {
  $options = array();
  $options['view_one'] = 'view_one';
  $options['view_two'] = 'view_two';
  $options['view_three'] = 'view_three';

  $form['chooseview']=array(
    '#title' => t('Choose a View'),
    '#description' => t('Which View do you want to display?'),
    '#type' => 'select',
    '#name' => 'chooseview',
    '#required' => TRUE,
    '#options' => $options,
  );
  $form['show_me'] = array(
    '#type' => 'submit',
    '#value' => t('Show me, please!'),
  );
  if (!empty($form_state['values']['chooseview'])) {
    $form['display'][$view_name] = array(
      '#type' => 'markup', // Not necessary - just to be clear. 
      '#markup' => views_embed_view($form_state['values']['chooseview'], 'block_1'),
    );
  }
}

function MYMODULE_my_custom_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}
?>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.