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')中,只想放棄。但是,這工作。非常感謝你。 –