You are here

class AgreementForm in Agreement 8.2

Same name in this branch
  1. 8.2 src/Form/AgreementForm.php \Drupal\agreement\Form\AgreementForm
  2. 8.2 src/Entity/AgreementForm.php \Drupal\agreement\Entity\AgreementForm
Same name and namespace in other branches
  1. 3.0.x src/Entity/AgreementForm.php \Drupal\agreement\Entity\AgreementForm

Add or edit agreements.

Hierarchy

Expanded class hierarchy of AgreementForm

File

src/Entity/AgreementForm.php, line 15

Namespace

Drupal\agreement\Entity
View source
class AgreementForm extends EntityForm implements ContainerInjectionInterface {

  /**
   * Path validator.
   *
   * @var \Drupal\Core\Path\PathValidatorInterface
   */
  protected $pathValidator;

  /**
   * Initialize method.
   *
   * @param \Drupal\Core\Path\PathValidatorInterface $pathValidator
   *   The path validator service.
   */
  public function __construct(PathValidatorInterface $pathValidator) {
    $this->pathValidator = $pathValidator;
  }

  /**
   * Title callback for edit page.
   *
   * @return string
   *   The title when modifying the agreement entity.
   */
  public function title() {
    $this
      ->getEntity();
    return $this
      ->t('Manage Agreement: @label', [
      '@label' => $this->entity
        ->label(),
    ]);
  }

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

    /* @var \Drupal\agreement\Entity\Agreement $entity */
    $entity = $this->entity;
    $settings = $entity
      ->getSettings();

    // @todo https://drupal.org/node/2403359
    if (!$entity
      ->isNew()) {
      $form['#title'] = $this
        ->t('Manage Agreement: @label', [
        '@label' => $entity
          ->label(),
      ]);
    }
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Agreement type'),
      '#description' => $this
        ->t('Provide a human-readable label for this agreement type.'),
      '#default_value' => $entity
        ->label(),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => !$entity
        ->isNew() ? $entity
        ->id() : '',
      '#required' => TRUE,
      '#disabled' => !$entity
        ->isNew(),
      '#maxlength' => 32,
      '#machine_name' => [
        'exists' => [
          $this,
          'exists',
        ],
        'source' => [
          'type',
        ],
      ],
    ];
    $form['path'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Path'),
      '#description' => $this
        ->t('At what URL should the agreement page be located? Relative to site root. A leading slash is required.'),
      '#default_value' => $entity
        ->get('path') ? $entity
        ->get('path') : '',
      '#required' => TRUE,
      '#element_validate' => [
        [
          $this,
          'validatePath',
        ],
      ],
    ];
    $form['agreement'] = [
      '#type' => 'text_format',
      '#title' => $this
        ->t('Agreement text'),
      '#description' => $this
        ->t('Provide the agreement text.'),
      '#default_value' => $entity
        ->get('agreement') ? $entity
        ->get('agreement') : '',
      '#format' => $settings['format'] ? $settings['format'] : filter_default_format(),
      '#rows' => 12,
    ];
    $role_options = [];
    $roles = user_roles(FALSE);
    foreach ($roles as $role_name => $role) {
      if (!$role
        ->isAdmin()) {
        $role_options[$role
          ->id()] = $role
          ->label();
      }
    }
    $form['config'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this
        ->t('Settings'),
      '#default_tab' => 'edit-visibility',
    ];
    $form['visibility'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Visibility'),
      '#group' => 'config',
      '#parents' => [
        'settings',
        'visibility',
      ],
    ];
    $form['settings'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Settings'),
      '#group' => 'config',
      '#parents' => [
        'settings',
      ],
    ];
    $form['visibility']['settings'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Show agreement on specific pages'),
      '#options' => [
        0 => $this
          ->t('Show on every page except the listed pages'),
        1 => $this
          ->t('Show on only the listed pages'),
      ],
      '#required' => TRUE,
      '#default_value' => $entity
        ->getVisibilitySetting(),
      '#parents' => [
        'settings',
        'visibility',
        'settings',
      ],
    ];
    $form['visibility']['pages'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Pages'),
      '#description' => $this
        ->t("Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths\n                                  are %blog for the blog page and %blog-wildcard for every personal blog. %front is the\n                                  front page. The user password and reset pages will always be excluded.", [
        '%blog' => 'blog',
        '%blog-wildcard' => 'blog/*',
        '%front' => '<front>',
      ]),
      '#default_value' => $entity
        ->getVisibilityPages(),
      '#parents' => [
        'settings',
        'visibility',
        'pages',
      ],
    ];
    $form['settings']['roles'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Roles'),
      '#description' => $this
        ->t('Select all of the roles that are required to accept this agreement.'),
      '#default_value' => $settings['roles'],
      '#required' => TRUE,
      '#multiple' => TRUE,
      '#options' => $role_options,
      '#parents' => [
        'settings',
        'roles',
      ],
    ];
    $form['settings']['frequency'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Frequency'),
      '#description' => $this
        ->t('How ofter should users be required to accept the agreement?'),
      '#options' => [
        -1 => $this
          ->t('Only once'),
        0 => $this
          ->t('On every log in'),
        365 => $this
          ->t('Once a year'),
      ],
      '#required' => TRUE,
      '#default_value' => $settings['frequency'],
      '#parents' => [
        'settings',
        'frequency',
      ],
    ];
    $form['settings']['title'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Agreement Page Title'),
      '#description' => $this
        ->t('What should the title of the agreement page be?'),
      '#required' => TRUE,
      '#default_value' => $settings['title'],
      '#parents' => [
        'settings',
        'title',
      ],
    ];
    $form['settings']['checkbox'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Agreement Checkbox Text'),
      '#description' => $this
        ->t('This text will be displayed next to the "I agree" checkbox.'),
      '#required' => TRUE,
      '#default_value' => $settings['checkbox'],
      '#parents' => [
        'settings',
        'checkbox',
      ],
    ];
    $form['settings']['submit'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Agreement Submit Text'),
      '#description' => $this
        ->t('This text will be displayed on the "Submit" button.'),
      '#required' => TRUE,
      '#default_value' => $settings['submit'],
      '#parents' => [
        'settings',
        'submit',
      ],
    ];
    $form['settings']['success'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Agreement Success Message'),
      '#description' => $this
        ->t('What message should be displayed to the users once they accept the agreement?'),
      '#required' => TRUE,
      '#default_value' => $settings['success'],
      '#parents' => [
        'settings',
        'success',
      ],
    ];
    $form['settings']['failure'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Agreement Failure Message'),
      '#description' => $this
        ->t('What message should be displayed to the users if they do not accept the agreement?'),
      '#required' => TRUE,
      '#default_value' => $settings['failure'],
      '#parents' => [
        'settings',
        'failure',
      ],
    ];
    $form['settings']['revoked'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Agreement Revoke Message'),
      '#description' => $this
        ->t('What message should be displayed to the users if they revoke their agreement?'),
      '#default_value' => $settings['revoked'],
      '#parents' => [
        'settings',
        'revoked',
      ],
    ];
    $form['settings']['destination'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Agreement Success Destination'),
      '#description' => $this
        ->t('What page should be displayed after the user accepts the agreement? Leave blank
                                  to go to the original destination that triggered the agreement or the front page
                                  if no original destination is present. %front is the front page. Users who log
                                  in via the one-time login link will always be redirected to their user profile
                                  to change their password.', [
        '%front' => '<front>',
      ]),
      '#default_value' => $settings['destination'],
      '#parents' => [
        'settings',
        'destination',
      ],
    ];
    $form['settings']['recipient'] = [
      '#type' => 'email',
      '#title' => $this
        ->t('Recipient Email'),
      '#description' => $this
        ->t('Optionally sends an email to the provided email address each time any user agrees to this agreement. This transmits personal data.'),
      '#default_value' => $settings['recipient'],
      '#parents' => [
        'settings',
        'recipient',
      ],
    ];
    return parent::form($form, $form_state);
  }

  /**
   * Validate the provided path.
   *
   * @param array $element
   *   The form array element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function validatePath(array $element, FormStateInterface $form_state) {
    $new = $form_state
      ->getValue('path');
    $url = $this->pathValidator
      ->getUrlIfValidWithoutAccessCheck($new);
    if ($new !== $this->entity
      ->get('path') && (!$url || $url
      ->isExternal() || $url
      ->isRouted())) {
      $form_state
        ->setErrorByName('path', $this
        ->t('The path must be an internal and unused relative URL.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $pages_array = [];
    $agreement_text = $form_state
      ->getValue('agreement');
    $visibility = $form_state
      ->getValue([
      'settings',
      'visibility',
      'settings',
    ]);
    $visibility_pages = $form_state
      ->getValue([
      'settings',
      'visibility',
      'pages',
    ]);
    $roles = array_values($form_state
      ->getValue([
      'settings',
      'roles',
    ]));

    // Normalizes the visibility pages form state into an array.
    if ($visibility_pages) {
      $list = explode("\n", $visibility_pages);
      $list = array_map('trim', $list);
      $pages_array = array_filter($list, 'strlen');
    }
    $form_state
      ->setValue('agreement', $agreement_text['value']);
    $form_state
      ->setValue([
      'settings',
      'format',
    ], $agreement_text['format']);
    $form_state
      ->setValue([
      'settings',
      'visibility',
      'pages',
    ], $pages_array);
    $form_state
      ->setValue([
      'settings',
      'visibility',
      'settings',
    ], (int) $visibility);
    $form_state
      ->setValue([
      'settings',
      'frequency',
    ], (int) $form_state
      ->getValue([
      'settings',
      'frequency',
    ]));
    $form_state
      ->setValue([
      'settings',
      'roles',
    ], $roles);
    $form_state
      ->setRedirect('entity.agreement.collection');
    parent::submitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['cancel'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('Cancel'),
      '#url' => Url::fromRoute('entity.agreement.collection'),
      '#attributes' => [
        'class' => [
          'button',
        ],
      ],
    ];
    return $actions;
  }

  /**
   * Checks if the machine name exists.
   *
   * @param string $value
   *   The machine name to check.
   *
   * @return bool
   *   TRUE if the machine name exists already.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function exists($value) {
    $agreements = $this->entityTypeManager
      ->getStorage('agreement')
      ->load($value);
    return !empty($agreements);
  }

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

}

Members

Namesort descending Modifiers Type Description Overrides
AgreementForm::$pathValidator protected property Path validator.
AgreementForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
AgreementForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
AgreementForm::exists public function Checks if the machine name exists.
AgreementForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
AgreementForm::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
AgreementForm::title public function Title callback for edit page.
AgreementForm::validatePath public function Validate the provided path.
AgreementForm::__construct public function Initialize method.
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::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 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
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::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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.