Commit 60519cc2 authored by Jeff Hipp's avatar Jeff Hipp Committed by Adam Nagy
Browse files

Issue #2805089: Add test coverage and fix bug related to hard limit option.

parent 1f52bf23
Loading
Loading
Loading
Loading
+16 −3
Original line number Diff line number Diff line
@@ -57,9 +57,6 @@ function maxlength_element_info_alter(&$cache) {

/**
 * Implements hook_field_widget_third_party_settings_form().
 *
 * @todo add the settings in the field schema and also test the edge values,
 * like 0 or negative.
 */
function maxlength_field_widget_third_party_settings_form(WidgetInterface $plugin, FieldDefinitionInterface $field_definition, $form_mode, $form, FormStateInterface $form_state) {
  $plugin_id = $plugin->getPluginId();
@@ -80,6 +77,7 @@ function maxlength_field_widget_third_party_settings_form(WidgetInterface $plugi
        '#title' => t('Summary maximum length'),
        '#description' => t('The maximum number of characters in the field.'),
        '#default_value' => $plugin->getThirdPartySetting('maxlength', 'maxlength_js_summary'),
        '#element_validate' => ['maxlength_number_element_validate'],
      ];
      $element['maxlength_js_label_summary'] = [
        '#type' => 'textarea',
@@ -95,6 +93,7 @@ function maxlength_field_widget_third_party_settings_form(WidgetInterface $plugi
        '#title' => t('Maximum length'),
        '#description' => t('The maximum number of characters in the field.'),
        '#default_value' => $plugin->getThirdPartySetting('maxlength', 'maxlength_js'),
        '#element_validate' => ['maxlength_number_element_validate'],
      ];
      $element['maxlength_js_label'] = [
        '#type' => 'textarea',
@@ -113,10 +112,20 @@ function maxlength_field_widget_third_party_settings_form(WidgetInterface $plugi
        '#default_value' => $plugin->getThirdPartySetting('maxlength', 'maxlength_js_enforce'),
      ];
    }

    return $element;
  }
}

/**
 * Form element validation handler to ensure the maxlength numbers are positive.
 */
function maxlength_number_element_validate(array &$element, FormStateInterface $form_state) {
  if ($element['#value'] != '' && (int) $element['#value'] < 1) {
    $form_state->setError($element, t('The maximum length has to be a positive number.'));
  }
}

/**
 * Implements hook_field_widget_settings_summary_alter().
 */
@@ -154,6 +163,10 @@ function maxlength_field_widget_form_alter(&$element, FormStateInterface $form_s

      $maxlength_js_label = !empty($thirdPartySettings['maxlength']['maxlength_js_label_summary']) ? $thirdPartySettings['maxlength']['maxlength_js_label_summary'] : t('Content limited to @limit characters, remaining: <strong>@remaining</strong>');
      $element['summary']['#attributes']['maxlength_js_label'][] = $maxlength_js_label;

      if (isset($thirdPartySettings['maxlength']['maxlength_js_enforce']) && $thirdPartySettings['maxlength']['maxlength_js_enforce']) {
        $element['summary']['#attributes']['#maxlength_js_enforce'] = TRUE;
      }
    }

    if (isset($thirdPartySettings['maxlength']['maxlength_js']) && $thirdPartySettings['maxlength']['maxlength_js'] > 0) {
+4 −5
Original line number Diff line number Diff line
@@ -2,13 +2,14 @@

namespace Drupal\maxlength;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * The WidgetManager service.
 * The widget settings service.
 */
class WidgetSettings implements WidgetSettingsInterface {
class WidgetSettings implements WidgetSettingsInterface, ContainerInjectionInterface {

  /**
   * The module handler service.
@@ -18,7 +19,7 @@ class WidgetSettings implements WidgetSettingsInterface {
  protected $moduleHandler;

  /**
   * {@inheritdoc}
   * Constructs the WidgetSettings service.
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
@@ -90,8 +91,6 @@ class WidgetSettings implements WidgetSettingsInterface {

  /**
   * {@inheritdoc}
   *
   * @see \Drupal\maxlength\WidgetSettingsInterface::getAllowedSettings()
   */
  public function getAllowedSettings($widget_plugin_id) {
    $all_settings = $this->getAllowedSettingsForAll();
+4 −1
Original line number Diff line number Diff line
@@ -3,7 +3,7 @@
namespace Drupal\maxlength;

/**
 * The WidgetManagerInterface interface definition.
 * The widget settings interface definition.
 */
interface WidgetSettingsInterface {

@@ -20,6 +20,9 @@ interface WidgetSettingsInterface {

  /**
   * Returns all the settings which are allowed for all the widgets.
   *
   * @return array
   *   An array with all the settings which are allowed.
   */
  public function getAllowedSettingsForAll();

+110 −6
Original line number Diff line number Diff line
@@ -40,7 +40,13 @@ class MaxlengthCustomWidgetTest extends WebDriverTestBase {
      ->setComponent('body', [
        'type' => 'text_textarea_custom_widget',
        'third_party_settings' => [
          'maxlength' => ['maxlength_js' => 200],
          'maxlength' => [
            'maxlength_js' => 200,
            'maxlength_js_label' => 'Content limited to @limit characters, remaining: <strong>@remaining</strong> and total @count',
            'maxlength_js_summary' => 200,
            'maxlength_js_label_summary' => 'Summary content limited to @limit characters, remaining: <strong>@remaining</strong> and total @count',
            'maxlength_js_enforce' => FALSE,
          ],
        ],
      ])
      ->save();
@@ -50,7 +56,6 @@ class MaxlengthCustomWidgetTest extends WebDriverTestBase {
   * Tests that a custom textarea widget gets picked up and is supported.
   */
  public function testMaxlengthCustomWidgetSupported() {

    $admin_user = $this->drupalCreateUser([
      'bypass node access',
      'administer nodes',
@@ -61,16 +66,76 @@ class MaxlengthCustomWidgetTest extends WebDriverTestBase {
    $this->drupalGet('admin/structure/types/manage/article/form-display');
    $page = $this->getSession()->getPage();
    $page->pressButton('edit-fields-body-settings-edit');
    $this->getSession()->wait(1000);
    $this->assertSession()->assertWaitOnAjaxRequest();
    $page->checkField('Always show the summary field');
    $page->pressButton('Maxlength Settings');

    // Assert the maxlength config form.
    $this->assertSession()->fieldValueEquals('Summary maximum length', 200);
    $this->assertSession()->fieldValueEquals('Summary count down message', 'Summary content limited to @limit characters, remaining: <strong>@remaining</strong> and total @count');
    $this->assertSession()->fieldValueEquals('Maximum length', 200);
    $this->assertSession()->fieldValueEquals('Count down message', 'Content limited to @limit characters, remaining: <strong>@remaining</strong> and total @count');
    $this->assertSession()->checkboxNotChecked('Hard limit');

    $this->assertSession()->elementsCount('css', '[data-drupal-selector="edit-fields-body-settings-edit-form-third-party-settings-maxlength-maxlength-js-summary"]', 1);
    $page->findField('Summary max length')->setValue("123");

    // Assert the maximum length has to be a positive number.
    $page->fillField('Summary maximum length', '0');
    $page->pressButton('Update');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $this->assertSession()->pageTextContainsOnce('The maximum length has to be a positive number.');

    // Assert we can unset the value as well.
    $page->fillField('Summary maximum length', '');
    $page->pressButton('Update');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $this->assertSession()->pageTextNotContains('The maximum length has to be a positive number.');

    $page->pressButton('body_settings_edit');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $page->pressButton('Maxlength Settings');

    $page->fillField('Summary maximum length', '123');
    $page->pressButton('Update');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $this->assertSession()->pageTextNotContains('The maximum length has to be a positive number.');

    $page->pressButton('body_settings_edit');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $page->pressButton('Maxlength Settings');

    $page->fillField('Maximum length', '-1');
    $page->pressButton('Update');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $this->assertSession()->pageTextContainsOnce('The maximum length has to be a positive number.');

    $page->fillField('Maximum length', '0');
    $page->pressButton('Update');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $this->assertSession()->pageTextContainsOnce('The maximum length has to be a positive number.');

    // Assert we can unset the value as well.
    $page->fillField('Maximum length', '');
    $page->pressButton('Update');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $this->assertSession()->pageTextNotContains('The maximum length has to be a positive number.');

    $page->pressButton('body_settings_edit');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $page->pressButton('Maxlength Settings');

    $page->fillField('Maximum length', '200');
    $page->pressButton('Update');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $this->assertSession()->pageTextNotContains('The maximum length has to be a positive number.');

    $page->pressButton('Save');
    $this->assertSession()->responseContains('Max summary length: 123');
    $this->assertSession()->responseContains('Maximum summary length: 123');

    $this->drupalGet('node/add/article');

    // Give maxlength.js some time to manipulate the DOM.
    $this->getSession()->wait(1000, 'jQuery("div.counter").is(":visible")');
    $this->assertSession()->waitForElement('css', 'div.counter');

    // Check each counter for summary and body.
    $this->assertSession()->elementsCount('css', 'div.counter', 2);
@@ -78,6 +143,45 @@ class MaxlengthCustomWidgetTest extends WebDriverTestBase {
    // Check that the counter div follows the description of the field.
    $found = $this->xpath('//textarea[@data-drupal-selector="edit-body-0-value"]/following-sibling::div[@id="edit-body-0-value-counter"]');
    $this->assertCount(1, $found);

    // Fill the summary field with more characters than the limit.
    $page->fillField('Summary', '<strong>Leave blank</strong> to use <u>trimmed value</u> of full text as the summary. Leave blank to use trimmed value of full text as the summary. Extra characters');
    // The counter now should show "-17" for the extra characters.
    $this->assertSession()->pageTextContainsOnce('Summary content limited to 123 characters, remaining: -17 and total 140');

    // Fill the body field with more characters than the limit.
    $page->fillField('Body', '<b>Lorem ipsum</b> dolor sit amet, <u>consectetur adipiscing</u> elit. Ut accumsan justo non interdum fermentum. Phasellus semper risus eu arcu eleifend dignissim. Class aptent taciti sociosqu ad litora erat curae. Extra characters');
    // The counter now should show "-17" for the extra characters.
    $this->assertSession()->pageTextContainsOnce('Content limited to 200 characters, remaining: -17 and total 217');

    // Fill in the title and assert we can save the node with the extra
    // characters, and they are not truncated on edit.
    $page->fillField('Title', 'Article');
    $page->pressButton('Save');

    // Assert the counters in the form again.
    $this->drupalGet('node/1/edit');
    $this->assertSession()->pageTextContainsOnce('Summary content limited to 123 characters, remaining: -17 and total 140');
    $this->assertSession()->pageTextContainsOnce('Content limited to 200 characters, remaining: -17 and total 217');

    // Now set the "Hard limit" option for both of the fields and assert the
    // extra characters are truncated and "Extra characters" string is gone.
    $this->drupalGet('admin/structure/types/manage/article/form-display');
    $page->pressButton('edit-fields-body-settings-edit');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $page->pressButton('Maxlength Settings');
    $page->checkField('Hard limit');
    $page->pressButton('Update');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $page->pressButton('Save');

    $this->drupalGet('node/1/edit');
    $this->assertSession()->pageTextContains('Content limited to 123 characters, remaining: 0');
    $this->assertSession()->pageTextContains('Content limited to 200 characters, remaining: 0');
    $this->assertSession()->pageTextContainsOnce('Summary content limited to 123 characters, remaining: 0 and total 123');
    $this->assertSession()->pageTextContainsOnce('Content limited to 200 characters, remaining: 0 and total 200');
    $this->assertTrue($page->findField('Summary')->getValue() === '<strong>Leave blank</strong> to use <u>trimmed value</u> of full text as the summary. Leave blank to use trimmed value of full text as the summary.');
    $this->assertTrue($page->findField('Body')->getValue() === '<b>Lorem ipsum</b> dolor sit amet, <u>consectetur adipiscing</u> elit. Ut accumsan justo non interdum fermentum. Phasellus semper risus eu arcu eleifend dignissim. Class aptent taciti sociosqu ad litora erat curae.');
  }

}
+18 −3
Original line number Diff line number Diff line
@@ -42,9 +42,16 @@ class MaxlengthJavascriptTest extends WebDriverTestBase {
      'description' => 'Description of a text field',
    ])->save();
    $widget = [
      'type' => 'text_textarea',
      'type' => 'text_textarea_with_summary',
      'settings' => [
        'show_summary' => TRUE,
        'summary_rows' => 3,
      ],
      'third_party_settings' => [
        'maxlength' => ['maxlength_js' => 200],
        'maxlength' => [
          'maxlength_js' => 200,
          'maxlength_js_label' => 'Content limited to @limit characters, remaining: <strong>@remaining</strong> and total @count',
        ],
      ],
    ];
    EntityFormDisplay::load('entity_test.entity_test.default')
@@ -57,8 +64,11 @@ class MaxlengthJavascriptTest extends WebDriverTestBase {
    $this->drupalLogin($this->drupalCreateUser(['administer entity_test content']));
    $this->drupalGet($entity->toUrl('edit-form'));

    // Assert the maxlength counter labels.
    $this->assertSession()->pageTextContainsOnce('Content limited to 200 characters, remaining: 200 and total 0');

    // Give maxlength.js some time to manipulate the DOM.
    $this->getSession()->wait(1000, 'jQuery("div.counter").is(":visible")');
    $this->assertSession()->waitForElement('css', 'div.counter');

    // Check that only a counter div is found on the page.
    $this->assertSession()->elementsCount('css', 'div.counter', 1);
@@ -66,6 +76,11 @@ class MaxlengthJavascriptTest extends WebDriverTestBase {
    // Check that the counter div follows the description of the field.
    $found = $this->xpath('//div[@data-drupal-selector="edit-foo-0"]/following-sibling::div[@id="edit-foo-0-value-counter"]');
    $this->assertCount(1, $found);

    // Add some text to the field and assert the maxlength counters changed accordingly.
    $this->getSession()->getPage()->fillField('Foo', 'Some text with <strong>html</strong>');

    $this->assertSession()->pageTextContainsOnce('Content limited to 200 characters, remaining: 181 and total 19');
  }

  /**