You are here

class RRSSBSettingsForm in Ridiculously Responsive Social Sharing Buttons 8.2

RRSSB settings form.

@package Drupal\rrssb\Form

Hierarchy

Expanded class hierarchy of RRSSBSettingsForm

File

src/Form/RRSSBSettingsForm.php, line 13

Namespace

Drupal\rrssb\Form
View source
class RRSSBSettingsForm extends EntityForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $all_buttons = rrssb_button_config();
    $form = parent::form($form, $form_state);
    $config = $this->entity;
    $chosen = $config
      ->get('chosen');
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#default_value' => $config
        ->label(),
      '#required' => TRUE,
      '#description' => $this
        ->t('Administrative label for this button set.'),
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#machine_name' => [
        'exists' => [
          $this,
          'exists',
        ],
      ],
      '#default_value' => $config
        ->id(),
      '#disabled' => !$config
        ->isNew(),
      '#required' => TRUE,
    ];
    $form['follow'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Select type of buttons'),
      '#options' => [
        0 => $this
          ->t('Share'),
        1 => $this
          ->t('Follow'),
      ],
      '#default_value' => $config
        ->get('follow'),
      '#description' => $this
        ->t('"Share" buttons invite the visitor to share the page from your site onto their page/channel/profile.  "Follow" buttons direct the visitor to your page/channel/profile.'),
    ];

    // Create the config for the table of buttons.
    $form['chosen'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('Button'),
        $this
          ->t('Enabled'),
        $this
          ->t('Username'),
        $this
          ->t('Weight'),
      ],
      '#empty' => $this
        ->t('No buttons found'),
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'item-row-weight',
        ],
      ],
    ];
    foreach ($all_buttons as $name => $button) {
      $form['chosen'][$name]['#attributes']['class'][] = 'draggable';

      // Determine if this button requires a particular value of follow
      // to be valid. This is the case if one or other of the URL as not
      // present.
      // Both URLs absent makes no sense and would be a bug.
      unset($require_follow);
      if (!isset($button['follow_url'])) {
        $require_follow = 0;
      }
      elseif (!isset($button['share_url'])) {
        $require_follow = 1;
      }
      $form['chosen'][$name]['label'] = [
        '#type' => 'item',
        '#markup' => $name,
      ];
      $form['chosen'][$name]['enabled'] = [
        '#type' => 'checkbox',
        '#default_value' => isset($chosen[$name]['enabled']) ? $chosen[$name]['enabled'] : FALSE,
      ];
      if (isset($require_follow)) {

        // Hide entries where there is no corresponding URL.
        $form['chosen'][$name]['enabled']['#states'] = [
          'visible' => [
            ":input[name='follow']" => [
              'value' => $require_follow,
            ],
          ],
        ];
      }
      if (isset($button['follow_url']) && strpos($button['follow_url'], '[rrssb:username]') !== FALSE) {
        $form['chosen'][$name]['username'] = [
          '#type' => 'textfield',
          '#default_value' => isset($chosen[$name]['username']) ? $chosen[$name]['username'] : '',
          // Hide the username for share URLs where it isn't needed.
          // Otherwise it is a required field.
          '#states' => [
            'visible' => [
              ":input[name='follow']" => [
                'value' => 1,
              ],
            ],
            'required' => [
              ":input[name='follow']" => [
                'value' => 1,
              ],
              ":input[name='chosen[{$name}][enabled]']" => [
                'checked' => TRUE,
              ],
            ],
          ],
        ];
      }
      else {
        $form['chosen'][$name]['username'] = [];
      }
      $form['chosen'][$name]['weight'] = [
        '#type' => 'weight',
        '#title' => $this
          ->t('Weight for @title', [
          '@title' => $name,
        ]),
        '#title_display' => 'invisible',
        '#default_value' => isset($chosen[$name]['weight']) ? $chosen[$name]['weight'] : 0,
        '#delta' => 20,
        '#attributes' => [
          'class' => [
            'item-row-weight',
          ],
        ],
      ];
    }

    // Appearance settings stored as an array ready to pass to the library code.
    $appearance = $config
      ->get('appearance');
    $form['appearance'] = [
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#title' => $this
        ->t('Appearance'),
    ];
    $form['appearance']['size'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Size'),
      '#size' => 5,
      '#default_value' => $appearance['size'],
      '#description' => $this
        ->t('Size, as a proportion of default size set in CSS.'),
    ];
    $form['appearance']['shrink'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Minimum size'),
      '#size' => 5,
      '#default_value' => $appearance['shrink'],
      '#description' => $this
        ->t('Minimum size to shrink buttons to, as a proportion of original size.'),
    ];
    $form['appearance']['regrow'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Extra row size'),
      '#size' => 5,
      '#default_value' => $appearance['regrow'],
      '#description' => $this
        ->t('Maximum size of buttons after they have been forced to split onto extra rows of buttons, as a proportion of original size.'),
    ];
    $form['appearance']['minRows'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Minimum rows'),
      '#size' => 5,
      '#default_value' => $appearance['minRows'],
      '#description' => $this
        ->t('Minimum number of rows of buttons.  Set to a large value to create vertical layout.'),
    ];
    $form['appearance']['maxRows'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Maximum rows'),
      '#size' => 5,
      '#default_value' => $appearance['maxRows'],
      '#description' => $this
        ->t('Maximum number of rows of buttons.  If more rows would be needed, instead the labels are hidden.  Set to a large value to keep labels if at all possible.'),
    ];
    $form['appearance']['prefixReserve'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Prefix reserved width'),
      '#size' => 5,
      '#default_value' => $appearance['prefixReserve'],
      '#description' => $this
        ->t('Proportion of total width reserved for prefix to be inline.'),
    ];
    $form['appearance']['prefixHide'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Prefix maximum width'),
      '#size' => 5,
      '#default_value' => $appearance['prefixHide'],
      '#description' => $this
        ->t('Maximum prefix width as a proportion of total width before hiding prefix.'),
    ];
    $form['appearance']['alignRight'] = [
      '#type' => 'checkbox',
      '#title' => t('Right-align buttons'),
      '#size' => 5,
      '#default_value' => $appearance['alignRight'],
      '#description' => t('By default, buttons are left-aligned, with any padding added on the right.  Enable this to right-align, and instead pad on the left.'),
    ];
    $form['prefix'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Prefix text before the buttons'),
      '#default_value' => $config
        ->get('prefix'),
      '#description' => $this
        ->t('Put this text before the buttons.  For example "Follow us" or "Share this page".'),
    ];
    $form['image_tokens'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Tokens to use to find images'),
      '#default_value' => $config
        ->get('image_tokens'),
      '#description' => $this
        ->t('Enter one or more tokens, separated by |.  These tokens will be tried in turn to determine the image to use in buttons.
        The default value is @default which you can adapt to pick other fields or as desired.', [
        '@default' => RRSSB_DEFAULT_IMAGE_TOKEN,
      ]),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $values = $form_state
      ->getValues();
    foreach ($values['chosen'] as $name => $settings) {
      if ($settings['enabled']) {
        if ($values['follow'] && isset($settings['username']) && !$settings['username']) {
          $form_state
            ->setErrorByName("chosen[{$name}][username]", $this
            ->t('You must set the username to use "Follow" button for @button', [
            '@button' => $name,
          ]));
        }

        // If a button is enabled where there is no URL, we don't count that
        // as an error, just don't show the button (@see rrssb_settings).
      }
    }
  }

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

    // Clear cached CSS.
    rrssb_cache_flush();

    // @@ Need to clear the cached block and the node field?
    return $result;
  }

  /**
   * Helper function to check whether an Example configuration entity exists.
   */
  public function exists($id) {
    $entity = $this->entityTypeManager
      ->getStorage('rrssb_button_set')
      ->getQuery()
      ->condition('id', $id)
      ->execute();
    return (bool) $entity;
  }

}

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::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::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
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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::$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.
RRSSBSettingsForm::exists public function Helper function to check whether an Example configuration entity exists.
RRSSBSettingsForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
RRSSBSettingsForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
RRSSBSettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.