Last active
January 21, 2021 17:12
-
-
Save mharmuth/0ab021d5b65e4cab7c6efec951fc59e9 to your computer and use it in GitHub Desktop.
Custom Webform Handler for Drupal 8 Webform module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
Thank you very much for the example btw :)