You are here

class PostForm in Open Social 10.2.x

Same name and namespace in other branches
  1. 8.9 modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  2. 8 modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  3. 8.2 modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  4. 8.3 modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  5. 8.4 modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  6. 8.5 modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  7. 8.6 modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  8. 8.7 modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  9. 8.8 modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  10. 10.3.x modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  11. 10.0.x modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm
  12. 10.1.x modules/social_features/social_post/src/Form/PostForm.php \Drupal\social_post\Form\PostForm

Form controller for Post edit forms.

Hierarchy

Expanded class hierarchy of PostForm

1 file declares its use of PostForm
SocialAlbumPostForm.php in modules/social_features/social_album/src/Form/SocialAlbumPostForm.php

File

modules/social_features/social_post/src/Form/PostForm.php, line 19

Namespace

Drupal\social_post\Form
View source
class PostForm extends ContentEntityForm {
  private $postViewDefault;
  private $postViewProfile;
  private $postViewGroup;

  /**
   * The Current User object.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * Constructs a Form object.
   */
  public function __construct(AccountInterface $current_user, EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    $this->currentUser = $current_user;
  }

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

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

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

    // Init form mode comparison strings.
    $this
      ->setFormMode();

    // If we're rendered in a block and given a display mode then we store it
    // now because it's overwritten by ContentEntityForm::init().
    $display = $this
      ->getFormDisplay($form_state);
    $form = parent::buildForm($form, $form_state);
    $form['#attached']['library'][] = 'social_post/keycode-submit';

    // If we already have a form display mode then we simply restore that.
    if (!empty($display)) {
      $this
        ->setFormDisplay($display, $form_state);
    }
    elseif ($this->operation === 'edit') {
      $this
        ->configureViewMode($form_state);
    }

    // If this post has a visibility field then we configure its allowed values.
    if (isset($form['field_visibility'])) {
      $this
        ->configureVisibilityField($form, $form_state);
    }
    if ($this->entity
      ->isNew()) {
      unset($form['status']);
    }
    else {
      $form['status']['#access'] = $this->currentUser
        ->hasPermission('edit any post entities');
    }
    return $form;
  }

  /**
   * Configures the view mode when an existing entity is being edited.
   *
   * Uses the default view mode for community posts, the group view mode for
   * posts placed in a group and the profile view mode for posts placed on
   * someone's profile.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state used to render this form.
   */
  protected function configureViewMode(FormStateInterface $form_state) {
    $view_mode = $this->postViewDefault;
    if ($this->entity
      ->hasField('field_recipient_user') && !$this->entity
      ->get('field_recipient_user')
      ->isEmpty()) {
      $view_mode = $this->postViewProfile;
    }
    elseif ($this->entity
      ->hasField('field_recipient_group') && !$this->entity
      ->get('field_recipient_group')
      ->isEmpty()) {
      $view_mode = $this->postViewGroup;
    }
    $display = EntityFormDisplay::load($view_mode);
    $this
      ->setFormDisplay($display, $form_state);
  }

  /**
   * Configures the allows values for the visiblity field.
   *
   * Uses whether this is a new entity or an existing entity and which view mode
   * is used to configure the allowed values of the visibility field. This is
   * different for posts made to a profile or in a group.
   *
   * When editing a visibility is shown but can not be altered.
   *
   * For the meaning of the numbers in this function check the field definition
   * in the field.storage.post.field_visibility configuration object.
   *
   * @param array $form
   *   The post form being rendered.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   */
  protected function configureVisibilityField(array &$form, FormStateInterface $form_state) {
    $form['#attached']['library'][] = 'social_post/visibility-settings';

    // Default is create/add mode.
    $form['field_visibility']['widget'][0]['#edit_mode'] = FALSE;
    $display_id = $this
      ->getFormDisplay($form_state)
      ->id();

    // For the explanation of the numbers see
    // field.storage.post.field_visibility.
    if ($display_id === $this->postViewDefault || $display_id === $this->postViewProfile) {

      // Set default value to community.
      unset($form['field_visibility']['widget'][0]['#options'][0]);
      if (isset($form['field_visibility']['widget'][0]['#default_value'])) {
        $default_value = $form['field_visibility']['widget'][0]['#default_value'];
        if ((string) $default_value !== '1') {
          $form['field_visibility']['widget'][0]['#default_value'] = '2';
        }
      }
      else {
        $form['field_visibility']['widget'][0]['#default_value'] = '2';
      }
      $current_group = _social_group_get_current_group();

      // We unset the group visibility if we don't have a group.
      if (empty($current_group)) {
        unset($form['field_visibility']['widget'][0]['#options'][3]);
      }
    }
    else {
      $current_group = NULL;
      if ($this->operation === 'edit' && $this->entity
        ->hasField('field_recipient_group') && !$this->entity
        ->get('field_recipient_group')
        ->isEmpty()) {
        $current_group = $this->entity
          ->get('field_recipient_group')
          ->first()
          ->get('entity')
          ->getTarget()
          ->getValue();
      }
      else {
        $current_group = _social_group_get_current_group();
      }

      // We unset the group visibility if we don't have a group.
      if (empty($current_group)) {
        unset($form['field_visibility']['widget'][0]['#options'][3]);
      }
      else {
        $group_type_id = $current_group
          ->getGroupType()
          ->id();
        $allowed_options = social_group_get_allowed_visibility_options_per_group_type($group_type_id, NULL, $this->entity, $current_group);
        if ($group_type_id !== 'flexible_group') {
          $form['field_visibility']['widget'][0]['#default_value'] = "0";
          unset($form['field_visibility']['widget'][0]['#options'][2]);
          if ($allowed_options['community'] !== TRUE) {
            unset($form['field_visibility']['widget'][0]['#options'][0]);
          }
        }
        else {
          unset($form['field_visibility']['widget'][0]['#options'][0]);
          if ($allowed_options['community'] !== TRUE) {
            unset($form['field_visibility']['widget'][0]['#options'][2]);
          }
        }
        if ($allowed_options['public'] !== TRUE) {
          unset($form['field_visibility']['widget'][0]['#options'][1]);
        }
        else {
          $form['field_visibility']['widget'][0]['#default_value'] = "1";
        }
        if ($allowed_options['group'] !== TRUE) {
          unset($form['field_visibility']['widget'][0]['#options'][3]);
        }
        else {
          $form['field_visibility']['widget'][0]['#default_value'] = "3";
        }
      }
    }

    // When a post is being edited we configure the visibility to be shown as a
    // read-only value.
    if ($this->operation === 'edit') {

      /** @var \Drupal\social_post\Entity\Post $post */
      $post = $this->entity;
      $form['#post_id'] = $post
        ->id();

      // In edit mode we don't want people to actually change visibility
      // setting of the post.
      if ($current_value = $this->entity
        ->get('field_visibility')->value) {

        // We set the default value.
        $form['field_visibility']['widget'][0]['#default_value'] = $current_value;
      }

      // Unset the other options, because we do not want to be able to change
      // it but we do want to use the button for informing the user.
      foreach ($form['field_visibility']['widget'][0]['#options'] as $key => $option) {
        if ($option['value'] != $form['field_visibility']['widget'][0]['#default_value']) {
          unset($form['field_visibility']['widget'][0]['#options'][$key]);
        }
      }

      // Set button to disabled in our template, users have no option anyway.
      $form['field_visibility']['widget'][0]['#edit_mode'] = TRUE;
    }
  }

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

    // Init form modes.
    $this
      ->setFormMode();
    $display = $this
      ->getFormDisplay($form_state);
    if ($this->entity
      ->isNew()) {
      if (isset($display) && ($display_id = $display
        ->get('id'))) {
        if ($display_id === $this->postViewProfile) {
          $account_profile = \Drupal::routeMatch()
            ->getParameter('user');
          $this->entity
            ->get('field_recipient_user')
            ->setValue($account_profile);
        }
        elseif ($display_id === $this->postViewGroup) {
          $group = \Drupal::routeMatch()
            ->getParameter('group');
          $this->entity
            ->get('field_recipient_group')
            ->setValue($group);
        }
      }
    }
    $status = parent::save($form, $form_state);
    switch ($status) {
      case SAVED_NEW:
        $message = $this
          ->t('Your post %label has been posted.', [
          '%label' => $this->entity
            ->label(),
        ]);
        $this->moduleHandler
          ->alter('social_post_message', $message, $form_state);
        $this
          ->messenger()
          ->addStatus($message);
        break;
      default:
        $this
          ->messenger()
          ->addStatus($this
          ->t('Your post %label has been saved.', [
          '%label' => $this->entity
            ->label(),
        ]));
    }
  }

  /**
   * Function to set the current form modes.
   *
   * Retrieve the form display before it is overwritten in the parent.
   */
  protected function setFormMode() {
    if ($this
      ->getBundleEntity() !== NULL) {
      $bundle = $this
        ->getBundleEntity()
        ->id();

      // Set as variables, since the bundle might be different.
      $this->postViewDefault = 'post.' . $bundle . '.default';
      $this->postViewProfile = 'post.' . $bundle . '.profile';
      $this->postViewGroup = 'post.' . $bundle . '.group';
    }
  }

}

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 4
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::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 EntityForm::submitForm 4
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
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
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::actions protected function Returns an array of supported actions for the current entity form. 35
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 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::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::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
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.
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.
PostForm::$currentUser protected property The Current User object.
PostForm::$postViewDefault private property
PostForm::$postViewGroup private property
PostForm::$postViewProfile private property
PostForm::buildForm public function Form constructor. Overrides EntityForm::buildForm 1
PostForm::configureViewMode protected function Configures the view mode when an existing entity is being edited.
PostForm::configureVisibilityField protected function Configures the allows values for the visiblity field. 1
PostForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
PostForm::getFormId public function Returns a unique string identifying the form. Overrides EntityForm::getFormId
PostForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save 1
PostForm::setFormMode protected function Function to set the current form modes.
PostForm::__construct public function Constructs a Form object. Overrides ContentEntityForm::__construct
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.