有一个ajax回调函数,其中根据表单字段的自定义输入动态生成数据。
//ajax callback submit
$form['action'] = [
'#type' => 'button',
'#value' => $this->t('Submit'),
'#ajax' => [
'callback' => '::getData',
'wrapper' => 'table-data',
'method' => 'replaceWith',
'effect' => 'fade',
];
//ajax callback function
public function getData($form, FormStateInterface &$form_state) {
$table_data = $this->getTableData($form_state); //getting the data dynamically
$form['section']['#attached']['drupalSettings']['table_data'] = $table_data; //assigning the data to drupalSettings
dpm($table_data); //to check if the assignment is updated
return array($form['table_markup'],$form['section']); //$form['table_markup'] is a markup used to display data in the table
}
//javascript code
(function ($, Drupal, drupalSettings) {
Drupal.behaviors.display_data = {
attach: function (context, settings) {
alert(drupalSettings.table_data);
var table_data = drupalSettings.table_data; //inconsistency noticed in this assignment
}
};
})(jQuery, Drupal, drupalSettings);
现在,每当我单击submit按钮时,$table_data就会被动态更新并分配给drupalSettings,但是将其值传递给javascript似乎是不一致的,这意味着javascript中的drupalSettings.table_data没有得到更新,而是显示了前面的设置值。
要使它正常工作,我必须重新加载页面,更改表单输入并提交。
我已经意识到它可能与缓存有关,并试图通过如下设置routing.yml文件来避免它:
options:
no_cache: 'TRUE'
这里不确定如何使用缓存标记,因为我没有定义任何标记试图在回调中重建表单,而回调也不起作用。表单输入字段即使在重新加载页面之后也不会被清除,我很困惑为什么即使在no_cache设置为true之后也会发生这种情况呢?
尝试在javascript上使用“delete”,这也不起作用
是否有适当的方法确保在javascript上接收到的来自drupal的变量总是更新的变量?
发布于 2018-07-05 22:30:33
在这种情况下,您的AJAX回调方法需要返回一个AjaxResponse对象(见API文档),而不是返回HTML (也就是表单呈现数组)。AjaxResponse对象应该包含至少两个命令,一个用于更新HTML (处理后的表单),另一个用于更新drupalSettings对象。一个可能的反应可能是
public static function ajaxCallback(array $form, FormStateInterface $form_state) {
// Assuming the $form variable is either the updated render array or rendered output.
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#wrapper-id', $form));
// The $data variable is an assoc array with he same keys you passed during the build under #attached key.
// If you don't want to merge the settings but instead replace it, remove the second argument.
$response->addCommand(new SettingsCommand ($data, TRUE));
return $response;
}
https://drupal.stackexchange.com/questions/264324
复制