Problem/Motivation

When you add an #ajax callback to a FieldWidget it will lose the properties that you set in __construct during submit.

E.g.

public function __construct() {
$this->testProperty = 'test property';
}
$widget['widget']['#ajax'] = [
      'callback' => array($this, 'changeSelectedRoles'),
      'event' => 'change',
      'progress' => array(
        'type' => 'throbber',
        'message' => t('Change selected roles...'),
      ),
    ];

When you submit the form without triggering the ajax callback it will show $this->testProperty as 'test property''.
When you submit the form with triggering the ajax callback it will show $this->testProperty as NULL.

Comments

barthje created an issue. See original summary.

barthje’s picture

Title: Add an #ajax callback to a FieldWidget and triggering it it will lose the properties set in __construct » Add an #ajax callback to a FieldWidget and triggering it it will lose the properties set in __construct during submit
Issue summary: View changes
Steven Buteneers’s picture

Experiencing the same problem in a ContentEntityForm. When the ajax callback is triggered on the change event, the form is rebuild via AJAX and the injected service('s) are NULL.

voleger’s picture

Be sure that your object in callable array use DependencySerializationTrait.
This trait handles serialization of used services, so your ajax calls shouldn't fail anymore.

barthje’s picture

Status: Active » Closed (works as designed)

You are right, that was the problem.