1

I have a block, of which I want to update the contents via AJAX. So the block is:

$block['subject'] = t('My Block');
$block['content'] = '<div id="block_wrapper"></div>';

And the form element AJAX part:

$form['select_element']['#ajax'] = array(
  'callback' => 'ajax_callback',
  'wrapper' => 'block_wrapper',
  'method' => 'replace',
);

The callback:

function ajax_callback($form, $form_state) {
  return views_embed_view('view_name', 'default', $form_state['values']['select_element']);
}

However when I change the form element the whole block content is replaced and the wrapper is replaced by a empty div, so subsequent alterations of the select element fail to update the block.

The wrapper documentation explains the entire div is replaced, not just it contents. But many modules (like for example Views) have dynamically updating form elements where changing a select element toggles other parts of a form, which keeps working no matter how often you change it. Do they insert the wrapper div again in the response? And how should I alter the response of views_embed_view to put the contents in a wrapper div?

| improve this question | | | | |
4

Thanks @Tasneem for directing me. I did it as follows:

function hook_form() {
  $form['select_element'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $default,
    '#ajax' => array(
      'callback' => 'ajax_callback',
      'wrapper' => 'block_wrapper',
      'method' => 'replace',
    ),
  );

  $form['block_wrapper'] = array(
    '#type' => 'item',
    '#title' => t('Contents'),
    '#id' => 'block_wrapper',
    '#markup' => views_embed_view(...),
  );

  return $form;
}


function ajax_callback($form, $form_state) {
  $form['block_wrapper'] = array(
    '#type' => 'item',
    '#title' => t('Contents'),
    '#id' => 'block_wrapper',
    '#markup' => views_embed_view(...),
  );

  // Returning the entire $form here made the select element appear twice, so only return the wrapper element.
  return $form['block_wrapper'];
}
| improve this answer | | | | |
3

I think you must to create block_wrapper in the $form before ajax as a container :

$form['select_element']['block_wrapper'] = array(
'#type' => 'container',
'#id' => 'block_wrapper',
'#attributes' => array(
  'class' => array('myclass')
  ),
);

to make ajax wrapper found it.

| improve this answer | | | | |
  • The problem is that the div with the id is replaced by the AJAX call, so no matter in what way I add it, it will be replaced. – Neograph734 May 17 '15 at 11:49
  • 1
    try to put view directily in the form in callback funtion not return .. or remove method => 'replace' – Tasneem May 17 '15 at 12:01

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.