You are here

abstract class FlagFormBase in Flag 8.4

Provides the base flag add/edit form.

Since both the add and edit flag forms are largely the same, the majority of functionality is done in this class. It generates the form, validates the input, and handles the submit.

Hierarchy

Expanded class hierarchy of FlagFormBase

File

src/Form/FlagFormBase.php, line 19

Namespace

Drupal\flag\Form
View source
abstract class FlagFormBase extends EntityForm {

  /**
   * The action link plugin manager.
   *
   * @var Drupal\flag\ActionLink\ActionLinkPluginManager
   */
  protected $actionLinkManager;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $bundleInfoService;

  /**
   * The link generator.
   *
   * @var \Drupal\Core\Utility\LinkGeneratorInterface
   */
  protected $linkGenerator;

  /**
   * Constructs a new form.
   *
   * @param \Drupal\flag\ActionLink\ActionLinkPluginManager $action_link_manager
   *   The link type plugin manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info_service
   *   The bundle info service.
   * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
   *   The link generator service.
   */
  public function __construct(ActionLinkPluginManager $action_link_manager, EntityTypeBundleInfoInterface $bundle_info_service, LinkGeneratorInterface $link_generator) {
    $this->actionLinkManager = $action_link_manager;
    $this->bundleInfoService = $bundle_info_service;
    $this->linkGenerator = $link_generator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.flag.linktype'), $container
      ->get('entity_type.bundle.info'), $container
      ->get('link_generator'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $entity_type = NULL) {
    $form = parent::buildForm($form, $form_state);
    $flag = $this->entity;
    $form['#flag'] = $flag;
    $form['#flag_name'] = $flag
      ->id();
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#default_value' => $flag
        ->label(),
      '#description' => $this
        ->t('A short, descriptive title for this flag. It will be used in administrative interfaces to refer to this flag, and in page titles and menu items of some views this module provides (these are customizable, though). Some examples could be <em>Bookmarks</em>, <em>Favorites</em>, or <em>Offensive</em>.'),
      '#maxlength' => 255,
      '#required' => TRUE,
      '#weight' => -3,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#title' => $this
        ->t('Machine name'),
      '#default_value' => $flag
        ->id(),
      '#description' => $this
        ->t('The machine-name for this flag. It may be up to 32 characters long and may only contain lowercase letters, underscores, and numbers. It will be used in URLs and in all API calls.'),
      '#weight' => -2,
      '#machine_name' => [
        'exists' => '\\Drupal\\flag\\Entity\\Flag::load',
      ],
      '#disabled' => !$flag
        ->isNew(),
      '#required' => TRUE,
    ];
    $form['global'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Scope'),
      '#default_value' => $flag
        ->isGlobal() ? 1 : 0,
      '#options' => [
        0 => $this
          ->t('Personal'),
        1 => $this
          ->t('Global'),
      ],
      '#weight' => -1,
    ];

    // Add descriptions for each radio button.
    $form['global'][0]['#description'] = $this
      ->t('Each user has individual flags on entities.');
    $form['global'][1]['#description'] = $this
      ->t('The entity is either flagged or not for all users.');
    $form['messages'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('Messages'),
    ];
    $form['messages']['flag_short'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Flag link text'),
      '#default_value' => $flag
        ->get('flag_short') ?: $this
        ->t('Flag this item'),
      '#description' => $this
        ->t('The text for the "flag this" link for this flag.'),
      '#required' => TRUE,
    ];
    $form['messages']['flag_long'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Flag link description'),
      '#default_value' => $flag
        ->get('flag_long'),
      '#description' => $this
        ->t('The description of the "flag this" link. Usually displayed on mouseover.'),
    ];
    $form['messages']['flag_message'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Flagged message'),
      '#default_value' => $flag
        ->get('flag_message'),
      '#description' => $this
        ->t('Message displayed after flagging content. If JavaScript is enabled, it will be displayed below the link. If not, it will be displayed in the message area.'),
    ];
    $form['messages']['unflag_short'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Unflag link text'),
      '#default_value' => $flag
        ->get('unflag_short') ?: $this
        ->t('Unflag this item'),
      '#description' => $this
        ->t('The text for the "unflag this" link for this flag.'),
      '#required' => TRUE,
    ];
    $form['messages']['unflag_long'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Unflag link description'),
      '#default_value' => $flag
        ->get('unflag_long'),
      '#description' => $this
        ->t('The description of the "unflag this" link. Usually displayed on mouseover.'),
    ];
    $form['messages']['unflag_message'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Unflagged message'),
      '#default_value' => $flag
        ->get('unflag_message'),
      '#description' => $this
        ->t('Message displayed after content has been unflagged. If JavaScript is enabled, it will be displayed below the link. If not, it will be displayed in the message area.'),
    ];
    $form['access'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('Flag access'),
      '#tree' => FALSE,
      '#weight' => 10,
    ];

    // Switch plugin type in case a different is chosen.
    $flag_type_plugin = $flag
      ->getFlagTypePlugin();
    $flag_type_def = $flag_type_plugin
      ->getPluginDefinition();
    $bundles = $this->bundleInfoService
      ->getBundleInfo($flag_type_def['entity_type']);
    $entity_bundles = [];
    foreach ($bundles as $bundle_id => $bundle_row) {
      $entity_bundles[$bundle_id] = $bundle_row['label'];
    }

    // Flag classes will want to override this form element.
    $form['access']['bundles'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Flaggable types'),
      '#options' => $entity_bundles,
      '#default_value' => $flag
        ->getBundles(),
      '#description' => $this
        ->t('Check any bundles that this flag may be used on. Leave empty to apply to all bundles.'),
      '#weight' => 10,
    ];
    $form['access']['unflag_denied_text'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Unflag not allowed text'),
      '#default_value' => $flag
        ->getUnflagDeniedText(),
      '#description' => $this
        ->t('If a user is allowed to flag but not unflag, this text will be displayed after flagging. Often this is the past-tense of the link text, such as "flagged".'),
      '#weight' => -1,
    ];
    $form['display'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('Display options'),
      '#description' => $this
        ->t('Flags are usually controlled through links that allow users to toggle their behavior. You can choose how users interact with flags by changing options here. It is legitimate to have none of the following checkboxes ticked, if, for some reason, you wish <a href="@placement-url">to place the the links on the page yourself</a>.', [
        '@placement-url' => 'http://drupal.org/node/295383',
      ]),
      '#tree' => FALSE,
      '#weight' => 20,
      '#prefix' => '<div id="link-type-settings-wrapper">',
      '#suffix' => '</div>',
    ];
    $form['display']['settings'] = [
      '#type' => 'container',
      '#weight' => 21,
    ];
    $form = $flag_type_plugin
      ->buildConfigurationForm($form, $form_state);
    $form['display']['link_type'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Link type'),
      '#options' => $this->actionLinkManager
        ->getAllLinkTypes(),
      // '#after_build' => array('flag_check_link_types'),
      '#default_value' => $flag
        ->getLinkTypePlugin()
        ->getPluginId(),
      // Give this a high weight so additions by the flag classes for entity-
      // specific options go above.
      '#weight' => 18,
      '#attributes' => [
        'class' => [
          'flag-link-options',
        ],
      ],
      '#required' => TRUE,
      '#ajax' => [
        'callback' => '::updateSelectedPluginType',
        'wrapper' => 'link-type-settings-wrapper',
        'event' => 'change',
        'method' => 'replace',
      ],
    ];

    //debug($flag->getLinkTypePlugin()->getPluginId(), 'default value');
    $form['display']['link_type_submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Update'),
      '#submit' => [
        '::submitSelectPlugin',
      ],
      '#weight' => 20,
      '#attributes' => [
        'class' => [
          'js-hide',
        ],
      ],
    ];

    // Add the descriptions to each ratio button element. These attach to the
    // elements when FormAPI expands them.
    $action_link_plugin_defs = $this->actionLinkManager
      ->getDefinitions();
    foreach ($action_link_plugin_defs as $key => $info) {
      $form['display']['link_type'][$key] = [
        '#description' => $info['description'],
        '#executes_submit_callback' => TRUE,
        '#limit_validation_errors' => [
          [
            'link_type',
          ],
        ],
        '#submit' => [
          '::submitSelectPlugin',
        ],
      ];
    }
    $action_link_plugin = $flag
      ->getLinkTypePlugin();
    $form = $action_link_plugin
      ->buildConfigurationForm($form, $form_state);
    return $form;
  }

  /**
   * Handles switching the configuration type selector.
   */
  public function updateSelectedPluginType($form, FormStateInterface $form_state) {
    return $form['display'];
  }

  /**
   * Handles submit call when sensor type is selected.
   */
  public function submitSelectPlugin(array $form, FormStateInterface $form_state) {

    // Rebuild the entity using the form's new state.
    $this->entity = $this
      ->buildEntity($form, $form_state);
    $form_state
      ->setRebuild();
  }

  /**
   * {@inheritdoc}
   */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    $entity = parent::buildEntity($form, $form_state);

    // Update the link type plugin.
    // @todo Do this somewhere else?
    $entity
      ->setLinkTypePlugin($entity
      ->get('link_type'));

    //debug($entity->getLinkTypePlugin()->getPluginId(), $entity->get('link_type'));
    return $entity;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $flag = $this->entity;
    $flag
      ->getFlagTypePlugin()
      ->validateConfigurationForm($form, $form_state);
    $flag
      ->getLinkTypePlugin()
      ->validateConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $flag = $this->entity;
    $flag
      ->getFlagTypePlugin()
      ->submitConfigurationForm($form, $form_state);
    $flag
      ->getLinkTypePlugin()
      ->submitConfigurationForm($form, $form_state);
    $status = $flag
      ->save();
    $message_params = [
      '%label' => $flag
        ->label(),
    ];
    $logger_params = [
      '%label' => $flag
        ->label(),
      'link' => $flag
        ->toLink($this
        ->t('Edit'), 'edit-form')
        ->toString(),
    ];
    if ($status == SAVED_UPDATED) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('Flag %label has been updated.', $message_params));
      $this
        ->logger('flag')
        ->notice('Flag %label has been updated.', $logger_params);
    }
    else {
      $this
        ->messenger()
        ->addMessage($this
        ->t('Flag %label has been added.', $message_params));
      $this
        ->logger('flag')
        ->notice('Flag %label has been added.', $logger_params);
    }

    // We clear caches more vigorously if the flag was new.
    // _flag_clear_cache($flag->entity_type, !empty($flag->is_new));
    // Save permissions.
    // This needs to be done after the flag cache has been cleared, so that
    // the new permissions are picked up by hook_permission().
    // This may need to move to the flag class when we implement extra
    // permissions for different flag types: http://drupal.org/node/879988
    // If the flag ID has changed, clean up all the obsolete permissions.
    if ($flag
      ->id() != $form['#flag_name']) {
      $old_name = $form['#flag_name'];
      $permissions = [
        "flag {$old_name}",
        "unflag {$old_name}",
      ];
      foreach (array_keys(user_roles()) as $rid) {
        user_role_revoke_permissions($rid, $permissions);
      }
    }

    /*
        foreach (array_keys(user_roles(!\Drupal::moduleHandler()->moduleExists('session_api'))) as $rid) {
          // Create an array of permissions.
          $permissions = array(
            "flag $flag->name" => $flag->roles['flag'][$rid],
            "unflag $flag->name" => $flag->roles['unflag'][$rid],
          );
          user_role_change_permissions($rid, $permissions);
        }
    */

    // @todo: when we add database caching for flags we'll have to clear the
    // cache again here.
    $form_state
      ->setRedirect('entity.flag.collection');
  }

  /**
   * {@inheritdoc}
   */
  public function delete(array $form, FormStateInterface $form_state) {
    $form_state
      ->setRedirect('flag_list');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::$entity protected property The entity being used by this form. 7
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::actions protected function Returns an array of supported actions for the current entity form. 29
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::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::form public function Gets the actual form array to be built. 30
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::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
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::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::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 17
EntityForm::__get public function
EntityForm::__set public function
FlagFormBase::$actionLinkManager protected property The action link plugin manager.
FlagFormBase::$bundleInfoService protected property The entity type manager.
FlagFormBase::$linkGenerator protected property The link generator. Overrides LinkGeneratorTrait::$linkGenerator
FlagFormBase::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity
FlagFormBase::buildForm public function Form constructor. Overrides EntityForm::buildForm 2
FlagFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FlagFormBase::delete public function
FlagFormBase::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
FlagFormBase::submitSelectPlugin public function Handles submit call when sensor type is selected.
FlagFormBase::updateSelectedPluginType public function Handles switching the configuration type selector.
FlagFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
FlagFormBase::__construct public function Constructs a new form.
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.
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.