Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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
Comment #2
barthje CreditAttribution: barthje commentedComment #3
Steven Buteneers CreditAttribution: Steven Buteneers commentedExperiencing 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.
Comment #4
volegerBe sure that your object in callable array use
DependencySerializationTrait
.This trait handles serialization of used services, so your ajax calls shouldn't fail anymore.
Comment #5
barthje CreditAttribution: barthje commentedYou are right, that was the problem.