Drupal 7 Ajax with tableselect和字段后续更新

时间:2018-05-06 15:20:01

标签: ajax forms drupal-7

我想根据从tableselect字段中选择的模板填充一组表单字段,然后可以根据需要手动修改某些字段。似乎$ form_state ['values']并不反映后面的这些变化。

例如,我在tableselect中选择“Option 2”。文本字段按预期更改为“文本2”。然后我在文本字段中输入更新并点击“提交”。 验证和提交挂钩都接收$ forms_state ['values'] ['text']等于“Text 2”。更改后的文本(“更新”)只能在$ form_state ['input'] ['text']中找到。

见下面的代码。

<?php
function _pilates_test_dropdown_form($form, &$form_state) {
$header = array();
$data = [1 => ["name" => 'option 1', "text" => 'text 1'],
         2 => ["name" => 'option 2', "text" => 'text 2'],
        ];
$header[] = t('Option');
$header[] = t('Text');
$options = array();

foreach ($data as $data_id => $item) {
    if(! isset($initial_option_id)) {
        $initial_option_id = $data_id;
    }
    $options[$data_id] = array();
    $options[$data_id][] = $item['name'];
    $options[$data_id][] = $item['text'];
}

$selected_id = empty($form_state['values']['selected_id']) ? 
        $initial_option_id 
        : 
        $form_state['values']['selected_id'];

$form['selected_id'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#multiple' => FALSE,
  '#default_value' => $selected_id,
    '#ajax' => array(
      'callback' => '_pilates_test_dropdown_ajax_callback',
      'wrapper' => 'item-details-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),  
  );
$form['details'] = array(
       '#type' => 'container',
       '#prefix' => '<div id="item-details-div">',
       '#suffix' => '</div>',);  
$form['details']['text'] = array(
       '#type' => 'textfield',
       '#description' => t('This field value is set after tableselect change.'),
       '#value' => $data[$selected_id]['text'],
    );  
$form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
);  

  return $form;
 }
function _pilates_test_dropdown_form_submit($form, &$form_state) { 
    dpm($form_state);  
}
function _pilates_test_dropdown_form_validate($form, &$form_state) {
  // already failed some checks ?  
  if (form_get_errors()) {
      return; 
  } 
  dpm($form_state);
}
function _pilates_test_dropdown_ajax_callback($form, $form_state) {
 return $form['details'];
}

1 个答案:

答案 0 :(得分:1)

你不应该为这个项目使用#value。试试这个:

$form['details'] = array(
  '#type' => 'container',
  '#prefix' => '<div id="item-details-div">',
  '#suffix' => '</div>',);

$form['details']['text'] = array(
  '#type' => 'textfield',
  '#description' => t('This field value is set after tableselect change.'),
  '#default_value' => $data[$selected_id]['text'],
);

if (!empty($form_state['triggering_element'])) {
  if ($form_state['triggering_element']['#name'] == 'selected_id') {
    $form_state['input']['text'] = $data[$selected_id]['text'];
  }
}