1

I have a Drupal 8 form with several fields that update a price via Ajax.

One of the fields is failing to a textbox, that does a callback on the blur event. It looks like this:

$form['free_amount'] = array(
  '#type' => 'number',
  '#title' => $config->get('add_on_free.label'),
  '#description' => $config->get('add_on_free.description'),
  '#default_value' => '0',
  '#min' => 0,
  '#ajax' => array(
    'callback' => $callback,
    'event' => 'blur',
    'target' => $id,
  ),
);

$form['payment']['price']['total_price'] = array(
  '#prefix' => '<div id="totalPrice">',
  '#suffix' => '</div>',
  '#markup' => $this->t('Total amount to pay: @symbol@total', 
               ['@symbol' => $symbol, '@total' => $totalPrice]),
);

The ajax callback looks like this:

public function updateMemberPriceCallback(array $form, FormStateInterface $form_state) {
  $ajax_response = new AjaxResponse();
  $ajax_response->addCommand(new HtmlCommand('#Pricing', $form['payment']['price']));

  return $ajax_response;
}

The problem I'm having is that sometimes when the form submits, the free_amount field has no value. It doesn't always happen, and I haven't figured out a pattern that causes it. I thought it might be if the blur event didn't occur before submitting the form, but that doesn't seem to be it. I can't see a clear pattern to when it occurs.

If I take the Ajax update off the field, it always submits correctly, but the total doesn't update before the form submits.

Is there a way I can make this work reliably?

Thanks for your help,

James

2
  • What free amount field?
    – Jaypan
    Apr 18, 2017 at 23:07
  • Perhaps this maybe causing your empty field bug: '#default_value' => '0',. Currently your default value is of type string '0', since this is a number field, it should just be type integer 0, without the string quotes ''. So make it '#default_value' => 0,
    – No Sssweat
    Apr 19, 2017 at 0:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.