我的模块有一个自定义视图风格插件。在样式设置表单中,我希望实现ajax回调,如以下所述:https://www.drupal.org/docs/8/api/javascript-api/ajax-forms
然而,我没有任何运气。我可以得到旋转的效果,但之后什么都不会发生。下面是我尝试过的一个例子:
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
public function TestCallback(array $form, FormStateInterface $form_state) {
$ajax_response = new AjaxResponse();
$text = 'Text to see if this is working';
$ajax_response->addCommand(new HtmlCommand('#foo', $text));
return $ajax_response;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['test'] = [
'#title' => t('TEST!'),
'#type' => 'select',
'#options' => [
'' => t('None'),
'foo' => t('Bar'),
],
'#ajax' => [
'event' => 'change',
'callback' => '::TestCallback',
// having the line below uncommented seems to help
//'url' => views_ui_build_form_url($form_state),
],
'#prefix' => '',
'#default_value' => '',
];
}如果取消注释“url”,将得到以下错误:
Uncaught TypeError: Cannot read property 'settings' of undefined
at resetSize (:34:32)
at later (debounce.js?v=8.6.3:20)如果我继续评论的话,我会得到:
Failed to load resource: the server responded with a status of 500 ()
/admin/structure/views/ajax/display/view_name/page_1/style_options?
_wrapper_format=drupal_ajax&ajax_form=1&_wrapper_format=drupal_ajax:1
Uncaught Drupal.AjaxError
ajax.js?v=8.6.3:500缺少和/或不正确的是什么?
发布于 2019-01-23 19:11:53
据我所知,看到AJAX文档,我认为您不应该返回一个AjaxResponse对象。您应该从Ajax回调返回一个可呈现的数组。
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['test'] = [
'#title' => t('TEST!'),
'#type' => 'select',
'#options' => [
'' => t('None'),
'foo' => t('Bar'),
],
'#ajax' => [
'event' => 'change',
'wrapper' => 'ajax-output-container',
// Since views style options forms are complex, they're built by
// Drupal in a different way. To bypass this problem we need to
// provide the full path to the Ajax callback.
'callback' => __CLASS__ . '::testCallback',
],
'#prefix' => '',
'#default_value' => '',
];
}
/**
* This is the AJAX callback.
*
* It generates the output for the AJAX request. The output REPLACES
* the "wrapper" you define in #ajax.
*/
public function testCallback(array $form, FormStateInterface $form_state) {
// This element will replace the DIV#foo you have in your #prefix.
$elem = [
'#type' => 'markup',
'#markup' => 'Is it not working!>',
];
return $elem;
}#prefix标记中删除,那么尝试在表单中插入一个单独的项目,并使用#markup。发布于 2019-01-26 02:29:39
$route_name = "views_ui.form_{$form_key}";可能是问题所在。
尝试在views_ui_build_form_url($form_state)->toString();函数下面打印这个结果,看看是否是问题所在: buildOptionsForm
如果保留注释,则会发生错误,因为它们不是ajax所需的url或“#包装器”。
在这里,您可以更深入地研究这个错误:https://api.drupal.org/api/drupal/core%21modules%21views_ui%21 admin.inc/函数/视图_用户界面_构建_表格_url/8.2.x
发布于 2019-01-26 23:43:06
我认为您可能会遇到一个与这个Drupal核心问题相关的问题。请参阅有关实现工作的发行评论和这一个。
https://drupal.stackexchange.com/questions/275397
复制相似问题