Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Drupal\convoca_user\Form;
- use Drupal\Core\Form\FormBase;
- use Drupal\Core\Form\FormStateInterface;
- class UserForm extends FormBase {
- /**
- * {@inheritdoc}
- */
- public function getFormId() {
- return 'form_custom_user';
- }
- public function buildForm(array $form, FormStateInterface $form_state) {
- $form['name'] = array(
- '#type' => 'textfield',
- '#title' => t('Name:'),
- '#required' => TRUE,
- );
- $form['mail'] = array(
- '#type' => 'email',
- '#title' => t('Email:'),
- '#required' => TRUE,
- );
- $form['password'] = array(
- '#type' => 'password',
- '#title' => t('Password:'),
- '#required' => TRUE,
- );
- $form['actions']['submit'] = array(
- '#type' => 'submit',
- '#value' => $this->t('Save'),
- '#button_type' => 'primary',
- );
- return $form;
- }
- public function validateForm(array &$form, FormStateInterface $form_state) {
- if (strlen($form_state->getValue('password')) < 10) {
- $form_state->setErrorByName('password', $this->t('This password is very short'));
- }
- }
- public function submitForm(array &$form, FormStateInterface $form_state) {
- $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
- $user = \Drupal\user\Entity\User::create();
- /*
- The Basics options for creation custom user.
- @TODO is the best way for get value and save user?
- */
- $user->setUsername($form_state->getValue('name'));
- $user->setEmail($form_state->getValue('mail'));
- $user->setPassword($form_state->getValue('password'));
- $user->enforceIsNew(); // Set this to FALSE if you want to edit (resave) an existing user object
- $user->activate(); // Is for active my user, there is more options, but these are the basics
- $user->save();
- foreach ($form_state->getValues() as $key => $value) {
- drupal_set_message($key . ': ' . $value); // Print values
- }
- }
- }
Add Comment
Please, Sign In to add comment