BakeryPullForm.php in Bakery Single Sign-On System 8.2
File
src/Forms/BakeryPullForm.php
View source
<?php
namespace Drupal\bakery\Forms;
use Drupal\bakery\BakeryService;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class BakeryPullForm extends FormBase implements ContainerInjectionInterface {
private $service;
public function __construct(BakeryService $service) {
$this->service = $service;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('bakery.bakery_service'));
}
public function getFormId() {
return 'bakery_forms_pull_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['or_email'] = [
'#type' => 'radios',
'#options' => [
0 => t('Username'),
1 => t('Username or email'),
],
'#default_value' => 0,
];
$form['name'] = [
'#type' => 'textfield',
'#required' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Request account'),
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$existing_account = user_load_by_name($form_state
->getValue('name'));
if (!$existing_account && $form_state
->getValue('or_email')) {
$existing_account = user_load_by_mail($form_state
->getValue('name'));
}
if ($existing_account) {
$form_state
->setError($form['name'], $this
->t('Account @link exists.', [
'@link' => $existing_account
->toLink($existing_account
->getAccountName()),
]));
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$result = $this->service
->requestAccount($form_state
->getValue('name'), $form_state
->getValue('or_email'));
if ($result === FALSE) {
$this
->messenger()
->addError($this
->t("Pulling account %name failed: maybe there is a typo or they don't exist on the master site.", [
'%name' => $form_state
->getValue('name'),
]));
}
else {
$form_state
->setRedirect('user', [
'id' => $result,
]);
}
}
}