daily pastebin goal
79%
SHARE
TWEET

Untitled

a guest Apr 27th, 2018 135 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. namespace Drupal\convoca_user\Form;
  4. use Drupal\Core\Form\FormBase;
  5. use Drupal\Core\Form\FormStateInterface;
  6.  
  7. class UserForm extends FormBase {
  8.     /**
  9.      * {@inheritdoc}
  10.      */
  11.     public function getFormId() {
  12.         return 'form_custom_user';
  13.     }
  14.  
  15.     public function buildForm(array $form, FormStateInterface $form_state) {
  16.         $form['name'] = array(
  17.             '#type' => 'textfield',
  18.             '#title' => t('Name:'),
  19.             '#required' => TRUE,
  20.         );
  21.         $form['mail'] = array(
  22.             '#type' => 'email',
  23.             '#title' => t('Email:'),
  24.             '#required' => TRUE,
  25.         );
  26.         $form['password'] = array(
  27.             '#type' => 'password',
  28.             '#title' => t('Password:'),
  29.             '#required' => TRUE,
  30.         );
  31.         $form['actions']['submit'] = array(
  32.             '#type' => 'submit',
  33.             '#value' => $this->t('Save'),
  34.             '#button_type' => 'primary',
  35.         );
  36.         return $form;
  37.     }
  38.  
  39.     public function validateForm(array &$form, FormStateInterface $form_state) {
  40.         if (strlen($form_state->getValue('password')) < 10) {
  41.             $form_state->setErrorByName('password', $this->t('This password is very short'));
  42.         }
  43.     }
  44.  
  45.     public function submitForm(array &$form, FormStateInterface $form_state) {
  46.         $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
  47.         $user = \Drupal\user\Entity\User::create();
  48.  
  49.         /*
  50.          The Basics options for creation custom user.
  51.          @TODO is the best way for get value and save user?
  52.         */
  53.         $user->setUsername($form_state->getValue('name'));
  54.         $user->setEmail($form_state->getValue('mail'));
  55.         $user->setPassword($form_state->getValue('password'));
  56.         $user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object
  57.         $user->activate(); // Is for active my user, there is more options, but these are the basics
  58.         $user->save();
  59.         foreach ($form_state->getValues() as $key => $value) {
  60.             drupal_set_message($key . ': ' . $value); // Print values
  61.         }
  62.     }
  63. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top