我在使用 Drupal 和 AJAX 时遇到一个问题,其中某个字段在启用时不会更新其值,但在禁用时却可以工作。
function my_module_form_node_event_video_edit_form_alter(&$form, FormStateInterface $form_state) {
add_video_ajax($form, $form_state);
}
function add_video_ajax(&$form, &$form_state) {
// add ajax callback to Video ID field
$form['field_video_id'] ['widget'] [0]['value']['#ajax'] = [
'callback' => 'ajax_callback',
'event' => 'change',
'wrapper' => 'replace-container',
];
$form['field_aspect_ratio'][ '#prefix'] = '<div id="replace-container">';
$form['field_aspect_ratio'][ '#suffix'] = '</div>';
$value = $form_state->getValue('field_video_id');
$value = isset($value[0]) ? $value[0]['value']: NULL;
if($value){
$form['field_aspect_ratio'] ['widget']['#default_value'] = $value;
}
}
function ajax_callback($form, $form_state) {
$response = new AjaxResponse();
$response->addCommand(
new ReplaceCommand( '#replace-container', $form['field_aspect_ratio'])
);
return $response;
}
此代码不起作用,因为更新字段未禁用。我想要不禁用($form['field_aspect_ratio']['#disabled'] = true;)此代码工作,因为我想允许用户手动选择此字段下拉列表。
如果不可能,我计划使用另一种方式
function ajax_callback($form, $form_state) {
$response = new AjaxResponse();
$response->addCommand(
new InvokeCommand( 'selector', 'method', 'arguments')
);
return $response;
}
//js
$.fn.method = function(data) {
//will work here
});