0
我需要从JavaScript传递一个值到我的drupal 8表单。如何将JavaScript的值传递给Drupal 8表单?
我在窗体中添加了一个隐藏字段。 Javascript正在计算一个值并将其写入该字段。但是我怎样才能得到函数submitForm()中的值呢?
即使正确的方法使用隐藏字段?如果是这样,我需要做些什么来完成这项工作?
我已经删除了大部分代码以提高可读性。
FooForm.php:
class FooForm extends FormBase
{
public function getFormId()
{
return 'fooID';
}
public function buildForm(array $form, FormStateInterface $form_state)
{
//...here are lot's of elements not relevant right now
$form['myhiddenfield'] = ['#type' => 'hidden'];//adding hidden field.
$form['#attached']['library'][] = 'foo/foocalculator';
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state)
{
dpm($form_state->getValues()['myhiddenfield']);//not getting the calculated value.
}
foocalculator.js:
(function ($, Drupal) {
passToDrupal = $('#myhiddenfield');
$('#edit-submit--3').click(function (event) {
calcRoute(address, $editparcel.fieldValue().toString())
});
})(jQuery, Drupal);
function calcRoute(start, destination) {
var request = {
origin: start,
destination: destination,
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
mydistance = result.routes[0].legs[0].distance.value;
passToDrupal.val(mydistance);//adds value to hidden field.
}
});
}
我花了最近几个小时玩弄了将数据存储在_SESSION和\ Drupal :: service('user.private_tempstore')中,只想放弃。但是,这工作。非常感谢你。 –