1

I am trying to transition a state_machine field on the User entity during an event. What I have thus far is:

/* @var \Drupal\user\Entity\User $user */
$user = User::load($id);

/* @var \Drupal\Core\Field\FieldItemListInterface $state_field */
$state_field = $user->get('field_screening_status');

/* @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state */
$state = $state_field->get(0);

$transitions = $state->getTransitions();

$state->applyTransition($transitions['mark_needs_screening']);

Of course, this does not actually save it to the user. I would actually need to call:

$user->set('field_screening_status', 'needs_screening');
$user->save();

But, how might I instead use the state_machine API to apply the transition to a user field?

1 Answer 1

1

Here's what I ended up with. Would be curious if the community has a better solution.

/* @var \Drupal\user\Entity\User $user */
$user = User::load(\Drupal::currentUser());

/* @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state */
$state = $user->get('field_screening_status')->get(0);

$transitions = $state->getTransitions();

if (array_key_exists('mark_needs_screening', $transitions)) {
  $user->set('field_screening_status', 'needs_screening');
  $user->save();
}

UPDATE: Thanks to @lisastreeter in #commerce on drupal.slack.com

$user = User::load($id);
$state = $user->get('field_screening_status')->first();
$transition = $state->getWorkflow()->getTransition('mark_needs_screening');

if ($transition) {
  $state->applyTransition($transition);
}

Not sure if that get(0) change to first() really made the difference, but it works now.

Your Answer

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

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