0

I'm running Drupal 8.8.x

The Problem

Entity is not being saved when form is submitted through AJAX. Example:

Build Form

public function buildForm(array $form, FormStateInterface $form_state, EntityInterface $entity = NULL) {
  if($entity) {
    $this->entity = $entity;


    $form['element'] = [
      '#type' => 'textfield',
      '#title' => $this->t('My title'),
      '#name' => 'element',
      '#ajax' => [
         'event' => 'focusout',
         'callback' => [$this, 'myCallback'],
         'disable-refocus' => TRUE
      ]
    ];
  }

  return $form;
}

Submit Form

public function submitForm(array &$form, FormStateInterface $form_state) {
 $element = $form_state->getTriggeringElement()['#name'];
 $value = $form_state->getValue($element);

 $this->entity->set($element, $value);
 $this->entity->save();
}

I've confirmed $element and $value are the correct key and value. However, when I save the entity nothing happens. There is nothing updated in the database. And there are no errors emitted in the console or watchdog.

If anyone knows what could be the issue I'd appreciate some insight! :)

0
1

Drupal 8 doesn't cache Ajax forms anymore, so you can't get properties of the form object set in the initial form build. see Bypass form caching by default for forms using #ajax.

Forms are only cached as rendered form. Put the entity id in a hidden form element to load the entity before saving. Add the entity cache tag to the form if you use default values from the entity.

Or consider to switch from a general Form API form to an entity form.

1
  • You’re such a champ in caching! "Should I blame caching?", "Yes, but 4k4 has the answer!" ;)
    – user72672
    Jan 11 '20 at 22:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.