You are here

class IframeWidgetBase in Iframe 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldWidget/IframeWidgetBase.php \Drupal\iframe\Plugin\Field\FieldWidget\IframeWidgetBase

Plugin implementation base functions.

Hierarchy

Expanded class hierarchy of IframeWidgetBase

File

src/Plugin/Field/FieldWidget/IframeWidgetBase.php, line 13

Namespace

Drupal\iframe\Plugin\Field\FieldWidget
View source
class IframeWidgetBase extends WidgetBase {

  /**
   * Allowed editable attributes of iframe field on node-edit.
   *
   * @var array
   */
  public $allowedAttributes = [
    'title' => 1,
    'width' => 1,
    'height' => 1,
    'url' => 1,
  ];

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'width' => '',
      'height' => '',
      'class' => '',
      'expose_class' => 0,
      'frameborder' => '0',
      'scrolling' => 'auto',
      'transparency' => '0',
      'tokensupport' => '0',
      'allowfullscreen' => '0',
    ] + parent::defaultSettings();
  }

  /**
   * Translate the description for iframe width/height only once.
   */
  protected static function getSizedescription() {
    return t('The iframe\'s width and height can be set in pixels as a number only ("500" for 500 pixels) or in a percentage value followed by the percent symbol (%) ("50%" for 50 percent).');
  }

  /**
   * It is {@inheritdoc}.
   *
   * Used : at "Manage form display" after work-symbol.
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {

    /* Settings form after "manage form display" page, valid for one content type */
    $field_settings = $this
      ->getFieldSettings();
    $settings = $this
      ->getSettings();
    $values = [];
    $values = $settings + $field_settings + self::defaultSettings();

    // \iframe_debug(0, 'manage settingsForm field_settings', $field_settings);
    // \iframe_debug(0, 'manage settingsForm settings', $settings);
    // \iframe_debug(0, 'manage settingsForm values', $values);
    $element['width'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Iframe Width'),
      // ''
      '#default_value' => isset($values['width']) ? $values['width'] : '',
      '#description' => self::getSizedescription(),
      '#maxlength' => 4,
      '#size' => 4,
    ];
    $element['height'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Iframe Height'),
      // ''
      '#default_value' => isset($values['height']) ? $values['height'] : '',
      '#description' => self::getSizedescription(),
      '#maxlength' => 4,
      '#size' => 4,
    ];
    $element['class'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Additional CSS Class'),
      // ''
      '#default_value' => isset($values['class']) ? $values['class'] : '',
      '#description' => $this
        ->t('When output, this iframe will have this class attribute. Multiple classes should be separated by spaces.'),
    ];
    $element['expose_class'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Expose Additional CSS Class'),
      // 0
      '#default_value' => isset($values['expose_class']) ? $values['expose_class'] : '',
      '#description' => $this
        ->t('Allow author to specify an additional class attribute for this iframe.'),
    ];
    $element['frameborder'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Frameborder'),
      '#options' => [
        '0' => $this
          ->t('No frameborder'),
        '1' => $this
          ->t('Show frameborder'),
      ],
      // 0
      '#default_value' => isset($values['frameborder']) ? $values['frameborder'] : '0',
      '#description' => $this
        ->t('Frameborder is the border around the iframe. Most people want it removed, so the default value for frameborder is zero (0), or no border.'),
    ];
    $element['scrolling'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Scrolling'),
      '#options' => [
        'auto' => $this
          ->t('Automatic'),
        'no' => $this
          ->t('Disabled'),
        'yes' => $this
          ->t('Enabled'),
      ],
      // 'auto'
      '#default_value' => isset($values['scrolling']) ? $values['scrolling'] : 'auto',
      '#description' => $this
        ->t('Scrollbars help the user to reach all iframe content despite the real height of the iframe content. Please disable it only if you know what you are doing.'),
    ];
    $element['transparency'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Transparency'),
      '#options' => [
        '0' => $this
          ->t('No transparency'),
        '1' => $this
          ->t('Allow transparency'),
      ],
      // 0
      '#default_value' => isset($values['transparency']) ? $values['transparency'] : '0',
      '#description' => $this
        ->t('Allow transparency per CSS in the outer iframe tag. You have to set background-color:transparent in your iframe body tag too!'),
    ];
    $element['tokensupport'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Token Support'),
      '#options' => [
        '0' => $this
          ->t('No tokens allowed'),
        '1' => $this
          ->t('Tokens only in title field'),
        '2' => $this
          ->t('Tokens for title and URL field'),
      ],
      // 0
      '#default_value' => isset($values['tokensupport']) ? $values['tokensupport'] : '0',
      '#description' => $this
        ->t('Are tokens allowed for users to use in title or URL field?'),
    ];
    $element['allowfullscreen'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Allow fullscreen'),
      '#options' => [
        '0' => $this
          ->t('false'),
        '1' => $this
          ->t('true'),
      ],
      // 0
      '#default_value' => isset($values['allowfullscreen']) ? $values['allowfullscreen'] : '0',
      '#description' => $this
        ->t('Allow fullscreen for iframe. The iframe can activate fullscreen mode by calling the requestFullscreen() method.'),
    ];
    if (!\Drupal::moduleHandler()
      ->moduleExists('token')) {
      $element['tokensupport']['#description'] .= ' ' . $this
        ->t('Attention: Token module is not currently enabled!');
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $field_settings = $this
      ->getFieldSettings();
    $settings = $this
      ->getSettings() + $field_settings;

    /* summary on the "manage display" page, valid for one content type */
    $summary = [];
    $summary[] = $this
      ->t('Iframe default width: @width', [
      '@width' => $settings['width'],
    ]);
    $summary[] = $this
      ->t('Iframe default height: @height', [
      '@height' => $settings['height'],
    ]);
    $summary[] = $this
      ->t('Iframe default frameborder: @frameborder', [
      '@frameborder' => $settings['frameborder'],
    ]);
    $summary[] = $this
      ->t('Iframe default scrolling: @scrolling', [
      '@scrolling' => $settings['scrolling'],
    ]);
    return $summary;
  }

  /**
   * It is {@inheritdoc}.
   *
   * Used: (1) at admin edit fields.
   *
   * Used: (2) at add-story for creation content.
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    // 1) Shows the "default fields" in the edit-type-field page
    // -- (on_admin_page = true).
    // 2) Edit-fields on the article-edit-page (on_admin_page = false).
    // Global settings.
    $field_settings = $this
      ->getFieldSettings();
    $settings = $this
      ->getSettings() + $field_settings + self::defaultSettings();

    /** @var \Drupal\iframe\Plugin\Field\FieldType\IframeItem $item */
    $item =& $items[$delta];
    $field_definition = $item
      ->getFieldDefinition();
    $on_admin_page = isset($element['#field_parents'][0]) && 'default_value_input' == $element['#field_parents'][0];
    $is_new = $item
      ->getEntity()
      ->isNew();

    // \iframe_debug(0, 'add-story formElement field_setting', $field_settings);
    // \iframe_debug(0, 'add-story formElement setting', $settings);
    $values = $item
      ->toArray();
    if ($is_new || $on_admin_page) {
      foreach ($values as $vkey => $vval) {
        if ($vval !== NULL && $vval !== '') {
          $settings[$vkey] = $vval;
        }
      }
    }
    else {
      if (isset($settings['expose_class']) && $settings['expose_class']) {
        $this->allowedAttributes['class'] = 1;
      }
      foreach ($this->allowedAttributes as $attribute => $attrAllowed) {
        if ($attrAllowed) {
          $settings[$attribute] = $values[$attribute];
        }
      }
    }

    // \iframe_debug(0, 'add-story formElement final setting', $settings);
    foreach ($settings as $attribute => $attrValue) {
      $item
        ->setValue($attribute, $attrValue);
    }
    $element += [
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#open' => TRUE,
    ];
    if (!$on_admin_page) {
      $element['#title'] = $field_definition
        ->getLabel();
    }
    $element['title'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Iframe Title'),
      '#placeholder' => '',
      '#default_value' => $settings['title'],
      '#size' => 80,
      '#maxlength' => 1024,
      '#weight' => 2,
    ];
    $element['url'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Iframe URL'),
      '#placeholder' => 'https://',
      '#default_value' => isset($settings['url']) ? $settings['url'] : '',
      '#size' => 80,
      '#maxlength' => 1024,
      '#weight' => 1,
      '#element_validate' => [
        [
          get_class($this),
          'validateUrl',
        ],
      ],
    ];
    $element['width'] = [
      '#title' => $this
        ->t('Iframe Width'),
      '#type' => 'textfield',
      '#default_value' => isset($settings['width']) ? $settings['width'] : '',
      '#description' => self::getSizedescription(),
      '#maxlength' => 4,
      '#size' => 4,
      '#weight' => 3,
      '#element_validate' => [
        [
          get_class($this),
          'validateWidth',
        ],
      ],
    ];
    $element['height'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Iframe Height'),
      '#default_value' => isset($settings['height']) ? $settings['height'] : '',
      '#description' => self::getSizedescription(),
      '#maxlength' => 4,
      '#size' => 4,
      '#weight' => 4,
      '#element_validate' => [
        [
          get_class($this),
          'validateHeight',
        ],
      ],
    ];
    if (isset($settings['expose_class']) && $settings['expose_class']) {
      $element['class'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Additional CSS Class'),
        // ''
        '#default_value' => $settings['class'],
        '#description' => $this
          ->t('When output, this iframe will have this class attribute. Multiple classes should be separated by spaces.'),
        '#weight' => 5,
      ];
    }

    // \iframe_debug(0, 'formElement', $element);
    return $element;
  }

  /**
   * Validate width(if minimum url is defined)
   *
   * @see \Drupal\Core\Form\FormValidator
   */
  public static function validateWidth(&$form, FormStateInterface &$form_state) {
    $parents = $form['#parents'];
    $itemfield = $parents[0];
    $iteminst = $parents[1];

    /*
     * $value = $form['#value'];
     * $itemname = $parents[2];
     * $itemid = $form['#id'];
     */
    $node = $form_state
      ->getUserInput();
    $me = $node[$itemfield][$iteminst];

    // \iframe_debug(0, 'validateWidth', $me);
    if (!empty($me['url']) && isset($me['width'])) {
      if (empty($me['width']) || !preg_match('#^(\\d+\\%?|auto)$#', $me['width'])) {
        $form_state
          ->setError($form, self::getSizedescription());
      }
    }
  }

  /**
   * Validate height (if minimum url is defined)
   *
   * @see \Drupal\Core\Form\FormValidator
   */
  public static function validateHeight(&$form, FormStateInterface &$form_state) {
    $parents = $form['#parents'];
    $itemfield = $parents[0];
    $iteminst = $parents[1];

    /*
     * $value = $form['#value'];
     * $itemname = $parents[2];
     * $itemid = $form['#id'];
     */
    $node = $form_state
      ->getUserInput();
    $me = $node[$itemfield][$iteminst];

    // \iframe_debug(0, 'validateHeight', $me);
    if (!empty($me['url']) && isset($me['height'])) {
      if (empty($me['height']) || !preg_match('#^(\\d+\\%?|auto)$#', $me['height'])) {
        $form_state
          ->setError($form, self::getSizedescription());
      }
    }
  }

  /**
   * Validate url.
   *
   * @see \Drupal\Core\Form\FormValidator
   */
  public static function validateUrl(&$form, FormStateInterface &$form_state) {
    $parents = $form['#parents'];
    $itemfield = $parents[0];
    $iteminst = $parents[1];

    /*
     * $value = $form['#value'];
     * $itemname = $parents[2];
     * $itemid = $form['#id'];
     */
    $node = $form_state
      ->getUserInput();
    $me = $node[$itemfield][$iteminst];
    $testabsolute = true;

    // \iframe_debug(0, 'validateUrl', $me);
    if (!empty($me['url'])) {
      if (preg_match('#^/($|[^/])#', $me['url'])) {
        $testabsolute = false;
      }
      if (!UrlHelper::isValid($me['url'], $testabsolute)) {
        $form_state
          ->setError($form, t('Invalid syntax for "Iframe URL".'));
      }
      elseif (strpos($me['url'], '//') === 0) {
        $form_state
          ->setError($form, t('Drupal does not accept scheme-less URLs. Please add "https:" to your URL, this works on http-parent-pages too.'));
      }
    }
  }

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

    // Global values.
    $field_settings = $this
      ->getFieldSettings();
    $settings = $this
      ->getSettings() + $field_settings;
    if (isset($settings['expose_class']) && $settings['expose_class']) {
      $this->allowedAttributes['class'] = 1;
    }

    // \iframe_debug(0, __METHOD__ . ' settings', $settings);
    // \iframe_debug(0, __METHOD__ . ' old-values', $values);
    foreach ($values as $delta => $value) {

      /*
       * Validate that all keys are available,
       * in the user-has-only-some-values case too.
       */
      $testvalue = $value + $settings;
      $newvalue = [];
      foreach ($testvalue as $key => $val) {
        if (isset($this->allowedAttributes[$key]) && $this->allowedAttributes[$key]) {
          $newvalue[$key] = $val;
        }
        elseif (isset($settings[$key])) {
          $newvalue[$key] = $settings[$key];
        }
        else {
          $newvalue[$key] = $val;
        }
      }
      if (!empty($settings['class']) && !strstr($newvalue['class'], $settings['class'])) {
        $newvalue['class'] = trim(implode(" ", [
          $settings['class'],
          $newvalue['class'],
        ]));
      }
      $new_values[$delta] = $newvalue;
    }

    // \iframe_debug(0, __METHOD__ . ' new-values', $new_values);
    return $new_values;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AllowedTagsXssTrait::allowedTags public function Returns a list of tags allowed by AllowedTagsXssTrait::fieldFilterXss().
AllowedTagsXssTrait::displayAllowedTags public function Returns a human-readable list of allowed tags for display in help texts.
AllowedTagsXssTrait::fieldFilterXss public function Filters an HTML string to prevent XSS vulnerabilities.
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
IframeWidgetBase::$allowedAttributes public property Allowed editable attributes of iframe field on node-edit.
IframeWidgetBase::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsBase::defaultSettings
IframeWidgetBase::formElement public function It is . Overrides WidgetInterface::formElement 3
IframeWidgetBase::getSizedescription protected static function Translate the description for iframe width/height only once.
IframeWidgetBase::massageFormValues public function Massages the form values into the format expected for field values. Overrides WidgetBase::massageFormValues
IframeWidgetBase::settingsForm public function It is . Overrides WidgetBase::settingsForm
IframeWidgetBase::settingsSummary public function Returns a short summary for the current widget settings. Overrides WidgetBase::settingsSummary
IframeWidgetBase::validateHeight public static function Validate height (if minimum url is defined)
IframeWidgetBase::validateUrl public static function Validate url.
IframeWidgetBase::validateWidth public static function Validate width(if minimum url is defined)
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
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.
WidgetBase::$fieldDefinition protected property The field definition.
WidgetBase::$settings protected property The widget settings. Overrides PluginSettingsBase::$settings
WidgetBase::addMoreAjax public static function Ajax callback for the "Add another item" button.
WidgetBase::addMoreSubmit public static function Submission handler for the "Add another item" button.
WidgetBase::afterBuild public static function After-build handler for field elements in a form.
WidgetBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 5
WidgetBase::errorElement public function Assigns a field-level validation error to the right widget sub-element. Overrides WidgetInterface::errorElement 8
WidgetBase::extractFormValues public function Extracts field values from submitted form values. Overrides WidgetBaseInterface::extractFormValues 2
WidgetBase::flagErrors public function Reports field-level validation errors against actual form elements. Overrides WidgetBaseInterface::flagErrors 2
WidgetBase::form public function Creates a form element for a field. Overrides WidgetBaseInterface::form 3
WidgetBase::formMultipleElements protected function Special handling to create form elements for multiple values. 1
WidgetBase::formSingleElement protected function Generates the form element for a single copy of the widget.
WidgetBase::getFieldSetting protected function Returns the value of a field setting.
WidgetBase::getFieldSettings protected function Returns the array of field settings.
WidgetBase::getFilteredDescription protected function Returns the filtered field description.
WidgetBase::getWidgetState public static function Retrieves processing information about the widget from $form_state. Overrides WidgetBaseInterface::getWidgetState
WidgetBase::getWidgetStateParents protected static function Returns the location of processing information within $form_state.
WidgetBase::handlesMultipleValues protected function Returns whether the widget handles multiple values.
WidgetBase::isApplicable public static function Returns if the widget can be used for the provided field. Overrides WidgetInterface::isApplicable 4
WidgetBase::isDefaultValueWidget protected function Returns whether the widget used for default value form.
WidgetBase::setWidgetState public static function Stores processing information about the widget in $form_state. Overrides WidgetBaseInterface::setWidgetState
WidgetBase::__construct public function Constructs a WidgetBase object. Overrides PluginBase::__construct 5