Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom Webform Handler for Drupal 8 Webform module
<?php
namespace Drupal\your_custom_module\Plugin\WebformHandler;
use Drupal\user\Entity\User;
/**
* Create a new user entity from a webform submission.
*
* @WebformHandler(
* id = "create_user",
* label = @Translation("Create User"),
* category = @Translation("Entity creation"),
* description = @Translation("Creates a new drupal user."),
* cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
* results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
* )
*/
class RegisterFacilityHandler extends WebformHandlerBase
{
/**
* {@inheritdoc}
*/
public function postSave(
WebformSubmissionInterface $webformSubmission,
$update = true
) {
$user = $this->createUser($webformSubmission);
// do something with $user
}
/**
* Create user.
*
* @param WebformSubmissionInterface $webformSubmission
*
* @return User
*/
protected function createUser(WebformSubmissionInterface $webformSubmission): User
{
$email = $webformSubmission->getData('email');
/** @var User $user */
$user = User::create();
// madatory fields
$user->setPassword($webformSubmission->getData('password'));
$user->setEmail($email);
$user->setUsername($webformSubmission->getData('username'));
$user->addRole('user');
$user->enforceIsNew();
// optional fields
$user->set('init', $email);
$user->set('langcode', 'en');
$user->set('preferred_langcode', 'en');
$user->set('preferred_admin_langcode', 'en');
$user->save();
return $user;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.