You are here

class GroupTypeForm in Group 2.0.x

Same name and namespace in other branches
  1. 8 src/Entity/Form/GroupTypeForm.php \Drupal\group\Entity\Form\GroupTypeForm

Form controller for group type forms.

Hierarchy

Expanded class hierarchy of GroupTypeForm

File

src/Entity/Form/GroupTypeForm.php, line 15

Namespace

Drupal\group\Entity\Form
View source
class GroupTypeForm extends BundleEntityFormBase {

  /**
   * The entity field manager service.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * Constructs a new GroupTypeForm.
   *
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager service.
   */
  public function __construct(EntityFieldManagerInterface $entity_field_manager) {
    $this->entityFieldManager = $entity_field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_field.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\group\Entity\GroupTypeInterface $type */
    $form = parent::form($form, $form_state);
    $type = $this->entity;
    if ($this->operation === 'add') {
      $fields = $this->entityFieldManager
        ->getBaseFieldDefinitions('group');
    }
    else {
      $fields = $this->entityFieldManager
        ->getFieldDefinitions('group', $type
        ->id());
    }
    $form['label'] = [
      '#title' => $this
        ->t('Name'),
      '#type' => 'textfield',
      '#default_value' => $type
        ->label(),
      '#description' => $this
        ->t('The human-readable name of this group type. This text will be displayed as part of the list on the %group-add page. This name must be unique.', [
        '%group-add' => $this
          ->t('Add group'),
      ]),
      '#required' => TRUE,
      '#size' => 30,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $type
        ->id(),
      '#maxlength' => GroupTypeInterface::ID_MAX_LENGTH,
      '#machine_name' => [
        'exists' => [
          'Drupal\\group\\Entity\\GroupType',
          'load',
        ],
        'source' => [
          'label',
        ],
      ],
      '#description' => $this
        ->t('A unique machine-readable name for this group type. It must only contain lowercase letters, numbers, and underscores. This name will be used for constructing the URL of the %group-add page, in which underscores will be converted into hyphens.', [
        '%group-add' => $this
          ->t('Add group'),
      ]),
    ];
    $form['description'] = [
      '#title' => $this
        ->t('Description'),
      '#type' => 'textarea',
      '#default_value' => $type
        ->getDescription(),
      '#description' => $this
        ->t('This text will be displayed on the <em>Add group</em> page.'),
    ];
    $form['title_label'] = [
      '#title' => $this
        ->t('Title field label'),
      '#type' => 'textfield',
      '#default_value' => $fields['label']
        ->getLabel(),
      '#description' => $this
        ->t('Sets the label of the field that will be used for group titles.'),
      '#required' => TRUE,
    ];
    $form['new_revision'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Create a new revision when a group is modified'),
      '#default_value' => $type
        ->shouldCreateNewRevision(),
    ];
    $form['creator_membership'] = [
      '#title' => $this
        ->t('The group creator automatically becomes a member'),
      '#type' => 'checkbox',
      '#default_value' => $type
        ->creatorGetsMembership(),
      '#description' => $this
        ->t('This will make sure that anyone who creates a group of this type will automatically become a member of it.'),
    ];
    $form['creator_wizard'] = [
      '#title' => $this
        ->t('Group creator must complete their membership'),
      '#type' => 'checkbox',
      '#default_value' => $type
        ->creatorMustCompleteMembership(),
      '#description' => $this
        ->t('This will first show you the form to create the group and then a form to fill out your membership details.<br />You can choose to disable this wizard if you did not or will not add any fields to the membership.<br /><strong>Warning:</strong> If you do have fields on the membership and do not use the wizard, you may end up with required fields not being filled out.'),
      '#states' => [
        'visible' => [
          ':input[name="creator_membership"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];

    // Add-form specific elements.
    if ($this->operation == 'add') {
      $form['add_admin_role'] = [
        '#title' => $this
          ->t('Automatically configure an administrative role'),
        '#type' => 'checkbox',
        '#default_value' => 0,
        '#description' => $this
          ->t("This will create an 'Admin' role by default which will have all currently defined permissions."),
      ];
      $form['assign_admin_role'] = [
        '#title' => $this
          ->t('Automatically assign this administrative role to group creators'),
        '#type' => 'checkbox',
        '#default_value' => 0,
        '#description' => $this
          ->t("This will assign the 'Admin' role to the group creator membership."),
        '#states' => [
          'visible' => [
            ':input[name="creator_membership"]' => [
              'checked' => TRUE,
            ],
            ':input[name="add_admin_role"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
    }
    else {
      $options = [];
      foreach ($type
        ->getRoles(FALSE) as $group_role) {
        $options[$group_role
          ->id()] = $group_role
          ->label();
      }
      $form['creator_roles'] = [
        '#title' => $this
          ->t('Group creator roles'),
        '#type' => 'checkboxes',
        '#options' => $options,
        '#default_value' => $type
          ->getCreatorRoleIds(),
        '#description' => $this
          ->t('Please select which custom group roles a group creator will receive.'),
        '#states' => [
          'visible' => [
            ':input[name="creator_membership"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
      if (empty($options)) {
        $add_role_url = Url::fromRoute('entity.group_role.add_form', [
          'group_type' => $type
            ->id(),
        ]);
        $t_args = [
          '@url' => $add_role_url
            ->toString(),
        ];
        $description = $this
          ->t('You do not have any custom group roles yet, <a href="@url">create one here</a>.', $t_args);
        $form['creator_roles']['#description'] .= "<br /><em>{$description}</em>";
      }
    }
    return $this
      ->protectBundleIdElement($form);
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this
      ->t('Save group type');
    $actions['delete']['#value'] = $this
      ->t('Delete group type');
    return $actions;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $id = trim($form_state
      ->getValue('id'));

    // '0' is invalid, since elsewhere we might check it using empty().
    if ($id == '0') {
      $form_state
        ->setErrorByName('id', $this
        ->t("Invalid machine-readable name. Enter a name other than %invalid.", [
        '%invalid' => $id,
      ]));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\group\Entity\GroupTypeInterface $type */
    $type = $this->entity;

    // Trim any whitespace off the label.
    $type
      ->set('label', trim($type
      ->label()));

    // Clean up the creator role IDs as it comes from a checkboxes element.
    if ($creator_roles = $type
      ->getCreatorRoleIds()) {
      $type
        ->set('creator_roles', array_values(array_filter($creator_roles)));
    }
    $status = $type
      ->save();
    $t_args = [
      '%label' => $type
        ->label(),
    ];

    // Update title field definition.
    $fields = $this->entityFieldManager
      ->getFieldDefinitions('group', $type
      ->id());
    $title_field = $fields['label'];
    $title_label = $form_state
      ->getValue('title_label');
    if ($title_field
      ->getLabel() !== $title_label) {
      $title_field
        ->getConfig($type
        ->id())
        ->setLabel($title_label)
        ->save();
    }
    if ($status == SAVED_UPDATED) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The group type %label has been updated.', $t_args));
    }
    elseif ($status == SAVED_NEW) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The group type %label has been added. You may now configure which roles a group creator will receive by editing the group type.', $t_args));
      $context = array_merge($t_args, [
        'link' => $type
          ->toLink($this
          ->t('View'), 'collection')
          ->toString(),
      ]);
      $this
        ->logger('group')
        ->notice('Added group type %label.', $context);

      // Optionally create a default admin role.
      if ($form_state
        ->getValue('add_admin_role')) {
        $storage = $this->entityTypeManager
          ->getStorage('group_role');

        /** @var \Drupal\group\Entity\GroupRoleInterface $group_role */
        $group_role = $storage
          ->create([
          'id' => $type
            ->id() . '-admin',
          'label' => $this
            ->t('Admin'),
          'weight' => 100,
          'group_type' => $type
            ->id(),
        ]);
        $group_role
          ->grantAllPermissions()
          ->save();

        // Optionally auto-assign the admin role to group creators.
        if ($form_state
          ->getValue('assign_admin_role')) {
          $type
            ->set('creator_roles', [
            $type
              ->id() . '-admin',
          ])
            ->save();
        }
      }
    }
    $form_state
      ->setRedirectUrl($type
      ->toUrl('collection'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BundleEntityFormBase::protectBundleIdElement protected function Protects the bundle entity's ID property's form element against changes.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 11
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 3
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 13
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties. 9
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 6
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 3
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 12
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 20
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
GroupTypeForm::$entityFieldManager protected property The entity field manager service.
GroupTypeForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
GroupTypeForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
GroupTypeForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
GroupTypeForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
GroupTypeForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
GroupTypeForm::__construct public function Constructs a new GroupTypeForm.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.