You are here

class GroupSubscribeForm in Organic groups 8

Provides a form for subscribing to a group.

As this form in fact saves the OG membership it is easier to use Drupal\Core\Entity\ContentEntityForm However we mimic the functionality of Drupal\Core\Entity\EntityConfirmFormBase, so it will be presented as a confirmation page.

Hierarchy

Expanded class hierarchy of GroupSubscribeForm

File

src/Form/GroupSubscribeForm.php, line 26

Namespace

Drupal\og\Form
View source
class GroupSubscribeForm extends ContentEntityForm {

  /**
   * OG access service.
   *
   * @var \Drupal\og\OgAccessInterface
   */
  protected $ogAccess;

  /**
   * Constructs a GroupSubscribeForm.
   *
   * @param \Drupal\og\OgAccessInterface $og_access
   *   The OG access service.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface|null $entity_type_bundle_info
   *   The entity type bundle service.
   * @param \Drupal\Component\Datetime\TimeInterface|null $time
   *   The time service.
   *
   * @todo Set the `EntityRepositoryInterface` type hint on the second argument
   *   once Drupal 8.6.0 is released. It is currently omitted to preserve
   *   backwards compatibility with Drupal 8.5.x and earlier.
   *
   * @see https://github.com/Gizra/og/issues/397
   */
  public function __construct(OgAccessInterface $og_access, EntityRepositoryInterface $entity_repository, ?EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, ?TimeInterface $time = NULL) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    $this->ogAccess = $og_access;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('og.access'), $container
      ->get('entity.repository'), $container
      ->get('entity_type.bundle.info'), $container
      ->get('datetime.time'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'og_subscribe_confirm_form';
  }

  /**
   * Get the question to present to the user according to the membership state.
   *
   * @return string
   *   The confirmation question.
   */
  public function getQuestion() {

    /** @var \Drupal\og\OgMembershipInterface $membership */
    $membership = $this->entity;

    /** @var EntityInterface $group */
    $group = $membership
      ->getGroup();
    $label = $group
      ->access('view') ? $group
      ->label() : $this
      ->t('Private group');
    $message = $this
      ->isStateActive() ? $this
      ->t('Are you sure you want to join the group %label?', [
      '%label' => $label,
    ]) : $this
      ->t('Are you sure you want to request a subscription to the group %label?', [
      '%label' => $label,
    ]);
    return $message;
  }

  /**
   * Get confirmation text, according to the membership state.
   *
   * @return string
   *   The text.
   */
  public function getConfirmText() {
    return $this
      ->isStateActive() ? $this
      ->t('Join') : $this
      ->t('Request membership');
  }

  /**
   * Return the URL to redirect on cancel.
   *
   * @return \Drupal\Core\Url
   *   The URL object to redirect to.
   */
  public function getCancelUrl() {

    /** @var EntityInterface $group */
    $group = $this->entity
      ->getGroup();

    // User doesn't have access to the group entity, so redirect to front page,
    // otherwise back to the group entity.
    return $group
      ->access('view') ? $group
      ->toUrl() : new Url('<front>');
  }

  /**
   * {@inheritdoc}
   *
   * @see \Drupal\Core\Entity\EntityConfirmFormBase::buildForm
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $state = $this
      ->isStateActive() ? OgMembershipInterface::STATE_ACTIVE : OgMembershipInterface::STATE_PENDING;

    /** @var \Drupal\og\OgMembershipInterface $membership */
    $membership = $this->entity;
    $membership
      ->setState($state);

    // Add confirmation related elements.
    $form['#title'] = $this
      ->getQuestion();
    $form['#attributes']['class'][] = 'confirmation';
    $form['description'] = [
      '#markup' => $this
        ->t('This action cannot be undone.'),
    ];
    $form['confirm'] = [
      '#type' => 'hidden',
      '#value' => 1,
    ];

    // By default, render the form using theme_confirm_form().
    if (!isset($form['#theme'])) {
      $form['#theme'] = 'confirm_form';
    }
    $form = parent::buildForm($form, $form_state);
    if ($this
      ->isStateActive() && !empty($form[OgMembershipInterface::REQUEST_FIELD])) {

      // State is active, so no need to show the request field, as the user
      // will not need any approval for joining.
      $form[OgMembershipInterface::REQUEST_FIELD]['#access'] = FALSE;
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   *
   * @see \Drupal\Core\Entity\EntityConfirmFormBase::actions
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this
      ->getConfirmText();
    $actions['cancel'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('Cancel'),
      '#attributes' => [
        'class' => [
          'button',
        ],
      ],
      '#url' => $this
        ->getCancelUrl(),
      '#cache' => [
        'contexts' => [
          'url.query_args:destination',
        ],
      ],
    ];
    return $actions;
  }

  /**
   * Determine if the membership state should be active.
   *
   * @return bool
   *   True if the state is active.
   */
  public function isStateActive() {

    /** @var \Drupal\og\OgMembershipInterface $membership */
    $membership = $this
      ->getEntity();

    /** @var EntityInterface $group */
    $group = $membership
      ->getGroup();
    $user = $membership
      ->getOwner();
    $skip_approval = $this->ogAccess
      ->userAccess($group, 'subscribe without approval', $user)
      ->isAllowed();
    $state = $skip_approval ? OgMembershipInterface::STATE_ACTIVE : OgMembershipInterface::STATE_PENDING;
    if (!$group
      ->access('view', $user) && $state === OgMembershipInterface::STATE_ACTIVE) {

      // Determine with which state a user can subscribe to a group they don't
      // have access to.
      // By default, for security reasons, if the group is private, then the
      // state would be pending, regardless if the "subscribe without approval"
      // is enabled.
      $state = $this
        ->config('og.settings')
        ->get('deny_subscribe_without_approval') ? OgMembershipInterface::STATE_PENDING : OgMembershipInterface::STATE_ACTIVE;
    }
    return $state === OgMembershipInterface::STATE_ACTIVE;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    /** @var \Drupal\og\OgMembershipInterface $membership */
    $membership = $this
      ->getEntity();

    /** @var EntityInterface $group */
    $group = $membership
      ->getGroup();
    $message = $membership
      ->isActive() ? $this
      ->t('You are now subscribed to the group.') : $this
      ->t('Your subscription request has been sent.');
    $this
      ->messenger()
      ->addMessage($message);

    // User doesn't have access to the group entity, so redirect to front page,
    // otherwise back to the group entity.
    $redirect = $group
      ->access('view') ? $group
      ->toUrl() : Url::fromRoute('<front>');
    $form_state
      ->setRedirectUrl($redirect);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentEntityForm::$entity protected property The entity being used by this form. Overrides EntityForm::$entity 9
ContentEntityForm::$entityRepository protected property The entity repository service.
ContentEntityForm::$entityTypeBundleInfo protected property The entity type bundle info service.
ContentEntityForm::$time protected property The time service.
ContentEntityForm::addRevisionableFormFields protected function Add revision form fields if the entity enabled the UI.
ContentEntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity 3
ContentEntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties Overrides EntityForm::copyFormValuesToEntity
ContentEntityForm::flagViolations protected function Flags violations for the current form. 4
ContentEntityForm::form public function Gets the actual form array to be built. Overrides EntityForm::form 13
ContentEntityForm::getBundleEntity protected function Returns the bundle entity of the entity, or NULL if there is none.
ContentEntityForm::getEditedFieldNames protected function Gets the names of all fields edited in the form. 4
ContentEntityForm::getFormDisplay public function Gets the form display. Overrides ContentEntityFormInterface::getFormDisplay
ContentEntityForm::getFormLangcode public function Gets the code identifying the active form language. Overrides ContentEntityFormInterface::getFormLangcode
ContentEntityForm::getNewRevisionDefault protected function Should new revisions created on default.
ContentEntityForm::init protected function Initializes the form state and the entity before the first form build. Overrides EntityForm::init 1
ContentEntityForm::initFormLangcodes protected function Initializes form language code values.
ContentEntityForm::isDefaultFormLangcode public function Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface::isDefaultFormLangcode
ContentEntityForm::prepareEntity protected function Prepares the entity object before the form is built first. Overrides EntityForm::prepareEntity 1
ContentEntityForm::setFormDisplay public function Sets the form display. Overrides ContentEntityFormInterface::setFormDisplay
ContentEntityForm::showRevisionUi protected function Checks whether the revision form fields should be added to the form.
ContentEntityForm::updateChangedTime public function Updates the changed time of the entity.
ContentEntityForm::updateFormLangcode public function Updates the form language to reflect any change to the entity language.
ContentEntityForm::validateForm public function Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level… Overrides FormBase::validateForm 3
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
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::$privateEntityManager private property The entity manager.
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::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
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 1
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::save public function Form submission handler for the 'save' action. Overrides EntityFormInterface::save 41
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
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::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 1
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. 1
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. Overrides UrlGeneratorTrait::redirect
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.
GroupSubscribeForm::$ogAccess protected property OG access service.
GroupSubscribeForm::actions protected function Overrides EntityForm::actions
GroupSubscribeForm::buildForm public function Overrides EntityForm::buildForm
GroupSubscribeForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
GroupSubscribeForm::getCancelUrl public function Return the URL to redirect on cancel.
GroupSubscribeForm::getConfirmText public function Get confirmation text, according to the membership state.
GroupSubscribeForm::getFormId public function Returns a unique string identifying the form. Overrides EntityForm::getFormId
GroupSubscribeForm::getQuestion public function Get the question to present to the user according to the membership state.
GroupSubscribeForm::isStateActive public function Determine if the membership state should be active.
GroupSubscribeForm::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 ContentEntityForm::submitForm
GroupSubscribeForm::__construct public function Constructs a GroupSubscribeForm. Overrides ContentEntityForm::__construct
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.