RoleForm.php 2.01 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\user;

5
use Drupal\Core\Entity\EntityForm;
6
use Drupal\Core\Form\FormStateInterface;
7 8 9

/**
 * Form controller for the role entity edit forms.
10 11
 *
 * @internal
12
 */
13
class RoleForm extends EntityForm {
14 15 16 17

  /**
   * {@inheritdoc}
   */
18
  public function form(array $form, FormStateInterface $form_state) {
19
    $entity = $this->entity;
20
    $form['label'] = [
21
      '#type' => 'textfield',
22
      '#title' => $this->t('Role name'),
23 24 25 26
      '#default_value' => $entity->label(),
      '#size' => 30,
      '#required' => TRUE,
      '#maxlength' => 64,
27
      '#description' => $this->t('The name for this role. Example: "Moderator", "Editorial board", "Site architect".'),
28 29
    ];
    $form['id'] = [
30 31 32 33 34 35
      '#type' => 'machine_name',
      '#default_value' => $entity->id(),
      '#required' => TRUE,
      '#disabled' => !$entity->isNew(),
      '#size' => 30,
      '#maxlength' => 64,
36
      '#machine_name' => [
37
        'exists' => ['\Drupal\user\Entity\Role', 'load'],
38 39 40
      ],
    ];
    $form['weight'] = [
41
      '#type' => 'value',
42
      '#value' => $entity->getWeight(),
43
    ];
44 45 46 47 48 49 50

    return parent::form($form, $form_state, $entity);
  }

  /**
   * {@inheritdoc}
   */
51
  public function save(array $form, FormStateInterface $form_state) {
52 53 54 55
    $entity = $this->entity;

    // Prevent leading and trailing spaces in role names.
    $entity->set('label', trim($entity->label()));
56 57
    $status = $entity->save();

58
    $edit_link = $this->entity->link($this->t('Edit'));
59
    if ($status == SAVED_UPDATED) {
60 61
      drupal_set_message($this->t('Role %label has been updated.', ['%label' => $entity->label()]));
      $this->logger('user')->notice('Role %label has been updated.', ['%label' => $entity->label(), 'link' => $edit_link]);
62 63
    }
    else {
64 65
      drupal_set_message($this->t('Role %label has been added.', ['%label' => $entity->label()]));
      $this->logger('user')->notice('Role %label has been added.', ['%label' => $entity->label(), 'link' => $edit_link]);
66
    }
67
    $form_state->setRedirect('entity.user_role.collection');
68 69 70
  }

}